text
stringlengths
5
1.04M
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <tvm/arith/analyzer.h> #include <tvm/runtime/registry.h> #include <tvm/tir/function.h> #include <tvm/tir/stmt_functor.h> #include <algorithm> #include <unordered_set> #include "../../tir/ir/functor_common.h" #include "../schedule/graph.h" namespace tvm { namespace tir { /*! \brief The helper mutator that transforms ProducerLoad to BufferLoad */ class ProducerToBufferTransformer : public StmtExprMutator { public: explicit ProducerToBufferTransformer(const std::unordered_map<te::Tensor, Buffer>& tensor2buffers) : tensor2buffers_(tensor2buffers) {} PrimExpr VisitExpr_(const ProducerLoadNode* op) final { auto visited_op = Downcast<ProducerLoad>(StmtExprMutator::VisitExpr_(op)); te::Tensor tensor = Downcast<te::Tensor>(visited_op->producer); auto it = tensor2buffers_.find(tensor); ICHECK(it != tensor2buffers_.end()) << "IndexError: Cannot find the tensor " << tensor; const Buffer& buffer = it->second; return BufferLoad(buffer, visited_op->indices); } private: /*! \brief The Map from Operations to buffers */ const std::unordered_map<te::Tensor, Buffer>& tensor2buffers_; }; /*! \brief Helper data structure to store information. */ struct CreateFuncInfo { /*! \brief The Tensor arg_list. */ Array<te::Tensor> arg_list; /*! \brief The map from each Tensor to its corresponding buffer. */ std::unordered_map<te::Tensor, Buffer> tensor2buffers; /*! \brief The transformer from ProducerLoad to BufferLoad. */ ProducerToBufferTransformer transformer; /*! \brief The buffers should be allocated at function root. */ Array<Buffer> root_alloc; /*! \brief The count map to make block name unique. */ std::unordered_map<String, int> name_count; explicit CreateFuncInfo(Array<te::Tensor> arg_list) : arg_list(std::move(arg_list)), transformer(tensor2buffers) {} bool IsArg(const te::Tensor& tensor) const { return std::any_of(arg_list.begin(), arg_list.end(), [&tensor](const te::Tensor& arg) { return tensor == arg; }); } String GetUniqueName(const String& prefix) { String unique_prefix = prefix; auto it = name_count.find(prefix); while (name_count.count(unique_prefix)) { unique_prefix = prefix + "_" + std::to_string(++it->second); } name_count[unique_prefix] = 0; return unique_prefix; } }; class LayoutFreePlaceholdersNormalizer : public StmtMutator { public: PrimFunc Process(PrimFunc func) { for (int i = 0, n = func->params.size(); i < n; ++i) { if (const auto* v = func->params[i].as<VarNode>()) { if (Optional<Buffer> buffer = func->buffer_map.Get(GetRef<Var>(v))) { buffer2index_[buffer.value()] = i; } } } PrimFuncNode* f = func.CopyOnWrite(); f->body = VisitStmt(std::move(f->body)); if (this->layout_free_buffer_indices_.empty()) { return func; } Array<Integer> indices; indices.reserve(this->layout_free_buffer_indices_.size()); for (int i : this->layout_free_buffer_indices_) { indices.push_back(Integer(i)); } return WithAttr(std::move(func), attr, indices); } Stmt VisitStmt_(const BlockNode* _block) final { Block block = Downcast<Block>(StmtMutator::VisitStmt_(_block)); if (Optional<ObjectRef> ann = block->annotations.Get(attr)) { Array<Buffer> buffers = Downcast<Array<Buffer>>(ann); for (Buffer buffer : buffers) { auto it = buffer2index_.find(buffer); if (it != buffer2index_.end()) { layout_free_buffer_indices_.insert(it->second); } } block.CopyOnWrite()->annotations.erase(attr); } return block; } std::unordered_map<tir::Buffer, int, ObjectPtrHash, ObjectPtrEqual> buffer2index_; std::set<int> layout_free_buffer_indices_; String attr = "layout_free_placeholders"; }; BlockRealize GenerateBlockFromTensors(const te::ComputeOp& compute_op, const Array<te::Tensor>& tensors, Array<PrimExpr> bindings, PrimExpr expr_body, CreateFuncInfo* info, arith::Analyzer* analyzer) { // Step 1. Push_back data_par axis and reduce_axis into block_vars. Array<IterVar> iter_vars; std::unordered_map<const VarNode*, PrimExpr> var_map; iter_vars.reserve(compute_op->axis.size() + compute_op->reduce_axis.size()); auto f_push_block_vars = [&iter_vars, &var_map, &analyzer](const Array<IterVar>& iters) { for (IterVar iter_var : iters) { // Create new var Var new_var(iter_var->var->name_hint, iter_var->var->dtype); var_map[iter_var->var.get()] = new_var; const PrimExpr& dom_min = analyzer->Simplify(iter_var->dom->min); const PrimExpr& dom_extent = analyzer->Simplify(iter_var->dom->extent); iter_vars.push_back(IterVar(Range::FromMinExtent(dom_min, dom_extent), new_var, iter_var->iter_type, iter_var->thread_tag, iter_var->span)); } }; f_push_block_vars(compute_op->axis); f_push_block_vars(compute_op->reduce_axis); // Step 2. // - Declare buffers // - Update `op2buffers` // - Add the non-argument tensors to `alloc_buffer` of the root block Array<Buffer> buffers; for (const te::Tensor& tensor : tensors) { Buffer buffer = decl_buffer(tensor->shape, tensor->dtype, tensor->GetNameHint(), "global"); info->tensor2buffers[tensor] = buffer; buffers.push_back(buffer); if (!info->IsArg(tensor)) { info->root_alloc.push_back(info->tensor2buffers[tensor]); } } // Step 3. Calculate indices for BufferStore Array<PrimExpr> indices; indices.reserve(compute_op->axis.size()); for (const IterVar& iter_var : compute_op->axis) { auto it = var_map.find(iter_var->var.get()); ICHECK(it != var_map.end()); indices.push_back(it->second); } // Step 4. Create block body. String block_name{nullptr}; Optional<Stmt> init = NullOpt; Stmt body; if (const auto* reduce = expr_body.as<ReduceNode>()) { // Case 1. Reduce compute block_name = info->GetUniqueName(compute_op->name); int n_buffers = buffers.size(); Array<PrimExpr> lhs; Array<PrimExpr> rhs; lhs.reserve(n_buffers); rhs.reserve(n_buffers); // Make the LHS operands and RHS operands: // - A LHS operand is the buffer storing the reduction result, with corresponding indices. // - A RHS operand is the value to be reduced. for (int i = 0; i < n_buffers; ++i) { const PrimExpr& left = BufferLoad(buffers[i], indices); const PrimExpr& right = analyzer->Simplify(Substitute(info->transformer(reduce->source[i]), var_map)); lhs.push_back(left); rhs.push_back(right); ICHECK_EQ(left->dtype, right->dtype); } Array<Var> temp_vars; Array<Stmt> body_stmts; Array<Stmt> init_stmts; temp_vars.reserve(n_buffers); body_stmts.reserve(n_buffers); init_stmts.reserve(n_buffers); // - When there is only one buffer, we directly create a BufferStore which stores "combiner(lhs, // rhs)" into the target buffer position. // - In case there are multiple buffers, to avoid incorrect results, we create some intermediate // variables and use LetStmts to bind the variables with "combiner(lhs, rhs)". After that, we // then store the value of the variables into the target buffer positions. for (int i = 0; i < n_buffers; ++i) { const Buffer& buffer = buffers[i]; init_stmts.push_back(BufferStore(buffer, reduce->combiner->identity_element[i], indices)); PrimExpr value{nullptr}; if (n_buffers > 1) { temp_vars.push_back(Var("v_" + buffer->name, PrimType(lhs[i].dtype()))); value = temp_vars.back(); } else { value = reduce->combiner.get()->operator()(lhs, rhs)[i]; } body_stmts.push_back(BufferStore(buffer, value, indices)); } init = SeqStmt::Flatten(init_stmts); body = SeqStmt::Flatten(body_stmts); if (n_buffers > 1) { // When there are multiple buffers, we wrap the body with LetStmts. for (int i = n_buffers - 1; i >= 0; --i) { PrimExpr value = reduce->combiner.get()->operator()(lhs, rhs)[i]; body = LetStmt(temp_vars[i], std::move(value), std::move(body)); } } } else { // Case 2. Data parallel compute ICHECK_EQ(tensors.size(), 1); block_name = info->GetUniqueName(tensors[0]->GetNameHint()); const PrimExpr& compute_body = Substitute(info->transformer(expr_body), var_map); body = BufferStore(info->tensor2buffers[tensors[0]], analyzer->Simplify(compute_body), indices); } // Step 5. Add script_parsing_detect_access attr for auto complete the whole IR. Map<String, ObjectRef> annotations; auto mutate_attr = [&info](const ObjectRef& value) -> ObjectRef { if (const auto* tensor_value = value.as<te::TensorNode>()) { return info->tensor2buffers.at(GetRef<te::Tensor>(tensor_value)); } else { return value; } }; for (const auto& pair : compute_op->attrs) { const String& key = pair.first; const ObjectRef& value = pair.second; // TensorIR will not allow Tensor data structure if (value->IsInstance<ArrayNode>()) { const auto array_value = Downcast<Array<ObjectRef>>(value); annotations.Set(key, MutateArray(array_value, mutate_attr)); } else { annotations.Set(key, mutate_attr(value)); } } // Set script_parsing_detect_access annotations.Set(tir::attr::script_parsing_detect_access, IntImm(DataType::Int(32), 3)); // Step 6. Create Block and BlockRealize. return BlockRealize(/*iter_values=*/std::move(bindings), /*predicate=*/Bool(true), /*block=*/ Block(/*iter_vars=*/std::move(iter_vars), /*reads=*/{}, /*writes=*/{}, /*name_hint=*/block_name, /*body=*/std::move(body), /*init=*/std::move(init), /*alloc_buffers=*/{}, /*match_buffers=*/{}, /*annotations=*/std::move(annotations))); } inline bool ReduceEqual(const tir::ReduceNode* a, const tir::ReduceNode* b) { return (a->combiner.same_as(b->combiner)) && (a->source.same_as(b->source)) && (a->axis.same_as(b->axis)) && (a->condition.same_as(b->condition)) && ((a->init.empty() && b->init.empty()) || (a->init.same_as(b->init))); } Stmt GenerateStmtFromCompute(const te::ComputeOp& compute_op, CreateFuncInfo* info, arith::Analyzer* analyzer) { // Step 1. Creating loop vars for block bindings. Array<IterVar> axes = compute_op->axis; axes.insert(axes.end(), compute_op->reduce_axis.begin(), compute_op->reduce_axis.end()); Array<PrimExpr> bindings; for (size_t i = 0; i < axes.size(); ++i) { const IterVar& axis = axes[i]; int bits = std::max(axis->dom->min.dtype().bits(), axis->dom->extent.dtype().bits()); bindings.push_back(Var("i" + std::to_string(i), runtime::DataType::Int(bits))); } // Step 2. Generate block bodies. Array<Stmt> seq_stmt; if (compute_op->body[0]->IsInstance<ReduceNode>()) { auto f_reducer_equal = [](const ReduceNode* a, const ReduceNode* b) -> bool { return a->combiner.same_as(b->combiner) && // a->source.same_as(b->source) && // a->axis.same_as(b->axis) && // a->condition.same_as(b->condition) && // ((a->init.empty() && b->init.empty()) || a->init.same_as(b->init)); }; PrimExpr expr_body = compute_op->body[0]; Array<te::Tensor> tensors = {compute_op.output(0)}; const tir::ReduceNode* reduce = expr_body.as<tir::ReduceNode>(); // specially handle reduction inline for multiplre reductions. for (size_t k = 1; k < compute_op->body.size(); ++k) { const tir::ReduceNode* reduce_ = compute_op->body[k].as<tir::ReduceNode>(); ICHECK(reduce_); ICHECK(f_reducer_equal(reduce_, reduce)) << "The Reduce inputs of ComputeOp should have the same attribute except value_index"; tensors.push_back(compute_op.output(k)); } seq_stmt.push_back(GenerateBlockFromTensors(compute_op, tensors, bindings, std::move(expr_body), info, analyzer)); } else { for (int i = 0; i < compute_op->num_outputs(); ++i) { const te::Tensor& tensor = compute_op.output(i); PrimExpr expr_body = compute_op->body[i]; seq_stmt.push_back(GenerateBlockFromTensors(compute_op, {tensor}, bindings, std::move(expr_body), info, analyzer)); } } Stmt body = SeqStmt::Flatten(seq_stmt); // Step 3. Generate loop nesting. for (size_t i = axes.size(); i > 0; --i) { const IterVar& axis = axes[i - 1]; PrimExpr dom_min = analyzer->Simplify(axis->dom->min); PrimExpr dom_extent = analyzer->Simplify(axis->dom->extent); const Var& loop_var = Downcast<Var>(bindings[i - 1]); body = For(loop_var, dom_min, dom_extent, ForKind::kSerial, body); } return body; } Stmt GenerateStmtFromExternOp(const te::ExternOp& extern_op, CreateFuncInfo* info) { // Step 1. Check all inputs are visited before and update var_map. std::unordered_map<const VarNode*, PrimExpr> var_map; ICHECK_EQ(extern_op->inputs.size(), extern_op->input_placeholders.size()); for (size_t i = 0; i < extern_op->inputs.size(); ++i) { const Buffer& placeholder = extern_op->input_placeholders[i]; const te::Tensor& input_tensor = extern_op->inputs[i]; auto it = info->tensor2buffers.find(input_tensor); ICHECK(it != info->tensor2buffers.end()); var_map[placeholder->data.get()] = it->second->data; } // Step 2. Update info with its output tensor and placeholder buffer. ICHECK_EQ(extern_op->num_outputs(), extern_op->output_placeholders.size()); for (int i = 0; i < extern_op->num_outputs(); ++i) { const Buffer& placeholder = extern_op->output_placeholders[i]; const te::Tensor& output_tensor = extern_op.output(i); info->tensor2buffers[output_tensor] = placeholder; if (!info->IsArg(output_tensor)) { info->root_alloc.push_back(placeholder); } } // Step 3. Collect Access Region Array<BufferRegion> reads, writes; for (const te::Tensor& tensor : extern_op->inputs) { // We have ICHECK before so it is not needed here. reads.push_back(BufferRegion::FullRegion(info->tensor2buffers[tensor])); } for (const Buffer& buffer : extern_op->output_placeholders) { writes.push_back(BufferRegion::FullRegion(buffer)); } Stmt body = Substitute(extern_op->body, var_map); // Step 4. Generate opaque block as body. return BlockRealize(/*iter_values=*/{}, /*predicate=*/Bool(true), /*block=*/ Block(/*iter_vars=*/{}, /*reads=*/std::move(reads), /*writes=*/std::move(writes), /*name_hint=*/info->GetUniqueName(extern_op->name), /*body=*/std::move(body), /*init=*/NullOpt, /*alloc_buffers=*/{}, /*match_buffers=*/{}, /*annotations=*/extern_op->attrs)); } /*! \brief Use Tensor Expression to create a schedulable TensorIR func. */ PrimFunc CreatePrimFunc(const Array<te::Tensor>& arg_list, const Optional<Array<tir::Var>> tir_var_list) { // Step 1. Create tensor read graph. Array<te::Operation> arg_ops; for (const te::Tensor& arg : arg_list) { arg_ops.push_back(arg->op); } te::ReadGraph g = te::CreateReadGraph(arg_ops); Array<te::Operation> order = te::PostDFSOrder(arg_ops, g); // Step 2. Checking all Operations are supported. for (const te::Operation& op : order) { if (!(op->IsInstance<te::PlaceholderOpNode>() || op->IsInstance<te::ComputeOpNode>() || op->IsInstance<te::ExternOpNode>())) LOG(FATAL) << "TypeError: Unsupported Operation: " << op->GetTypeKey() << ". " << "Only te.placeholder and te.compute are allowed for now."; } // Infomations used in CreatePrimFunc and its sub-functions. CreateFuncInfo info(arg_list); // Root body stmts. Array<Stmt> root_stmts; // Analyzer arith::Analyzer analyzer; // Step 3. Rewrite compute stages into blocks. for (const te::Operation& op : order) { if (const auto* placeholder = op.as<te::PlaceholderOpNode>()) { // Case 1. PlaceholderOp (te.placeholder) ICHECK_EQ(op->num_outputs(), 1); const te::Tensor& tensor = op.output(0); // Check op is in op list ICHECK(info.IsArg(tensor)); const Buffer& buffer = decl_buffer(placeholder->shape, placeholder->dtype, placeholder->name, "global"); info.tensor2buffers[tensor] = buffer; } else if (const auto* compute_op = op.as<te::ComputeOpNode>()) { // Case 2. ComputeOp (te.compute) root_stmts.push_back( GenerateStmtFromCompute(GetRef<te::ComputeOp>(compute_op), &info, &analyzer)); } else if (const auto extern_op = op.as<te::ExternOpNode>()) { // Case 3. ExternOp (te.extern) root_stmts.push_back(GenerateStmtFromExternOp(GetRef<te::ExternOp>(extern_op), &info)); } else { ICHECK(false) << "TypeError: Unsupported Operation: " << op->GetTypeKey() << ". " << "Only te.placeholder and te.compute are allowed for now."; } } // Step 4. Create func and complete it. Array<Var> parameters; Map<Var, Buffer> buffer_map; for (const te::Tensor& tensor : arg_list) { Var arg("var_" + tensor->GetNameHint(), PrimType(DataType::Handle())); parameters.push_back(arg); auto it = info.tensor2buffers.find(tensor); ICHECK(it != info.tensor2buffers.end()); buffer_map.Set(arg, it->second); } // add additional arguments for tir vars that are left unbound by match buffer if (tir_var_list) { for (const Var& v : tir_var_list.value()) { parameters.push_back(v); } } PrimFunc func = WithAttrs(PrimFunc(/*params=*/std::move(parameters), /*body=*/SeqStmt::Flatten(root_stmts), /*ret_type=*/VoidType(), /*buffer_map=*/std::move(buffer_map)), {{"global_symbol", String("main")}, {"tir.noalias", Bool(true)}}); const auto* complete = runtime::Registry::Get("script.Complete"); ICHECK(complete); func = (*complete)(func, info.root_alloc); return LayoutFreePlaceholdersNormalizer().Process(std::move(func)); } PrimFunc CreatePrimFuncFromOutputs(const Array<te::Tensor>& outputs) { std::vector<te::Tensor> stack; std::unordered_set<const te::TensorNode*> visited; for (const te::Tensor& output : outputs) { if (!visited.count(output.get())) { visited.insert(output.get()); stack.push_back(output); } } Array<te::Tensor> arg_list; while (!stack.empty()) { te::Tensor tensor = stack.back(); stack.pop_back(); if (tensor->op->IsInstance<te::PlaceholderOpNode>()) { arg_list.push_back(tensor); } else if (tensor->op->IsInstance<te::ComputeOpNode>()) { Array<te::Tensor> inputs = tensor->op->InputTensors(); for (const te::Tensor& input : inputs) { if (!visited.count(input.get())) { visited.insert(input.get()); stack.push_back(input); } } } } for (const te::Tensor& output : outputs) { arg_list.push_back(output); } return CreatePrimFunc(arg_list, {}); } TVM_REGISTER_GLOBAL("te.CreatePrimFunc").set_body_typed(CreatePrimFunc); TVM_REGISTER_GLOBAL("te.CreatePrimFuncFromOutputs").set_body_typed(CreatePrimFuncFromOutputs); } // namespace tir } // namespace tvm
#include <iostream> #include <vector> using namespace std; vector<int> arrayRightRotation(const vector<int> &inputArray, int arraySize, int numberOfRotations) { vector<int> outputArray(arraySize); for (auto i = 0; i < arraySize; ++i) { auto rotatedIndex = ((i - numberOfRotations) % arraySize + arraySize) % arraySize; outputArray[i] = inputArray[rotatedIndex]; } return outputArray; } int main() { int arraySize, numberOfRotations, numberOfQueries; cin >> arraySize >> numberOfRotations >> numberOfQueries; vector<int> inputArray(arraySize); for (auto i = 0; i < arraySize; ++i) { cin >> inputArray[i]; } vector<int> outputArray = arrayRightRotation(inputArray, arraySize, numberOfRotations); for (auto i = 0; i < numberOfQueries; ++i) { int m; cin >> m; cout << outputArray[m] << endl; } return 0; }
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // Please refer to the license text that comes with this tendis open source // project for additional information. #include <string> #include <utility> #include <memory> #include <algorithm> #include <cctype> #include <clocale> #include <vector> #include <list> #include "glog/logging.h" #include "tendisplus/utils/sync_point.h" #include "tendisplus/utils/string.h" #include "tendisplus/utils/invariant.h" #include "tendisplus/utils/redis_port.h" #include "tendisplus/commands/command.h" namespace tendisplus { Expected<std::string> hincrfloatGeneric(Session* sess, const RecordKey& metaRk, const Expected<RecordValue>& eValue, const RecordKey& subRk, long double inc, PStore kvstore) { auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } if (!eValue.ok() && eValue.status().code() != ErrorCodes::ERR_NOTFOUND && eValue.status().code() != ErrorCodes::ERR_EXPIRED) { return eValue.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); } // no else, else not found , so subkeyCount = 0, ttl = 0 auto getSubkeyExpt = kvstore->getKV(subRk, ptxn.value()); long double nowVal = 0; if (getSubkeyExpt.ok()) { Expected<long double> val = ::tendisplus::stold(getSubkeyExpt.value().getValue()); if (!val.ok()) { return {ErrorCodes::ERR_DECODE, "hash value is not a valid float"}; } nowVal = val.value(); } else if (getSubkeyExpt.status().code() == ErrorCodes::ERR_NOTFOUND) { nowVal = 0; hashMeta.setCount(hashMeta.getCount() + 1); } else { return getSubkeyExpt.status(); } nowVal += inc; RecordValue newVal( ::tendisplus::ldtos(nowVal, true), RecordType::RT_HASH_ELE, -1); RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); Status setStatus = kvstore->setKV(metaRk, metaValue, ptxn.value()); if (!setStatus.ok()) { return setStatus; } setStatus = kvstore->setKV(subRk, newVal, ptxn.value()); if (!setStatus.ok()) { return setStatus; } Expected<uint64_t> exptCommit = sess->getCtx()->commitTransaction( ptxn.value()); if (!exptCommit.ok()) { return exptCommit.status(); } else { return Command::fmtBulk(tendisplus::ldtos(nowVal, true)); } } Expected<std::string> hincrGeneric(Session* sess, const RecordKey& metaRk, const Expected<RecordValue>& eValue, const RecordKey& subRk, int64_t inc, PStore kvstore) { auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } if (!eValue.ok() && eValue.status().code() != ErrorCodes::ERR_NOTFOUND && eValue.status().code() != ErrorCodes::ERR_EXPIRED) { return eValue.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); } // no else, else not found , so subkeyCount = 0, ttl = 0 auto getSubkeyExpt = kvstore->getKV(subRk, ptxn.value()); int64_t nowVal = 0; if (getSubkeyExpt.ok()) { Expected<int64_t> val = ::tendisplus::stoll(getSubkeyExpt.value().getValue()); if (!val.ok()) { return {ErrorCodes::ERR_DECODE, "hash value is not an integer "}; } nowVal = val.value(); } else if (getSubkeyExpt.status().code() == ErrorCodes::ERR_NOTFOUND) { nowVal = 0; hashMeta.setCount(hashMeta.getCount() + 1); } else { return getSubkeyExpt.status(); } if ((inc < 0 && nowVal < 0 && inc < (LLONG_MIN - nowVal)) || (inc > 0 && nowVal > 0 && inc > (LLONG_MAX - nowVal))) { return {ErrorCodes::ERR_OVERFLOW, "increment or decrement would overflow"}; } nowVal += inc; RecordValue newVal(std::to_string(nowVal), RecordType::RT_HASH_ELE, -1); RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); Status setStatus = kvstore->setKV(metaRk, metaValue, ptxn.value()); if (!setStatus.ok()) { return setStatus; } setStatus = kvstore->setKV(subRk, newVal, ptxn.value()); if (!setStatus.ok()) { return setStatus; } Expected<uint64_t> exptCommit = sess->getCtx()->commitTransaction( ptxn.value()); if (!exptCommit.ok()) { return exptCommit.status(); } else { return Command::fmtLongLong(nowVal); } } class HLenCommand : public Command { public: HLenCommand() : Command("hlen", "rF") {} ssize_t arity() const { return 2; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_EXPIRED) { return fmtZero(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { return fmtZero(); } else if (!rv.status().ok()) { return rv.status(); } Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(rv.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } return fmtLongLong(exptHashMeta.value().getCount()); } } hlenCommand; class HExistsCommand : public Command { public: HExistsCommand() : Command("hexists", "rF") {} ssize_t arity() const { return 3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; const std::string& subkey = args[2]; SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock(sess, key, Command::RdLock()); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_EXPIRED) { return Command::fmtNull(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { return Command::fmtNull(); } else if (!rv.status().ok()) { return rv.status(); } RecordKey subRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, subkey); PStore kvstore = expdb.value().store; auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } Expected<RecordValue> eVal = kvstore->getKV(subRk, ptxn.value()); if (eVal.ok()) { return Command::fmtOne(); } else if (eVal.status().code() == ErrorCodes::ERR_NOTFOUND) { return Command::fmtZero(); } else { return eVal.status(); } } } hexistsCmd; class HAllCommand : public Command { public: explicit HAllCommand(const std::string& name, const char* sflags) : Command(name, sflags) {} ssize_t arity() const { return 2; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::list<Record>> getRecords(Session* sess) { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock(sess, key, Command::RdLock()); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_EXPIRED) { return std::list<Record>(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { return std::list<Record>(); } else if (!rv.status().ok()) { return rv.status(); } RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); // uint32_t storeId = expdb.value().dbId; PStore kvstore = expdb.value().store; auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } RecordKey fakeEle(expdb.value().chunkId, metaRk.getDbId(), RecordType::RT_HASH_ELE, metaRk.getPrimaryKey(), ""); std::string prefix = fakeEle.prefixPk(); auto cursor = ptxn.value()->createDataCursor(); cursor->seek(prefix); std::list<Record> result; while (true) { Expected<Record> exptRcd = cursor->next(); if (exptRcd.status().code() == ErrorCodes::ERR_EXHAUST) { break; } if (!exptRcd.ok()) { return exptRcd.status(); } Record& rcd = exptRcd.value(); const RecordKey& rcdKey = rcd.getRecordKey(); if (rcdKey.prefixPk() != prefix) { break; } result.emplace_back(std::move(rcd)); } return std::move(result); } }; class HGetAllCommand : public HAllCommand { public: HGetAllCommand() : HAllCommand("hgetall", "r") {} Expected<std::string> run(Session* sess) final { Expected<std::list<Record>> rcds = getRecords(sess); if (!rcds.ok()) { return rcds.status(); } std::stringstream ss; Command::fmtMultiBulkLen(ss, rcds.value().size() * 2); for (const auto& v : rcds.value()) { Command::fmtBulk(ss, v.getRecordKey().getSecondaryKey()); Command::fmtBulk(ss, v.getRecordValue().getValue()); } return ss.str(); } } hgetAllCmd; class HKeysCommand : public HAllCommand { public: HKeysCommand() : HAllCommand("hkeys", "rS") {} Expected<std::string> run(Session* sess) final { Expected<std::list<Record>> rcds = getRecords(sess); if (!rcds.ok()) { return rcds.status(); } std::stringstream ss; Command::fmtMultiBulkLen(ss, rcds.value().size()); for (const auto& v : rcds.value()) { Command::fmtBulk(ss, v.getRecordKey().getSecondaryKey()); } return ss.str(); } } hkeysCmd; class HValsCommand : public HAllCommand { public: HValsCommand() : HAllCommand("hvals", "rS") {} Expected<std::string> run(Session* sess) final { Expected<std::list<Record>> rcds = getRecords(sess); if (!rcds.ok()) { return rcds.status(); } std::stringstream ss; Command::fmtMultiBulkLen(ss, rcds.value().size()); for (const auto& v : rcds.value()) { Command::fmtBulk(ss, v.getRecordValue().getValue()); } return ss.str(); } } hvalsCmd; class HGetRecordCommand : public Command { public: explicit HGetRecordCommand(const std::string& name, const char* sflags) : Command(name, sflags) {} ssize_t arity() const { return 3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<Record> getRecord(Session* sess) { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; const std::string& subkey = args[2]; SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock(sess, key, Command::RdLock()); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_EXPIRED) { return rv.status(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { return rv.status(); } else if (!rv.status().ok()) { return rv.status(); } RecordKey subRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, subkey); PStore kvstore = expdb.value().store; auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } Expected<RecordValue> eVal = kvstore->getKV(subRk, ptxn.value()); if (eVal.ok()) { return std::move(Record(std::move(subRk), std::move(eVal.value()))); } else { return eVal.status(); } } }; class HGetCommand : public HGetRecordCommand { public: HGetCommand() : HGetRecordCommand("hget", "rF") {} ssize_t arity() const { return 3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { Expected<Record> ercd = getRecord(sess); if (ercd.status().code() == ErrorCodes::ERR_NOTFOUND) { return Command::fmtNull(); } else if (ercd.status().code() == ErrorCodes::ERR_EXPIRED) { return Command::fmtNull(); } else if (!ercd.ok()) { return ercd.status(); } return Command::fmtBulk(ercd.value().getRecordValue().getValue()); } } hgetCommand; class HStrlenCommand : public HGetRecordCommand { public: HStrlenCommand() : HGetRecordCommand("hstrlen", "rF") {} ssize_t arity() const { return 3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { Expected<Record> ercd = getRecord(sess); if (ercd.status().code() == ErrorCodes::ERR_NOTFOUND) { return Command::fmtZero(); } else if (ercd.status().code() == ErrorCodes::ERR_EXPIRED) { return Command::fmtZero(); } else if (!ercd.ok()) { return ercd.status(); } uint64_t size = ercd.value().getRecordValue().getValue().size(); return Command::fmtLongLong(size); } } hstrlenCommand; class HIncrByFloatCommand : public Command { public: HIncrByFloatCommand() : Command("hincrbyfloat", "wmF") {} ssize_t arity() const { return 4; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; const std::string& subkey = args[2]; const std::string& val = args[3]; Expected<long double> inc = ::tendisplus::stold(val); if (!inc.ok()) { return inc.status(); } auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock( sess, key, mgl::LockMode::LOCK_X); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() != ErrorCodes::ERR_OK && rv.status().code() != ErrorCodes::ERR_EXPIRED && rv.status().code() != ErrorCodes::ERR_NOTFOUND) { return rv.status(); } SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); RecordKey subRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, subkey); PStore kvstore = expdb.value().store; // now, we have no need to deal with expire, though it may still // be expired in a very rare situation since expireHash is in // a seperate txn (from code below) // if (Command::isKeyLocked(sess, storeId, metaKeyEnc)) { // return {ErrorCodes::ERR_BUSY, "key locked"}; // } // here maybe one more time io than the original tendis for (int32_t i = 0; i < RETRY_CNT - 1; ++i) { auto result = hincrfloatGeneric(sess, metaRk, rv, subRk, inc.value(), kvstore); if (result.status().code() != ErrorCodes::ERR_COMMIT_RETRY) { return result; } } return hincrfloatGeneric(sess, metaRk, rv, subRk, inc.value(), kvstore); } } hincrbyfloatCmd; class HIncrByCommand : public Command { public: HIncrByCommand() : Command("hincrby", "wmF") {} ssize_t arity() const { return 4; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; const std::string& subkey = args[2]; const std::string& val = args[3]; Expected<int64_t> inc = ::tendisplus::stoll(val); if (!inc.ok()) { return inc.status(); } auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock( sess, key, mgl::LockMode::LOCK_X); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() != ErrorCodes::ERR_OK && rv.status().code() != ErrorCodes::ERR_EXPIRED && rv.status().code() != ErrorCodes::ERR_NOTFOUND) { return rv.status(); } SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); // uint32_t storeId = expdb.value().dbId; RecordKey subRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, subkey); PStore kvstore = expdb.value().store; // now, we have no need to deal with expire, though it may still // be expired in a very rare situation since expireHash is in // a seperate txn (from code below) // if (Command::isKeyLocked(sess, storeId, metaKeyEnc)) { // return {ErrorCodes::ERR_BUSY, "key locked"}; // } // here maybe one more time io than the original tendis for (int32_t i = 0; i < RETRY_CNT - 1; ++i) { auto result = hincrGeneric(sess, metaRk, rv, subRk, inc.value(), kvstore); if (result.status().code() != ErrorCodes::ERR_COMMIT_RETRY) { return result; } } return hincrGeneric(sess, metaRk, rv, subRk, inc.value(), kvstore); } } hincrbyCommand; class HMGetGeneric : public Command { public: HMGetGeneric(const std::string& name, const char* sflags) : Command(name, sflags) { if (name == "hmget") { _returnVsn = false; } else { // hmgetvsn _returnVsn = true; } } ssize_t arity() const { return -3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock(sess, key, Command::RdLock()); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_NOTFOUND || rv.status().code() == ErrorCodes::ERR_EXPIRED) { std::stringstream ss; if (_returnVsn) { Command::fmtMultiBulkLen(ss, args.size() - 1); Command::fmtNull(ss); } else { Command::fmtMultiBulkLen(ss, args.size() - 2); } for (size_t i = 2; i < args.size(); ++i) { Command::fmtNull(ss); } return ss.str(); } else if (!rv.ok()) { return rv.status(); } SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); PStore kvstore = expdb.value().store; auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } std::stringstream ss; if (_returnVsn) { Command::fmtMultiBulkLen(ss, args.size() - 1); Command::fmtBulk(ss, std::to_string(rv.value().getCas())); } else { Command::fmtMultiBulkLen(ss, args.size() - 2); } for (size_t i = 2; i < args.size(); ++i) { RecordKey subKey(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, args[i]); Expected<RecordValue> eValue = kvstore->getKV(subKey, ptxn.value()); if (!eValue.ok()) { if (eValue.status().code() == ErrorCodes::ERR_NOTFOUND) { Command::fmtNull(ss); } else { return eValue.status(); } } else { Command::fmtBulk(ss, eValue.value().getValue()); } } return ss.str(); } private: bool _returnVsn; }; class HMGetCommand : public HMGetGeneric { public: HMGetCommand() : HMGetGeneric("hmget", "rF") {} } hmgetCmd; class HMGetVsnCommand : public HMGetGeneric { public: HMGetVsnCommand() : HMGetGeneric("hmgetvsn", "r") {} } hmgetvsnCmd; Status hmcas(Session* sess, const std::string& key, const std::vector<std::string>& subargs, uint64_t cmp, int64_t vsn, const Expected<int64_t>& newvsn) { SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock(sess, key, Command::RdLock()); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> eValue = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (eValue.status().code() != ErrorCodes::ERR_OK && eValue.status().code() != ErrorCodes::ERR_EXPIRED && eValue.status().code() != ErrorCodes::ERR_NOTFOUND) { return eValue.status(); } RecordKey metaRk( expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); PStore kvstore = expdb.value().store; auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; int64_t cas = -1; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); cas = eValue.value().getCas(); } // no else, else not found , so subkeyCount = 0, ttl = 0, cas = 0 if (cmp) { // kv should exist for comparison if (eValue.ok() && (int64_t)vsn != cas && cas != -1) { return {ErrorCodes::ERR_CAS, ""}; } } std::map<std::string, uint64_t> uniqkeys; std::map<std::string, std::string> existkvs; for (size_t i = 0; i < subargs.size(); i += 3) { std::string subk = subargs[i]; uniqkeys[subk] = i; } constexpr int OPSET = 0; constexpr int OPADD = 1; for (const auto& keyPos : uniqkeys) { bool exists = true; RecordKey rk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, keyPos.first); Expected<RecordValue> rv = kvstore->getKV(rk, ptxn.value()); if (rv.ok()) { existkvs[keyPos.first] = rv.value().getValue(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { exists = false; } else { return rv.status(); } const std::string& opstr = subargs[keyPos.second + 1]; Expected<uint64_t> eop = ::tendisplus::stoul(opstr); if (!eop.ok()) { return eop.status(); } RecordKey subrk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, keyPos.first); if (eop.value() == OPSET || (!exists && eop.value() == OPADD)) { RecordValue subrv( subargs[keyPos.second + 2], RecordType::RT_HASH_ELE, -1); Status s = kvstore->setKV(subrk, subrv, ptxn.value()); if (!s.ok()) { return s; } } else if (eop.value() == OPADD) { Expected<int64_t> ev = ::tendisplus::stoll(existkvs[keyPos.first]); if (!ev.ok()) { return ev.status(); } Expected<int64_t> ev1 = ::tendisplus::stoll(subargs[keyPos.second + 2]); if (!ev1.ok()) { return ev1.status(); } RecordValue subrv( std::to_string(ev1.value() + ev.value()), RecordType::RT_HASH_ELE, -1); Status s = kvstore->setKV(subrk, subrv, ptxn.value()); if (!s.ok()) { return s; } } else { return {ErrorCodes::ERR_UNKNOWN, ""}; } } if (newvsn.ok()) { cas = newvsn.value(); } else { if (cmp) { // if the kv does not exist before, use user passed cas if (eValue.ok() && cas != -1) { cas += 1; } else { cas = vsn + 1; } } else { cas = vsn + 1; } } hashMeta.setCount(hashMeta.getCount() + uniqkeys.size() - existkvs.size()); RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); metaValue.setCas(cas); Status s = kvstore->setKV(metaRk, metaValue, ptxn.value()); if (!s.ok()) { return s; } auto commitStat = sess->getCtx()->commitTransaction(ptxn.value()); return commitStat.status(); } class HMCasV2Command : public Command { public: HMCasV2Command() : Command("hmcasv2", "w") {} ssize_t arity() const { return -8; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); if ((args.size() - 5) % 3 != 0) { return {ErrorCodes::ERR_PARSEOPT, "wrong number of arguments for hmcas"}; } const std::string& key = args[1]; Expected<uint64_t> ecmp = ::tendisplus::stoull(args[2]); if (!ecmp.ok()) { return ecmp.status(); } Expected<int64_t> evsn = ::tendisplus::stoll(args[3]); if (!evsn.ok()) { return evsn.status(); } Expected<int64_t> enewvsn = ::tendisplus::stoll(args[4]); if (!enewvsn.ok()) { return enewvsn.status(); } uint64_t cmp = ecmp.value(); int64_t vsn = evsn.value(); int64_t newvsn = enewvsn.value(); if (cmp != 0 && cmp != 1) { return {ErrorCodes::ERR_PARSEOPT, "cmp should be 0 or 1"}; } auto server = sess->getServerEntry(); if (server->versionIncrease()) { if (newvsn <= vsn && cmp) { return {ErrorCodes::ERR_PARSEOPT, "new version must be greater than old version"}; } } std::vector<std::string> subargs; for (size_t i = 5; i < args.size(); ++i) { subargs.push_back(args[i]); } for (uint32_t i = 0; i < RETRY_CNT; ++i) { Status s = hmcas(sess, key, subargs, cmp, vsn, newvsn); if (!s.ok()) { if (s.code() == ErrorCodes::ERR_CAS) { return Command::fmtZero(); } else if (s.code() == ErrorCodes::ERR_COMMIT_RETRY) { if (i == RETRY_CNT - 1) { return s; } else { continue; } } else { return s; } } else { return Command::fmtOne(); } } INVARIANT_D(0); return {ErrorCodes::ERR_INTERNAL, "never reaches here"}; } } hmcasV2Cmd; class HMCasCommand : public Command { public: HMCasCommand() : Command("hmcas", "w") {} ssize_t arity() const { return -7; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); if ((args.size() - 4) % 3 != 0) { return {ErrorCodes::ERR_PARSEOPT, "wrong number of arguments for hmcas"}; } const std::string& key = args[1]; Expected<uint64_t> ecmp = ::tendisplus::stoul(args[2]); if (!ecmp.ok()) { return ecmp.status(); } Expected<int64_t> evsn = ::tendisplus::stoll(args[3]); if (!evsn.ok()) { return evsn.status(); } uint64_t cmp = ecmp.value(); int64_t vsn = evsn.value(); if (cmp != 0 && cmp != 1) { return {ErrorCodes::ERR_PARSEOPT, "cmp should be 0 or 1"}; } std::vector<std::string> subargs; for (size_t i = 4; i < args.size(); ++i) { subargs.push_back(args[i]); } for (uint32_t i = 0; i < RETRY_CNT; ++i) { Status s = hmcas(sess, key, subargs, cmp, vsn, {ErrorCodes::ERR_NOTFOUND, ""}); if (!s.ok()) { if (s.code() == ErrorCodes::ERR_CAS) { return Command::fmtZero(); } else if (s.code() == ErrorCodes::ERR_COMMIT_RETRY) { if (i == RETRY_CNT - 1) { return s; } else { continue; } } else { return s; } } else { return Command::fmtOne(); } } INVARIANT_D(0); return {ErrorCodes::ERR_INTERNAL, "never reaches here"}; } } hmcasCmd; class HMSetGeneric : public Command { public: HMSetGeneric(const std::string& name, const char* sflags) : Command(name, sflags) {} ssize_t arity() const { return -4; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> hmsetGeneric(Session* sess, const RecordKey& metaRk, const Expected<RecordValue>& eValue, const std::vector<Record>& rcds, PStore kvstore) { auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; uint32_t inserted = 0; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); } // no else, else not found , so subkeyCount = 0, ttl = 0 for (const auto& v : rcds) { auto getSubkeyExpt = kvstore->getKV(v.getRecordKey(), ptxn.value()); if (!getSubkeyExpt.ok()) { if (getSubkeyExpt.status().code() != ErrorCodes::ERR_NOTFOUND) { return getSubkeyExpt.status(); } inserted += 1; } Status setStatus = kvstore->setKV(v.getRecordKey(), v.getRecordValue(), ptxn.value()); if (!setStatus.ok()) { return setStatus; } } hashMeta.setCount(hashMeta.getCount() + inserted); RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); metaValue.setCas(-1); Status setStatus = kvstore->setKV(metaRk, metaValue, ptxn.value()); if (!setStatus.ok()) { return setStatus; } Expected<uint64_t> exptCommit = sess->getCtx()->commitTransaction( ptxn.value()); if (!exptCommit.ok()) { return exptCommit.status(); } else { if (getName() == "hmset") { return Command::fmtOK(); } else { // hset return Command::fmtLongLong(inserted); } } } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; if (args.size() % 2 != 0) { return {ErrorCodes::ERR_WRONG_ARGS_SIZE, ""}; } auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock( sess, key, mgl::LockMode::LOCK_X); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() != ErrorCodes::ERR_OK && rv.status().code() != ErrorCodes::ERR_EXPIRED && rv.status().code() != ErrorCodes::ERR_NOTFOUND) { return rv.status(); } SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); PStore kvstore = expdb.value().store; std::vector<Record> rcds; for (size_t i = 2; i < args.size(); i += 2) { RecordKey subKey(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, args[i]); RecordValue subRv(args[i + 1], RecordType::RT_HASH_ELE, -1); rcds.emplace_back(Record(std::move(subKey), std::move(subRv))); } for (int32_t i = 0; i < RETRY_CNT - 1; ++i) { auto result = hmsetGeneric(sess, metaRk, rv, rcds, kvstore); if (result.status().code() != ErrorCodes::ERR_COMMIT_RETRY) { return result; } } return hmsetGeneric(sess, metaRk, rv, rcds, kvstore); } }; class HMSetCommand : public HMSetGeneric { public: HMSetCommand() : HMSetGeneric("hmset", "wmF") {} } hmsetcmd; class HSetGeneric : public Command { public: HSetGeneric(const std::string& name, const char* sflags, bool setNx) : Command(name, sflags) { _setNx = setNx; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; const std::string& subkey = args[2]; const std::string& val = args[3]; SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock( sess, key, mgl::LockMode::LOCK_X); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() != ErrorCodes::ERR_OK && rv.status().code() != ErrorCodes::ERR_EXPIRED && rv.status().code() != ErrorCodes::ERR_NOTFOUND) { return rv.status(); } RecordKey metaKey(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); PStore kvstore = expdb.value().store; RecordKey subKey(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, subkey); RecordValue subRv(val, RecordType::RT_HASH_ELE, -1); // now, we have no need to deal with expire, though it may still // be expired in a very rare situation since expireHash is in // a seperate txn (from code below) // if (Command::isKeyLocked(sess, storeId, metaKeyEnc)) { // return {ErrorCodes::ERR_BUSY, "key locked"}; // } // here maybe one more time io than the original tendis for (int32_t i = 0; i < RETRY_CNT - 1; ++i) { auto result = hsetGeneric(sess, metaKey, rv, subKey, subRv, kvstore); if (result.status().code() != ErrorCodes::ERR_COMMIT_RETRY) { return result; } } return hsetGeneric(sess, metaKey, rv, subKey, subRv, kvstore); } Expected<std::string> hsetGeneric(Session* sess, const RecordKey& metaRk, const Expected<RecordValue>& eValue, const RecordKey& subRk, const RecordValue& subRv, PStore kvstore) { auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); } // no else, else not found , so subkeyCount = 0, ttl = 0 bool updated = false; auto getSubkeyExpt = kvstore->getKV(subRk, ptxn.value()); if (getSubkeyExpt.ok()) { updated = true; } else if (getSubkeyExpt.status().code() == ErrorCodes::ERR_NOTFOUND) { updated = false; hashMeta.setCount(hashMeta.getCount() + 1); } else { return getSubkeyExpt.status(); } if (_setNx && updated) { return Command::fmtZero(); } RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); Status setStatus = kvstore->setKV(metaRk, metaValue, ptxn.value()); if (!setStatus.ok()) { return setStatus; } setStatus = kvstore->setKV(subRk, subRv, ptxn.value()); if (!setStatus.ok()) { return setStatus; } Expected<uint64_t> exptCommit = sess->getCtx()->commitTransaction( ptxn.value()); if (!exptCommit.ok()) { return exptCommit.status(); } else { return updated ? Command::fmtZero() : Command::fmtOne(); } } private: bool _setNx; }; class HSetCommand : public HMSetGeneric { public: HSetCommand() : HMSetGeneric("hset", "wmF") {} } hsetCommand; class HSetNxCommand : public HSetGeneric { public: HSetNxCommand() : HSetGeneric("hsetnx", "wmF", true) {} ssize_t arity() const { return 4; } } hsetNxCommand; class HDelCommand : public Command { public: HDelCommand() : Command("hdel", "wF") {} ssize_t arity() const { return -3; } int32_t firstkey() const { return 1; } int32_t lastkey() const { return 1; } int32_t keystep() const { return 1; } Expected<uint32_t> delKeys(Session* sess, PStore kvstore, const RecordKey& metaKey, const Expected<RecordValue>& eValue, const std::vector<std::string>& args, Transaction* txn) { uint32_t dbId = metaKey.getDbId(); uint32_t realDel = 0; if (eValue.status().code() == ErrorCodes::ERR_NOTFOUND || eValue.status().code() == ErrorCodes::ERR_EXPIRED) { return 0; } if (!eValue.ok()) { return eValue.status(); } HashMetaValue hashMeta; uint64_t ttl = 0; if (eValue.ok()) { ttl = eValue.value().getTtl(); Expected<HashMetaValue> exptHashMeta = HashMetaValue::decode(eValue.value().getValue()); if (!exptHashMeta.ok()) { return exptHashMeta.status(); } hashMeta = std::move(exptHashMeta.value()); } // no else, else not found , so subkeyCount = 0, ttl = 0 for (size_t i = 2; i < args.size(); ++i) { RecordKey subRk(metaKey.getChunkId(), dbId, RecordType::RT_HASH_ELE, metaKey.getPrimaryKey(), args[i]); Expected<RecordValue> eVal = kvstore->getKV(subRk, txn); if (eVal.status().code() == ErrorCodes::ERR_NOTFOUND) { continue; } if (!eVal.ok()) { return eVal.status(); } Status s = kvstore->delKV(subRk, txn); if (!s.ok()) { return s; } realDel++; } // modify meta data INVARIANT_D(realDel <= hashMeta.getCount()); Status s; if (realDel >= hashMeta.getCount()) { if (realDel > hashMeta.getCount()) { LOG(ERROR) << "invalid hashmeta of " << metaKey.getPrimaryKey(); } s = Command::delKeyAndTTL(sess, metaKey, eValue.value(), txn); } else { hashMeta.setCount(hashMeta.getCount() - realDel); RecordValue metaValue(hashMeta.encode(), RecordType::RT_HASH_META, sess->getCtx()->getVersionEP(), ttl, eValue); s = kvstore->setKV(metaKey, metaValue, txn); } if (!s.ok()) { return s; } Expected<uint64_t> commitStatus = sess->getCtx()->commitTransaction(txn); if (!commitStatus.ok()) { return commitStatus.status(); } return realDel; } Expected<std::string> run(Session* sess) final { const std::vector<std::string>& args = sess->getArgs(); const std::string& key = args[1]; auto server = sess->getServerEntry(); auto expdb = server->getSegmentMgr()->getDbWithKeyLock( sess, key, mgl::LockMode::LOCK_X); if (!expdb.ok()) { return expdb.status(); } Expected<RecordValue> rv = Command::expireKeyIfNeeded(sess, key, RecordType::RT_HASH_META); if (rv.status().code() == ErrorCodes::ERR_EXPIRED) { return fmtZero(); } else if (rv.status().code() == ErrorCodes::ERR_NOTFOUND) { return fmtZero(); } else if (!rv.status().ok()) { return rv.status(); } SessionCtx* pCtx = sess->getCtx(); INVARIANT(pCtx != nullptr); RecordKey metaRk(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_META, key, ""); PStore kvstore = expdb.value().store; std::vector<RecordKey> rcds; for (size_t i = 2; i < args.size(); ++i) { rcds.emplace_back(RecordKey(expdb.value().chunkId, pCtx->getDbId(), RecordType::RT_HASH_ELE, key, args[i])); } for (uint32_t i = 0; i < RETRY_CNT; ++i) { auto ptxn = sess->getCtx()->createTransaction(kvstore); if (!ptxn.ok()) { return ptxn.status(); } Expected<uint32_t> delCount = delKeys(sess, kvstore, metaRk, rv, args, ptxn.value()); if (delCount.status().code() == ErrorCodes::ERR_COMMIT_RETRY) { if (i == RETRY_CNT - 1) { return delCount.status(); } else { continue; } } if (!delCount.ok()) { return delCount.status(); } return Command::fmtLongLong(delCount.value()); } // never reaches here INVARIANT_D(0); return {ErrorCodes::ERR_INTERNAL, "never reaches here"}; } } hdelCommand; } // namespace tendisplus
#include "fps_controller.h" #include "Dxlib.h" namespace game::fps { FPSController::FPSController() : startTime_(0), count_(0), fps_(0) {} FPSController::~FPSController() {} void FPSController::update() { if (count_ == 0) startTime_ = GetNowCount(); else if (count_ == N) { int t = GetNowCount(); fps_ = 1000.f / ((t - startTime_) / (float)N); count_ = 0; startTime_ = t; } count_++; } void FPSController::draw() const { DrawFormatString(700, 580, grayColor_, "%.2f", fps_); } void FPSController::wait() const { int tookTime = GetNowCount() - startTime_; int waitTime = count_ * 1000 / FPS - tookTime; if (waitTime > 0) Sleep(waitTime); } }
/* * Copyright (C) 2015 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 "field-inl.h" #include "class-inl.h" #include "dex_cache-inl.h" #include "object_array-inl.h" #include "object-inl.h" namespace art { namespace mirror { GcRoot<Class> Field::static_class_; GcRoot<Class> Field::array_class_; void Field::SetClass(Class* klass) { CHECK(static_class_.IsNull()) << static_class_.Read() << " " << klass; CHECK(klass != nullptr); static_class_ = GcRoot<Class>(klass); } void Field::ResetClass() { CHECK(!static_class_.IsNull()); static_class_ = GcRoot<Class>(nullptr); } void Field::SetArrayClass(Class* klass) { CHECK(array_class_.IsNull()) << array_class_.Read() << " " << klass; CHECK(klass != nullptr); array_class_ = GcRoot<Class>(klass); } void Field::ResetArrayClass() { CHECK(!array_class_.IsNull()); array_class_ = GcRoot<Class>(nullptr); } void Field::VisitRoots(RootVisitor* visitor) { static_class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass)); array_class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass)); } ArtField* Field::GetArtField() { mirror::Class* declaring_class = GetDeclaringClass(); if (UNLIKELY(declaring_class->IsProxyClass())) { DCHECK(IsStatic()); DCHECK_EQ(declaring_class->NumStaticFields(), 2U); // 0 == Class[] interfaces; 1 == Class[][] throws; if (GetDexFieldIndex() == 0) { return &declaring_class->GetSFieldsPtr()->At(0); } else { DCHECK_EQ(GetDexFieldIndex(), 1U); return &declaring_class->GetSFieldsPtr()->At(1); } } mirror::DexCache* const dex_cache = declaring_class->GetDexCache(); ArtField* const art_field = dex_cache->GetResolvedField(GetDexFieldIndex(), sizeof(void*)); CHECK(art_field != nullptr); CHECK_EQ(declaring_class, art_field->GetDeclaringClass()); return art_field; } } // namespace mirror } // namespace art
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by app BSD-style license that can be // found in the LICENSE file. #include "intl_wisdom_server_impl.h" #include <lib/sys/cpp/component_context.h> #include <zircon/assert.h> #include <iostream> #include <sstream> #include "src/lib/icu_data/cpp/icu_data.h" #include "third_party/icu/source/common/unicode/unistr.h" #include "third_party/icu/source/i18n/unicode/calendar.h" #include "third_party/icu/source/i18n/unicode/datefmt.h" #include "third_party/icu/source/i18n/unicode/timezone.h" namespace intl_wisdom { using fuchsia::intl::CalendarId; using fuchsia::intl::LocaleId; using fuchsia::intl::TimeZoneId; using icu::Calendar; using icu::DateFormat; using icu::Locale; using icu::TimeZone; using icu::UnicodeString; using AskForWisdomCallback = fuchsia::examples::intl::wisdom::IntlWisdomServer::AskForWisdomCallback; using fuchsia::intl::Profile; namespace { const Locale LocaleIdToLocale(const std::string locale_id) { return Locale::createCanonical(locale_id.c_str()); } const Locale LocaleIdToLocale(const LocaleId& locale_id) { return LocaleIdToLocale(locale_id.id); } std::unique_ptr<TimeZone> TimeZoneIdToTimeZone(const TimeZoneId& time_zone_id) { return std::unique_ptr<TimeZone>( TimeZone::createTimeZone(UnicodeString::fromUTF8(time_zone_id.id))); } std::unique_ptr<Calendar> CalendarIdToCalendar(const CalendarId& calendar_id, const TimeZone& time_zone) { // Calendar ID strings are just locale IDs with an undefined language Locale as_locale = LocaleIdToLocale(calendar_id.id); UErrorCode error_code = U_ZERO_ERROR; return std::unique_ptr<Calendar>( Calendar::createInstance(time_zone, as_locale, error_code)); } } // namespace IntlWisdomServerImpl::IntlWisdomServerImpl( std::unique_ptr<sys::ComponentContext> startup_context) : startup_context_(std::move(startup_context)) { ZX_ASSERT(icu_data::Initialize() == ZX_OK); startup_context_->outgoing()->AddPublicService(bindings_.GetHandler(this)); } void IntlWisdomServerImpl::AskForWisdom(Profile intl_profile, int64_t timestamp_ms, AskForWisdomCallback callback) { // Parse the requested locale IDs auto& locale_ids = intl_profile.locales(); std::vector<Locale> locales; std::transform( locale_ids.begin(), locale_ids.end(), std::back_inserter(locales), [](LocaleId locale_id) { return LocaleIdToLocale(locale_id); }); std::unique_ptr<TimeZone> time_zone; if (intl_profile.time_zones().size() > 0) { time_zone = TimeZoneIdToTimeZone(intl_profile.time_zones()[0]); } else { time_zone = std::unique_ptr<TimeZone>(TimeZone::detectHostTimeZone()); } // Parse the requested calendar IDs, using the first requested timezone (or // device timezone as a fallback). auto& calendar_ids = intl_profile.calendars(); std::vector<std::unique_ptr<Calendar>> calendars; std::transform(calendar_ids.begin(), calendar_ids.end(), std::back_inserter(calendars), [&](CalendarId calendar_id) { return CalendarIdToCalendar(calendar_id, *time_zone); }); if (calendars.size() == 0) { UErrorCode error_code = U_ZERO_ERROR; calendars.push_back(std::unique_ptr<Calendar>( Calendar::createInstance(time_zone.get(), locales[0], error_code))); } std::string response = BuildResponse(timestamp_ms, locales, calendars); callback(response); } std::string IntlWisdomServerImpl::BuildResponse( const long timestamp_ms, const std::vector<Locale>& locales, const std::vector<std::unique_ptr<Calendar>>& calendars) const { std::ostringstream response; response << "\nA wise one knows the time...\n\n"; for (auto& locale : locales) { for (auto& calendar : calendars) { auto date_format = std::unique_ptr<DateFormat>(DateFormat::createDateTimeInstance( DateFormat::kFull, DateFormat::kFull, locale)); ZX_ASSERT(date_format); date_format->setCalendar(*calendar); UnicodeString formatted; date_format->format(static_cast<UDate>(timestamp_ms), formatted); std::string formatted_utf8; formatted.toUTF8String(formatted_utf8); response << formatted_utf8 << "\n"; } } response << "\nBut is it the 𝒄𝒐𝒓𝒓𝒆𝒄𝒕 time?\n"; return response.str(); } } // namespace intl_wisdom
#ifndef PLASKOWYZ_HH #define PLASKOWYZ_HH #include <iostream> #include "BrylaGeometryczna.hh" #define PLIK_WLASCIWY__PLASKOWYZ "dat/PlikWlasciwy_Plaskowyz0.dat" /*! * \file * \brief Ten plik zawiera diefinicje klasy Plaskowyz * * Klasa dziedziczy klase BrylaGeometryczna. Jako dane prywatne * mamy polozenie w formie wektora3D oraz konta orientacji w formie * double a takze unsigned int ile czyli ktory to plaskowyz. */ class Plaskowyz:public BrylaGeometryczna{ Wektor3D Polozenie; double KatOrientacji_stopnie; unsigned int ile; public: Wektor3D TransfDoUklWspRodzica(const Wektor3D& Wierz)const; virtual bool Tworz(Wektor3D polozenie,Wektor3D skala)override; }; #endif
#include"stdafx.h" #include<opencv2\opencv.hpp> #include<iostream> using namespace cv; int pause() { Mat src = imread("lena.jpg", 0); std::vector<std::vector<Point>> points; return 0; }
// // population.cpp // Reeval // // Created by Francesco Quinzan on 28.10.15. // Copyright © 2015 Francesco Quinzan. All rights reserved. // #include "population.hpp" #include "random.hpp" #include "table.hpp" using namespace std; /* generate random population */ void population::set(int dimension, int size, int order){ population::ord = order; population::data.CLEAR(); population::data.RESIZE(size, dimension); for (int i = 0; i < population::data.GET_N_ROW(); i++){ for (int j = 0; j < population::data.GET_N_COL(); j++) population::data.SET_VALUE(randomEngine::int_uar(order), i, j); } return; }; /* get population size (mu parameter) */ int population::size(){ return(population::data.GET_N_ROW()); }; /* erase given individual */ void population::kill(int individual){ population::data.ERASE_ROW(individual); return; }; /* get individual as vector<int> */ vector<int> population::individual(int individual){ return(population::data.GET_ROW(individual)); }; /* get poulation order */ int population::order(){ return(population::ord); }; /* get population dimension */ int population::dimension(){ return(population::data.GET_N_COL()); }; /* introduce mutation factor */ void population::mutation(int row){ /* mutation parameter */ double p = 1.0 / population::dimension(); /* intrduce mutation on individual*/ for (int i = 0; i < population::dimension(); i++){ if (randomEngine::uar() < p) population::data.SET_VALUE(randomEngine::int_uar(population::order()), row , i); } return; } /* create offspring */ void population::offspring(int n){ population::data.RESIZE(population::size() + 1, population::dimension()); vector<int> parents; int rnd; /* select n-parents */ for (int i = 0; i < n; i++){ parents.push_back(randomEngine::int_uar(population::size()-1)); } /* perform recombination */ for (int i = 0; i < population::dimension(); i++){ rnd = randomEngine::int_uar(n); for (int j = 0; j < n; j++){ if (rnd == j) population::data.SET_VALUE(data.GET_VALUE(parents.at(j), i), population::size()-1, i); } } return; }; /* check if true optimum has been reached */ int population::check(){ int err = 0; for (int i = 0; i < data.GET_N_ROW(); i++){ err = 0; for (int j = 0; j < data.GET_N_COL(); j++){ err = err + data.GET_VALUE(i, j); } if (err == 0) break; } return err; };
#include <stdio.h> #include <algorithm> #include <math.h> using namespace std; struct Pt { double x, y; }; Pt P[1000], CH[1000]; double calc_area(Pt P[], int n) { double ans = 0; int i; for(i = 0; i < n; i++) ans += P[i].x*P[i+1].y - P[i].y*P[i+1].x; return fabs(ans)/2; } double cross(Pt o, Pt a, Pt b) { return (a.x-o.x)*(b.y-o.y)- (a.y-o.y)*(b.x-o.x); } bool cmp(Pt a, Pt b) { if(a.x != b.x) return a.x < b.x; return a.y < b.y; } int monotone(int n) { sort(P, P+n, cmp); int i, m, t; m = 0; for(i = 0; i < n; i++) { while(m >= 2 && cross(CH[m-2], CH[m-1], P[i]) <= 0) m--; CH[m++] = P[i]; } for(i = n-1, t = m+1; i >= 0; i--) { while(m >= t && cross(CH[m-2], CH[m-1], P[i]) <= 0) m--; CH[m++] = P[i]; } return m; } int main() { int n, cases = 0, i; while(scanf("%d", &n) == 1 && n) { for(i = 0; i < n; i++) scanf("%lf %lf", &P[i].x, &P[i].y); P[n] = P[0]; double tile = calc_area(P, n); int m = monotone(n); double cont = calc_area(CH, m-1); printf("Tile #%d\n", ++cases); printf("Wasted Space = %.2lf %%\n\n", (cont-tile)*100/cont); } return 0; }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START bigtable_quickstart] #include "google/cloud/bigtable/table.h" int main(int argc, char* argv[]) try { if (argc != 4) { std::string const cmd = argv[0]; auto last_slash = std::string(cmd).find_last_of('/'); std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project_id> <instance_id> <table_id>\n"; return 1; } std::string const project_id = argv[1]; std::string const instance_id = argv[2]; std::string const table_id = argv[3]; // Create a namespace alias to make the code easier to read. namespace cbt = google::cloud::bigtable; cbt::Table table(cbt::CreateDefaultDataClient(project_id, instance_id, cbt::ClientOptions()), table_id); std::string row_key = "r1"; std::string column_family = "cf1"; std::cout << "Getting a single row by row key:" << std::flush; google::cloud::StatusOr<std::pair<bool, cbt::Row>> result = table.ReadRow(row_key, cbt::Filter::FamilyRegex(column_family)); if (!result) throw std::runtime_error(result.status().message()); if (!result->first) { std::cout << "Cannot find row " << row_key << " in the table: " << table_id << "\n"; return 0; } cbt::Cell const& cell = result->second.cells().front(); std::cout << cell.family_name() << ":" << cell.column_qualifier() << " @ " << cell.timestamp().count() << "us\n" << '"' << cell.value() << '"' << "\n"; return 0; } catch (std::exception const& ex) { std::cerr << "Standard C++ exception raised: " << ex.what() << "\n"; return 1; } // [END bigtable_quickstart]
/************************************************************************* SPDX-License-Identifier: MIT Copyright (c) 2020 Qazi Fahim Farhan (@fahimfarhan) May the CodeForces be with you! ************************************************************************/ /** // ⢀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⣠⣤⣶⣶ ⠄⠄⠄⠄⠄⠄⢴⡶⣶⣶⣶⡒⣶⣶⣖⠢⡄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⢀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⣠⣤⣶⣶ ⠄⠄⠄⠄⠄⠄⢠⣿⣋⣿⣿⣉⣿⣿⣯⣧⡰⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⢰⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⣿⣿⣹⣿⣿⣏⣿⣿⡗⣿⣿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣀⣀⣾⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠟⡛⣉⣭⣭⣭⠌⠛⡻⢿⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⡏⠉⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⣤⡌⣿⣷⣯⣭⣿⡆⣈⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⠀⠀⠀⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⠉⠁⠀⣿ ⠄⠄⠄⠄⠄⠄⠄⢻⣿⣿⣿⣿⣿⣿⣿⣷⢛⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣧⡀⠀⠀⠀⠀⠙⠿⠿⠿⠻⠿⠿⠟⠿⠛⠉⠀⠀⠀⠀⠀⣸⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢻⣷⣽⣿⣿⣿⢿⠃⣼⣧⣀⠄⠄⠄⠄⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣛⣻⣿⠟⣀⡜⣻⢿⣿⣿⣶⣤⡀⠄⠄⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⣴⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢠⣤⣀⣨⣥⣾⢟⣧⣿⠸⣿⣿⣿⣿⣿⣤⡀⠄⠄⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⢰⣹⡆⠀⠀⠀⠀⠀⠀⣭⣷⠀⠀⠀⠸⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢟⣫⣯⡻⣋⣵⣟⡼⣛⠴⣫⣭⣽⣿⣷⣭⡻⣦⡀⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠈⠉⠀⠀⠤⠄⠀⠀⠀⠉⠁⠀⠀⠀⠀⢿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⢰⣿⣿⣿⢏⣽⣿⢋⣾⡟⢺⣿⣿⣿⣿⣿⣿⣷⢹⣷⠄ // ⣿⣿⣿⣿⣿⣿⣿⣿⢾⣿⣷⠀⠀⠀⠀⡠⠤⢄⠀⠀⠀⠠⣿⣿⣷⠀⢸⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢣⣿⣿⣿⢸⣿⡇⣾⣿⠏⠉⣿⣿⣿⡇⣿⣿⡆ // ⣿⣿⣿⣿⣿⣿⣿⣿⡀⠉⠀⠀⠀⠀⠀⢄⠀⢀⠀⠀⠀⠀⠉⠉⠁⠀⠀⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢸⣿⣿⣿⠸⣿⡇⣿⣿⡆⣼⣿⣿⣿⡇⣿⣿⡇ // ⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿ ⠇⢀⠄⠄⠄⠄⠄⠘⣿⣿⡘⣿⣿⣷⢀⣿⣷⣿⣿⡿⠿⢿⣿⣿⡇⣩⣿⡇ // ⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿ ⣿⣿⠃⠄⠄⠄⠄⠄⠄⢻⣷⠙⠛⠋⣿⣿⣿⣿⣿⣷⣶⣿⣿⣿⡇⣿⣿⡇ */ #include <iostream> #include <climits> // this includes INT_MIN, INT_MAX, ... ... // #include <sstream> // #include <cstdio> // #include <cmath> // #include <cstring> // #include <cctype> // #include <string> #include <vector> // #include <list> // #include <set> // #include <unordered_set> // #include <map> // #include <unordered_map> // #include <queue> // #include <stack> #include <algorithm> // #include <functional> #include <iomanip> // std::setprecision // #include <regex> // for regular expressions using namespace std; #define PI 2*acos(0) //typedef long long int ll; #define ll long long int // other popular ones=> int64_t, uint64_t => use for 10^18 ll MOD = 1e9+7; // int n,m; vector<int> *g; bool *isvisited; #define GREATER 1 #define EQUAL 0 #define SMALLER -1 int bigIntComparator(string a, string b) { int sizeOfA = a.size(); int sizeOfB = b.size(); if(sizeOfA > sizeOfB) { return GREATER; } else if(sizeOfA < sizeOfB) { return SMALLER; } else{ for(int i=0; i<sizeOfA; i++) { if(a[i] < b[i]) { return SMALLER; } else if(a[i] > b[i]) { return GREATER; } } } return EQUAL; } string bigIntSum(string a, string b) { string summation = ""; if(a.size() < b.size()) { swap(a, b); } int len1 = a.size(), len2 = b.size(); int carry = 0; char ch; // int n = len2; int x = 0; for(int i=len1 - 1, j= len2-1; i>=0; i--, j--) { if(j >= 0) { x = (a[i] - '0') + (b[j] - '0') + carry; }else{ x = (a[i] - '0') + carry; } if(x < 10) { carry = 0; } else{ carry = 1; } x = x % 10; ch = x + '0'; summation = ch + summation; } if(carry == 1) { summation = "1" + summation; } return summation; } void start() {} void FastIO() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* std::cout << std::fixed; std::cout << std::setprecision(10); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); /* ---------- Interactive problems --------- on each interactive questions' end, add `cout.flush()` say, cout<<"some weirdo question"; cout<<"\n"; // end of question cout.flush(); // <-- just like this if still confusing, check out 1363D.cpp */ } int main(int argc, char const *argv[]){ /* code */ FastIO(); int T, n, k; int *a; cin>>T; while(T--) { cin>>n>>k; a = new int[n+1]; for(int i=0; i<n; i++) { cin>>a[i]; } int j = 0; int end = n-1; for(int i=0; i<k; i++) { while(a[j]<=0) { j++; if(j == end) { break; } } if(j!=end) { a[j]--; a[end]++; }else{ break; } } for(int i=0; i<n; i++) { cout<<a[i]<<" "; }cout<<"\n"; delete[] a; } return 0; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.IO.Stream #include "System/IO/Stream.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: SeekOrigin struct SeekOrigin; } // Completed forward declares // Type namespace: System.Security.Cryptography namespace System::Security::Cryptography { // Forward declaring type: TailStream class TailStream; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Security::Cryptography::TailStream); DEFINE_IL2CPP_ARG_TYPE(::System::Security::Cryptography::TailStream*, "System.Security.Cryptography", "TailStream"); // Type namespace: System.Security.Cryptography namespace System::Security::Cryptography { // Size: 0x39 #pragma pack(push, 1) // Autogenerated type: System.Security.Cryptography.TailStream // [TokenAttribute] Offset: FFFFFFFF class TailStream : public ::System::IO::Stream { public: public: // private System.Byte[] _Buffer // Size: 0x8 // Offset: 0x28 ::ArrayW<uint8_t> Buffer; // Field size check static_assert(sizeof(::ArrayW<uint8_t>) == 0x8); // private System.Int32 _BufferSize // Size: 0x4 // Offset: 0x30 int BufferSize; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _BufferIndex // Size: 0x4 // Offset: 0x34 int BufferIndex; // Field size check static_assert(sizeof(int) == 0x4); // private System.Boolean _BufferFull // Size: 0x1 // Offset: 0x38 bool BufferFull; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get instance field reference: private System.Byte[] _Buffer [[deprecated("Use field access instead!")]] ::ArrayW<uint8_t>& dyn__Buffer(); // Get instance field reference: private System.Int32 _BufferSize [[deprecated("Use field access instead!")]] int& dyn__BufferSize(); // Get instance field reference: private System.Int32 _BufferIndex [[deprecated("Use field access instead!")]] int& dyn__BufferIndex(); // Get instance field reference: private System.Boolean _BufferFull [[deprecated("Use field access instead!")]] bool& dyn__BufferFull(); // public System.Byte[] get_Buffer() // Offset: 0x126BBB8 ::ArrayW<uint8_t> get_Buffer(); // public System.Void .ctor(System.Int32 bufferSize) // Offset: 0x126BA7C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TailStream* New_ctor(int bufferSize) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::Cryptography::TailStream::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TailStream*, creationType>(bufferSize))); } // public System.Void Clear() // Offset: 0x126BB18 void Clear(); // public override System.Boolean get_CanRead() // Offset: 0x126BC34 // Implemented from: System.IO.Stream // Base method: System.Boolean Stream::get_CanRead() bool get_CanRead(); // public override System.Boolean get_CanSeek() // Offset: 0x126BC3C // Implemented from: System.IO.Stream // Base method: System.Boolean Stream::get_CanSeek() bool get_CanSeek(); // public override System.Boolean get_CanWrite() // Offset: 0x126BC44 // Implemented from: System.IO.Stream // Base method: System.Boolean Stream::get_CanWrite() bool get_CanWrite(); // public override System.Int64 get_Length() // Offset: 0x126BC54 // Implemented from: System.IO.Stream // Base method: System.Int64 Stream::get_Length() int64_t get_Length(); // public override System.Int64 get_Position() // Offset: 0x126BCB0 // Implemented from: System.IO.Stream // Base method: System.Int64 Stream::get_Position() int64_t get_Position(); // public override System.Void set_Position(System.Int64 value) // Offset: 0x126BD0C // Implemented from: System.IO.Stream // Base method: System.Void Stream::set_Position(System.Int64 value) void set_Position(int64_t value); // protected override System.Void Dispose(System.Boolean disposing) // Offset: 0x126BB28 // Implemented from: System.IO.Stream // Base method: System.Void Stream::Dispose(System.Boolean disposing) void Dispose(bool disposing); // public override System.Void Flush() // Offset: 0x126BD68 // Implemented from: System.IO.Stream // Base method: System.Void Stream::Flush() void Flush(); // public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) // Offset: 0x126BD6C // Implemented from: System.IO.Stream // Base method: System.Int64 Stream::Seek(System.Int64 offset, System.IO.SeekOrigin origin) int64_t Seek(int64_t offset, ::System::IO::SeekOrigin origin); // public override System.Void SetLength(System.Int64 value) // Offset: 0x126BDC8 // Implemented from: System.IO.Stream // Base method: System.Void Stream::SetLength(System.Int64 value) void SetLength(int64_t value); // public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) // Offset: 0x126BE24 // Implemented from: System.IO.Stream // Base method: System.Int32 Stream::Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) int Read(::ArrayW<uint8_t> buffer, int offset, int count); // public override System.Void Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count) // Offset: 0x126BE80 // Implemented from: System.IO.Stream // Base method: System.Void Stream::Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count) void Write(::ArrayW<uint8_t> buffer, int offset, int count); }; // System.Security.Cryptography.TailStream #pragma pack(pop) static check_size<sizeof(TailStream), 56 + sizeof(bool)> __System_Security_Cryptography_TailStreamSizeCheck; static_assert(sizeof(TailStream) == 0x39); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_Buffer // Il2CppName: get_Buffer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_Buffer)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_Buffer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Clear // Il2CppName: Clear template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::Clear)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Clear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_CanRead // Il2CppName: get_CanRead template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_CanRead)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_CanRead", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_CanSeek // Il2CppName: get_CanSeek template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_CanSeek)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_CanSeek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_CanWrite // Il2CppName: get_CanWrite template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_CanWrite)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_CanWrite", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_Length // Il2CppName: get_Length template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_Length)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_Length", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::get_Position // Il2CppName: get_Position template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::get_Position)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "get_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::set_Position // Il2CppName: set_Position template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)(int64_t)>(&System::Security::Cryptography::TailStream::set_Position)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "set_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Dispose // Il2CppName: Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)(bool)>(&System::Security::Cryptography::TailStream::Dispose)> { static const MethodInfo* get() { static auto* disposing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disposing}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Flush // Il2CppName: Flush template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)()>(&System::Security::Cryptography::TailStream::Flush)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Flush", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Seek // Il2CppName: Seek template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::Security::Cryptography::TailStream::*)(int64_t, ::System::IO::SeekOrigin)>(&System::Security::Cryptography::TailStream::Seek)> { static const MethodInfo* get() { static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg; static auto* origin = &::il2cpp_utils::GetClassFromName("System.IO", "SeekOrigin")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Seek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{offset, origin}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::SetLength // Il2CppName: SetLength template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)(int64_t)>(&System::Security::Cryptography::TailStream::SetLength)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "SetLength", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Read // Il2CppName: Read template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Security::Cryptography::TailStream::*)(::ArrayW<uint8_t>, int, int)>(&System::Security::Cryptography::TailStream::Read)> { static const MethodInfo* get() { static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Read", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, offset, count}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::TailStream::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TailStream::*)(::ArrayW<uint8_t>, int, int)>(&System::Security::Cryptography::TailStream::Write)> { static const MethodInfo* get() { static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TailStream*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, offset, count}); } };
#include <Arduino.h> #include <stdio.h> #include <FreeRTOS.h> #include <I2SMEMSSampler.h> #include <ADCSampler.h> #include <I2SOutput.h> #include <DACOutput.h> #include <SDCard.h> #include "SPIFFS.h" #include <WAVFileReader.h> #include <WAVFileWriter.h> #include "config.h" #define DEBOUNCE_TIME 50 int lastSteadyState = LOW; int lastFlickerableState = LOW; int currentState; unsigned long lastDebounceTime = 0; void wait_for_button_push() { currentState = digitalRead(GPIO_BUTTON); if (currentState != lastFlickerableState) { // reset the debouncing timer lastDebounceTime = millis(); // save the the last flickerable state lastFlickerableState = currentState; } if ((millis() - lastDebounceTime) > DEBOUNCE_TIME) { if (lastSteadyState == HIGH && currentState == LOW) vTaskDelay(pdMS_TO_TICKS(100)); // Serial.println("The button is pressed"); else if(lastSteadyState == LOW && currentState == HIGH) Serial.println("NOT PRESSED"); // save the the last steady state lastSteadyState = currentState; } while (gpio_get_level(GPIO_BUTTON) == 0) { vTaskDelay(pdMS_TO_TICKS(100)); } } void record(I2SSampler *input, const char *fname) { int16_t *samples = (int16_t *)malloc(sizeof(int16_t) * 1024); ESP_LOGI(TAG, "Start recording"); input->start(); // open the file on the sdcard FILE *fp = fopen(fname, "wb"); // create a new wave file writer WAVFileWriter *writer = new WAVFileWriter(fp, input->sample_rate()); // keep writing until the user releases the button while (gpio_get_level(GPIO_BUTTON) == 1) { int samples_read = input->read(samples, 1024); int64_t start = esp_timer_get_time(); writer->write(samples, samples_read); int64_t end = esp_timer_get_time(); ESP_LOGI(TAG, "Wrote %d samples in %lld microseconds", samples_read, end - start); } // stop the input input->stop(); // and finish the writing writer->finish(); fclose(fp); delete writer; free(samples); ESP_LOGI(TAG, "Finished recording"); } void play(Output *output, const char *fname) { int16_t *samples = (int16_t *)malloc(sizeof(int16_t) * 1024); // open the file on the sdcard FILE *fp = fopen(fname, "rb"); // create a new wave file writer WAVFileReader *reader = new WAVFileReader(fp); ESP_LOGI(TAG, "Start playing"); output->start(reader->sample_rate()); ESP_LOGI(TAG, "Opened wav file"); // read until theres no more samples while (true) { int samples_read = reader->read(samples, 1024); if (samples_read == 0) { break; } ESP_LOGI(TAG, "Read %d samples", samples_read); output->write(samples, samples_read); // ESP_LOGI(TAG, "Played samples"); } // stop the input output->stop(); fclose(fp); delete reader; // free(samples); // ESP_LOGI(TAG, "Finished playing"); } void main_task(void *param) { ESP_LOGI(TAG, "Starting up"); #ifdef USE_SPIFFS ESP_LOGI(TAG, "Mounting SPIFFS on /sdcard"); SPIFFS.begin(true, "/sdcard"); #else ESP_LOGI(TAG, "Mounting SDCard on /sdcard"); new SDCard("/sdcard", PIN_NUM_MISO, PIN_NUM_MOSI, PIN_NUM_CLK, PIN_NUM_CS); #endif ESP_LOGI(TAG, "Creating microphone"); #ifdef USE_I2S_MIC_INPUT I2SSampler *input = new I2SMEMSSampler(I2S_NUM_0, i2s_mic_pins, i2s_mic_Config); Serial.println("Sampler was created"); #else I2SSampler *input = new ADCSampler(ADC_UNIT_1, ADC1_CHANNEL_7, i2s_adc_config); #endif // #ifdef USE_I2S_SPEAKER_OUTPUT // Output *output = new I2SOutput(I2S_NUM_0, i2s_speaker_pins); // #else // Output *output = new DACOutput(I2S_NUM_0); // #endif gpio_set_direction(GPIO_BUTTON, GPIO_MODE_INPUT); gpio_set_pull_mode(GPIO_BUTTON, GPIO_PULLDOWN_ONLY); while (true) { // wait for the user to push and hold the button wait_for_button_push(); record(input, "/sdcard/test.wav"); Serial.println("successful"); // // wait for the user to push the button again // wait_for_button_push(); // play(output, "/sdcard/test.wav"); // vTaskDelay(pdMS_TO_TICKS(1000)); } } void setup() { Serial.begin(115200); xTaskCreate(main_task, "Main", 4096, NULL, 0, NULL); } void loop() { }
#ifndef OBJECT_H #define OBJECT_H class Object { protected: int x, y; int dx, dy; int color; public: Object(int _x = 0, int _y = 0, int _color = 0); void setLocation(int _x, int _y); void setCol(int c); int getX() const; int getY() const; int getCol() const; int left() const; int right() const; int top() const; int bottom() const; void reverseX(); void reverseY(); void setMovement(int _dx, int _dy); void setRandomMovement(); void bounce(int mx, int my); void move(); }; #endif
#include "qgeotilefetchergooglemaps.h" #include "qgeomapreplygooglemaps.h" #include "qgeotiledmapgooglemaps.h" #include "qgeotiledmappingmanagerenginegooglemaps.h" #include <QtLocation/private/qgeotilespec_p.h> #include <QDebug> #include <QSize> #include <QDir> #include <QUrl> #include <QUrlQuery> #include <QTime> #include <QNetworkProxy> #include <QtCore/QJsonDocument> #include <QSslSocket> #include <math.h> #include <map> QT_BEGIN_NAMESPACE QGeoTileFetcherGooglemaps::QGeoTileFetcherGooglemaps(const QVariantMap &parameters, QGeoTiledMappingManagerEngineGooglemaps *engine, const QSize &tileSize) : QGeoTileFetcher(engine), m_networkManager(new QNetworkAccessManager(this)), m_engineGooglemaps(engine), m_tileSize(tileSize), _googleVersionRetrieved(false), _scale(1) { if(parameters.contains(QStringLiteral("googlemaps.maps.apikey"))) m_apiKey = parameters.value(QStringLiteral("googlemaps.maps.apikey")).toString(); else m_apiKey = parameters.value(QStringLiteral("googlemaps.apikey")).toString(); m_signature = parameters.value(QStringLiteral("googlemaps.maps.signature")).toString(); m_client = parameters.value(QStringLiteral("googlemaps.maps.client")).toString(); m_baseUri = QStringLiteral("http://maps.googleapis.com/maps/api/staticmap"); if (parameters.contains(QStringLiteral("googlemaps.useragent"))) _userAgent = parameters.value(QStringLiteral("googlemaps.useragent")).toString().toLatin1(); else _userAgent = ""; if (parameters.contains(QStringLiteral("googlemaps.maps.language"))) { _language = parameters.value(QStringLiteral("googlemaps.maps.language")).toString().toLatin1(); if (_language.isEmpty()) _language = "en-US"; } else { QStringList langs = QLocale::system().uiLanguages(); _language = (langs.length() > 0) ? langs[0] : "en-US"; } if (parameters.contains(QStringLiteral("googlemaps.maps.highdpi"))) _scale = (parameters.value(QStringLiteral("googlemaps.maps.highdpi")).toBool()) ? 2 : 1; // Google version strings _secGoogleWord = "Galileo"; } QGeoTileFetcherGooglemaps::~QGeoTileFetcherGooglemaps() { } void QGeoTileFetcherGooglemaps::_getSessionToken() { QUrl sessionUrl("https://www.googleapis.com/tile/v1/createSession"); QUrlQuery queryItems; queryItems.addQueryItem("key", m_apiKey); queryItems.addQueryItem("mapType", "roadmap"); queryItems.addQueryItem("language", _language); queryItems.addQueryItem("region", "de"); sessionUrl.setQuery(queryItems); netRequest.setUrl(sessionUrl); QNetworkReply *sessionReply = m_networkManager->get(netRequest); if (sessionReply->error() != QNetworkReply::NoError) return; QJsonDocument document = QJsonDocument::fromJson(sessionReply->readAll()); if (!document.isObject()) return; QJsonObject object = document.object(); QJsonValue status = object.value(QStringLiteral("session")); printf("%s", status.toString().toLatin1().data()); } QGeoTiledMapReply *QGeoTileFetcherGooglemaps::getTileImage(const QGeoTileSpec &spec) { QString surl = _getURL(spec.mapId(), spec.x(), spec.y(), spec.zoom()); QUrl url(surl); netRequest.setUrl(url); QNetworkReply *netReply = m_networkManager->get(netRequest); QGeoTiledMapReply *mapReply = new QGeoMapReplyGooglemaps(netReply, spec); return mapReply; } void QGeoTileFetcherGooglemaps::_getSecGoogleWords(int x, int y, QString &sec1, QString &sec2) { sec1 = ""; // after &x=... sec2 = ""; // after &zoom=... int seclen = ((x * 3) + y) % 8; sec2 = _secGoogleWord.left(seclen); if (y >= 10000 && y < 100000) { sec1 = "&s="; } } QString QGeoTileFetcherGooglemaps::_getURL(int type, int x, int y, int zoom) { switch (type) { case 0: case 1: //Road Map { QString sec1 = ""; // after &x=... QString sec2 = ""; // after &zoom=... _getSecGoogleWords(x, y, sec1, sec2); return QString("http://mt.google.com/vt/lyrs=m&hl=%1&x=%2%3&y=%4&z=%5&s=%6&scale=%7").arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2).arg(_scale); } break; case 2: //Satallite Map { QString sec1 = ""; // after &x=... QString sec2 = ""; // after &zoom=... _getSecGoogleWords(x, y, sec1, sec2); return QString("http://mt.google.com/vt/lyrs=s&hl=%1&x=%2%3&y=%4&z=%5&s=%6&scale=%7").arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2).arg(_scale); } break; case 3: //Terrain Map { QString sec1 = ""; // after &x=... QString sec2 = ""; // after &zoom=... _getSecGoogleWords(x, y, sec1, sec2); return QString("http://mt.google.com/vt/lyrs=p&hl=%1&x=%2%3&y=%4&z=%5&s=%6&scale=%7").arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2).arg(_scale); } break; case 4: //Hybrid Map { QString sec1 = ""; // after &x=... QString sec2 = ""; // after &zoom=... _getSecGoogleWords(x, y, sec1, sec2); return QString("http://mt.google.com/vt/lyrs=y&hl=%1&x=%2%3&y=%4&z=%5&s=%6&scale=%7").arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2).arg(_scale); } break; } return ""; } void QGeoTileFetcherGooglemaps::_networkReplyError(QNetworkReply::NetworkError error) { qWarning() << "Could not connect to google maps. Error:" << error; if(_googleReply) { _googleReply->deleteLater(); _googleReply = NULL; } } void QGeoTileFetcherGooglemaps::_replyDestroyed() { _googleReply = NULL; } void QGeoTileFetcherGooglemaps::_googleVersionCompleted() { if (!_googleReply || (_googleReply->error() != QNetworkReply::NoError)) { qDebug() << "Error collecting Google maps version info"; return; } _googleReply->deleteLater(); _googleReply = NULL; } void QGeoTileFetcherGooglemaps::_tryCorrectGoogleVersions(QNetworkAccessManager* networkManager) { QMutexLocker locker(&_googleVersionMutex); if (_googleVersionRetrieved) { return; } _googleVersionRetrieved = true; if(networkManager) { QNetworkRequest qheader; QNetworkProxy proxy = networkManager->proxy(); QNetworkProxy tProxy; tProxy.setType(QNetworkProxy::DefaultProxy); networkManager->setProxy(tProxy); #ifndef QT_NO_SSL QSslConfiguration conf = qheader.sslConfiguration(); conf.setPeerVerifyMode(QSslSocket::VerifyNone); qheader.setSslConfiguration(conf); #endif QString url = "http://maps.google.com/maps/api/js?v=3.2&sensor=false"; qheader.setUrl(QUrl(url)); qheader.setRawHeader("User-Agent", _userAgent); _googleReply = networkManager->get(qheader); connect(_googleReply, &QNetworkReply::finished, this, &QGeoTileFetcherGooglemaps::_googleVersionCompleted); connect(_googleReply, &QNetworkReply::destroyed, this, &QGeoTileFetcherGooglemaps::_replyDestroyed); connect(_googleReply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &QGeoTileFetcherGooglemaps::_networkReplyError); networkManager->setProxy(proxy); } } QT_END_NAMESPACE
/* * 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. */ #if !defined(NAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680) #define NAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xercesc/sax/AttributeList.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN class XalanNamedNodeMap; class XALAN_PLATFORMSUPPORT_EXPORT NamedNodeMapAttributeList : public XERCES_CPP_NAMESPACE_QUALIFIER AttributeList { public: typedef XERCES_CPP_NAMESPACE_QUALIFIER AttributeList ParentType; explicit NamedNodeMapAttributeList( const XalanNamedNodeMap& theMap, MemoryManager& theManager); virtual ~NamedNodeMapAttributeList(); // These are inherited from AttributeList virtual XalanSize_t getLength() const; virtual const XalanDOMChar* getName(const XalanSize_t index) const; virtual const XalanDOMChar* getType(const XalanSize_t index) const; virtual const XalanDOMChar* getValue(const XalanSize_t index) const; virtual const XalanDOMChar* getType(const XalanDOMChar* const name) const; virtual const XalanDOMChar* getValue(const XalanDOMChar* const name) const; virtual const XalanDOMChar* getValue(const char* const name) const; private: // Not implemented... NamedNodeMapAttributeList& operator=(const NamedNodeMapAttributeList&); bool operator==(const NamedNodeMapAttributeList&); // Data members... const XalanNamedNodeMap& m_nodeMap; const XalanSize_t m_length; MemoryManager& m_memoryManager; static const XalanDOMChar s_typeString[]; }; XALAN_CPP_NAMESPACE_END #endif // NAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include <random> #include "gflags/gflags.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "paddle/fluid/operators/jit/kernels.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/platform/place.h" DEFINE_double(acc, 1e-5, "Test accuracy threshold."); template <typename T> void RandomVec(const int n, T* a, const T lower = static_cast<T>(-2.f), const T upper = static_cast<T>(2.f)) { static unsigned int seed = 100; std::mt19937 rng(seed++); std::uniform_real_distribution<double> uniform_dist(0, 1); for (int i = 0; i < n; ++i) { a[i] = static_cast<T>(uniform_dist(rng) * (upper - lower) + lower); } } template <typename T> void ExpectEQ(const T* target, const T* refer, size_t n) { if (std::is_floating_point<T>::value) { for (size_t i = 0; i < n; ++i) { EXPECT_NEAR(target[i], refer[i], FLAGS_acc) << " at index : " << i; } } else { for (size_t i = 0; i < n; ++i) { EXPECT_EQ(target[i], refer[i]) << " at index : " << i; } } } std::vector<int> TestSizes() { std::vector<int> s; for (int i = 1; i < 32; ++i) { s.push_back(i); } // test some large size s.push_back(100); s.push_back(1000); s.push_back(2000); return s; } namespace jit = paddle::operators::jit; using CPUPlace = paddle::platform::CPUPlace; template <typename KernelTuple, typename PlaceType, typename Tester, typename... Args> void TestAllImpls(const typename KernelTuple::attr_type& attr, const Tester& verifier, const Args&... args) { auto funcs = jit::GetAllCandidateFuncsWithTypes<KernelTuple, PlaceType>(attr); for (auto f : funcs) { VLOG(10) << "Test Kernel " << f.first; verifier(f.second, args...); } } template <typename KernelTuple, typename PlaceType> void TestKernelXYZN() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int d : TestSizes()) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(d), y(d), zref(d); RandomVec<T>(d, x.data()); RandomVec<T>(d, y.data()); std::vector<T> xinp(d), yinp(d); // inplace test std::copy(x.begin(), x.end(), xinp.begin()); std::copy(y.begin(), y.end(), yinp.begin()); const T* x_data = x.data(); const T* y_data = y.data(); T* zref_data = zref.data(); T* xinp_data = xinp.data(); T* yinp_data = yinp.data(); // test refer code inplace ref(x_data, y_data, zref_data, d); ref(x_data, yinp_data, yinp_data, d); ref(xinp_data, y_data, xinp_data, d); ExpectEQ<T>(xinp_data, zref_data, d); ExpectEQ<T>(yinp_data, zref_data, d); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const std::vector<T>& y, const std::vector<T>& zref) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(zref.size(), x.size()); EXPECT_EQ(zref.size(), y.size()); const T* x_data = x.data(); const T* y_data = y.data(); const T* zref_data = zref.data(); const int d = zref.size(); std::vector<T> ztgt(d); T* ztgt_data = ztgt.data(); // test normal tgt(x_data, y_data, ztgt_data, d); ExpectEQ<T>(ztgt_data, zref_data, d); // test inplace x std::copy(x.begin(), x.end(), ztgt.begin()); tgt(ztgt_data, y_data, ztgt_data, d); ExpectEQ<T>(ztgt_data, zref_data, d); // test inplace y std::copy(y.begin(), y.end(), ztgt.begin()); tgt(x_data, ztgt_data, ztgt_data, d); ExpectEQ<T>(ztgt_data, zref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, y, zref); } } template <typename KernelTuple, typename PlaceType> void TestKernelAXYN() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int d : TestSizes()) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); const T a = static_cast<T>(3); std::vector<T> x(d), yref(d); std::vector<T> xinp(d); // inplace test RandomVec<T>(d, x.data()); std::copy(x.begin(), x.end(), xinp.begin()); const T* x_data = x.data(); T* yref_data = yref.data(); T* xinp_data = xinp.data(); // test refer code inplace ref(&a, x_data, yref_data, d); ref(&a, xinp_data, xinp_data, d); ExpectEQ<T>(xinp_data, yref_data, d); auto verifier = [](const typename KernelTuple::func_type tgt, const T a, const std::vector<T>& x, const std::vector<T>& yref) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(yref.size(), x.size()); const T* x_data = x.data(); const T* yref_data = yref.data(); const int d = yref.size(); std::vector<T> ytgt(d); T* ytgt_data = ytgt.data(); // test normal tgt(&a, x_data, ytgt_data, d); ExpectEQ<T>(ytgt_data, yref_data, d); // test inplace x std::copy(x.begin(), x.end(), ytgt.begin()); tgt(&a, ytgt_data, ytgt_data, d); ExpectEQ<T>(ytgt_data, yref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, a, x, yref); } } template <typename KernelTuple, typename PlaceType> void TestKernelXYN() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int d : TestSizes()) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(d), yref(d); std::vector<T> xinp(d); // inplace test RandomVec<T>(d, x.data()); std::copy(x.begin(), x.end(), xinp.begin()); const T* x_data = x.data(); T* yref_data = yref.data(); T* xinp_data = xinp.data(); // test refer code inplace ref(x_data, yref_data, d); ref(xinp_data, xinp_data, d); ExpectEQ<T>(xinp_data, yref_data, d); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const std::vector<T>& yref) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(yref.size(), x.size()); const T* x_data = x.data(); const T* yref_data = yref.data(); const int d = yref.size(); std::vector<T> ytgt(d); T* ytgt_data = ytgt.data(); // test normal tgt(x_data, ytgt_data, d); ExpectEQ<T>(ytgt_data, yref_data, d); // test inplace x std::copy(x.begin(), x.end(), ytgt.begin()); tgt(ytgt_data, ytgt_data, d); ExpectEQ<T>(ytgt_data, yref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, yref); } } template <typename KernelTuple, typename PlaceType> void TestKernelXRN() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); auto last_acc = FLAGS_acc; FLAGS_acc = 1e-4; for (int d : TestSizes()) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(d); RandomVec<T>(d, x.data()); T ref_res; ref(x.data(), &ref_res, d); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const T ref_res) { EXPECT_TRUE(tgt != nullptr); T tgt_res; tgt(x.data(), &tgt_res, x.size()); ExpectEQ<T>(&tgt_res, &ref_res, 1); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, ref_res); } FLAGS_acc = last_acc; } template <typename KernelTuple, typename PlaceType> void TestKernelLSTM() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); std::vector<std::string> all_acts = {"sigmoid", "tanh", "relu", "identity"}; auto test_sizes = TestSizes(); test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000)); for (int d : test_sizes) { for (bool use_peephole : {true, false}) { for (auto& act_gate : all_acts) { for (auto& act_cand : all_acts) { for (auto& act_cell : all_acts) { const jit::lstm_attr_t attr( d, jit::to_kerneltype(act_gate), jit::to_kerneltype(act_cand), jit::to_kerneltype(act_cell), use_peephole); auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> xsrc(4 * d), wp(3 * d), ct_1(d); std::vector<T> ct_ref(d), ht_ref(d), checked(2 * d); RandomVec<T>(4 * d, xsrc.data()); RandomVec<T>(3 * d, wp.data(), -1.f, 1.f); RandomVec<T>(d, ct_1.data(), -1.f, 1.f); // x could be changed after compute, so copy to save src std::vector<T> x(xsrc.size()); std::copy(xsrc.begin(), xsrc.end(), x.begin()); const T* ct_1_data = ct_1.data(); const T* wp_data = wp.data(); T* x_data = x.data(); T* checked_data = checked.data(); T* ct_ref_data = ct_ref.data(); T* ht_ref_data = ht_ref.data(); jit::lstm_t step; step.gates = x_data; step.ct_1 = ct_1_data; step.ct = ct_ref_data; step.ht = ht_ref_data; if (use_peephole) { step.wp = wp_data; step.checked = checked_data; } ref(&step, &attr); VLOG(10) << attr; auto verifier = []( const typename KernelTuple::func_type tgt, const std::vector<T>& xsrc, const std::vector<T>& wp, const std::vector<T>& ct_1, const std::vector<T>& ct_ref, const std::vector<T>& ht_ref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(ct_ref.size(), ht_ref.size()); EXPECT_EQ(ct_1.size(), ht_ref.size()); EXPECT_EQ(xsrc.size(), 4 * ht_ref.size()); EXPECT_EQ(wp.size(), 3 * ht_ref.size()); // x could be changed after compute, so copy to save src int d = ht_ref.size(); std::vector<T> x(xsrc.size()), ct(ct_ref.size()), ht(ht_ref.size()); std::vector<T> checked(2 * d); std::copy(xsrc.begin(), xsrc.end(), x.begin()); const T* ct_1_data = ct_1.data(); const T* wp_data = wp.data(); const T* ct_ref_data = ct_ref.data(); const T* ht_ref_data = ht_ref.data(); T* x_data = x.data(); T* ct_data = ct.data(); T* ht_data = ht.data(); T* checked_data = checked.data(); jit::lstm_t step; step.gates = x_data; step.ct_1 = ct_1_data; step.ct = ct_data; step.ht = ht_data; if (attr.use_peephole) { step.wp = wp_data; step.checked = checked_data; } tgt(&step, &attr); ExpectEQ<T>(ct_data, ct_ref_data, d); ExpectEQ<T>(ht_data, ht_ref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, xsrc, wp, ct_1, ct_ref, ht_ref, attr); } } } } } } template <typename KernelTuple, typename PlaceType> void TestKernelGRU() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); std::vector<std::string> all_acts = {"sigmoid", "tanh", "relu", "identity"}; auto test_sizes = TestSizes(); test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000)); for (int d : test_sizes) { for (auto& act_gate : all_acts) { for (auto& act_cand : all_acts) { const jit::gru_attr_t attr(d, jit::to_kerneltype(act_gate), jit::to_kerneltype(act_cand)); auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> xsrc(3 * d), ht_1(d), ht_ref(d); RandomVec<T>(3 * d, xsrc.data()); RandomVec<T>(d, ht_1.data()); // x could be changed after compute, so copy to save src std::vector<T> x(xsrc.size()); std::copy(xsrc.begin(), xsrc.end(), x.begin()); const T* ht_1_data = ht_1.data(); T* x_data = x.data(); T* ht_ref_data = ht_ref.data(); jit::gru_t step; step.gates = x_data; step.ht_1 = ht_1_data; step.ht = ht_ref_data; ref(&step, &attr); VLOG(10) << attr; auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& xsrc, const std::vector<T>& ht_1, const std::vector<T>& ht_ref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(ht_1.size(), ht_ref.size()); EXPECT_EQ(xsrc.size(), 3 * ht_ref.size()); // x could be changed after compute, so copy to save src int d = ht_ref.size(); std::vector<T> x(xsrc.size()), ht(ht_ref.size()); std::copy(xsrc.begin(), xsrc.end(), x.begin()); const T* ht_1_data = ht_1.data(); const T* ht_ref_data = ht_ref.data(); T* x_data = x.data(); T* ht_data = ht.data(); jit::gru_t step; step.gates = x_data; step.ht_1 = ht_1_data; step.ht = ht_data; tgt(&step, &attr); ExpectEQ<T>(ht_data, ht_ref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, xsrc, ht_1, ht_ref, attr); } } } } template <typename KernelTuple, typename PlaceType> void TestKernelNCHW16CMulNC() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); const int n = 3, c = 16 * 4, h = 10, w = 10; auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); int sz = n * c * h * w; std::vector<T> x(sz), y(n * c), zref(sz); std::vector<T> ztgt(sz), zjit(sz); RandomVec<T>(sz, x.data()); RandomVec<T>(n * c, y.data()); const T* x_data = x.data(); const T* y_data = y.data(); T* zref_data = zref.data(); T* ztgt_data = ztgt.data(); T* zjit_data = zjit.data(); constexpr int simd_width = ZMM_FLOAT_BLOCK; int C = c / simd_width; auto tgt = jit::KernelFuncs<KernelTuple, PlaceType>::Cache().At(0); auto funcs = jit::GetAllCandidateFuncs<KernelTuple, PlaceType>(0); EXPECT_GT(funcs.size(), 0UL); auto jitcode = funcs[0]; EXPECT_TRUE(tgt != nullptr); if (std::is_same<T, float>::value && paddle::platform::MayIUse(paddle::platform::avx512f)) { EXPECT_TRUE(jitcode != nullptr); } for (int ni = 0; ni < n; ni++) { for (int ci = 0; ci < C; ci++) { auto ptr_x = x_data + ni * C * h * w * simd_width + ci * h * w * simd_width; auto ptr_y = y_data + ni * C * simd_width + ci * simd_width; auto ptr_zref = zref_data + ni * C * h * w * simd_width + ci * h * w * simd_width; auto ptr_ztgt = ztgt_data + ni * C * h * w * simd_width + ci * h * w * simd_width; ref(ptr_x, ptr_y, ptr_zref, h, w); tgt(ptr_x, ptr_y, ptr_ztgt, h, w); if (jitcode) { auto ptr_zjit = zjit_data + ni * C * h * w * simd_width + ci * h * w * simd_width; jitcode(ptr_x, ptr_y, ptr_zjit, h, w); } } } ExpectEQ<T>(ztgt_data, zref_data, sz); if (jitcode) { ExpectEQ<T>(zjit_data, zref_data, sz); } } template <typename KernelTuple, typename PlaceType> void TestKernelLayerNorm() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); const T epsilon = 9.99999975e-06; for (int n : {1, 2, 10}) { for (int x_dim_0 : {1, 9, 17, 50}) { int left = n * x_dim_0; for (int x_dim_1 : TestSizes()) { int right = x_dim_1; auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); int sz = left * right; std::vector<T> x(sz), mean(left), var(left), scale(right), bias(right), outref(sz); RandomVec<T>(sz, x.data()); RandomVec<T>(left, mean.data()); RandomVec<T>(left, var.data()); RandomVec<T>(right, scale.data()); RandomVec<T>(right, bias.data()); const T* scale_data = scale.data(); const T* bias_data = bias.data(); T* x_data = x.data(); T* mean_data = mean.data(); T* var_data = var.data(); T* outref_data = outref.data(); ref(x_data, outref_data, mean_data, var_data, scale_data, bias_data, left, epsilon, right); auto verifier = []( const typename KernelTuple::func_type tgt, const std::vector<T>& x_, const std::vector<T>& outref_, const std::vector<T>& mean_, const std::vector<T>& var_, const std::vector<T>& scale, const std::vector<T>& bias, const int& left, const float& epsilon, const typename KernelTuple::attr_type& right) { EXPECT_TRUE(tgt != nullptr); std::vector<T> outtgt(outref_.size()); std::vector<T> x(x_.size()); std::vector<T> mean(mean_.size()); std::vector<T> var(var_.size()); std::vector<T> outref(outref_.size()); std::copy(x_.begin(), x_.end(), x.begin()); std::copy(mean_.begin(), mean_.end(), mean.begin()); std::copy(var_.begin(), var_.end(), var.begin()); std::copy(outref_.begin(), outref_.end(), outref.begin()); EXPECT_EQ(x.size(), static_cast<size_t>(left * right)); EXPECT_EQ(outref.size(), static_cast<size_t>(left * right)); EXPECT_EQ(mean.size(), static_cast<size_t>(left)); EXPECT_EQ(var.size(), static_cast<size_t>(left)); EXPECT_EQ(scale.size(), static_cast<size_t>(right)); EXPECT_EQ(bias.size(), static_cast<size_t>(right)); const T* scale_data = scale.data(); const T* bias_data = bias.data(); T* x_data = x.data(); T* mean_data = mean.data(); T* var_data = var.data(); T* outref_data = outref.data(); T* outtgt_data = outtgt.data(); tgt(x_data, outtgt_data, mean_data, var_data, scale_data, bias_data, left, epsilon, right); ExpectEQ<T>(outtgt_data, outref_data, left * right); }; TestAllImpls<KernelTuple, PlaceType>(right, verifier, x, outref, mean, var, scale, bias, left, epsilon, right); } } } } template <typename KernelTuple, typename PlaceType> void TestKernelCRFDecoding() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); constexpr int state_trans_base_idx = 2; auto test_sizes = TestSizes(); test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 2000)); for (int seq_len : {1, 11, 17, 50}) { for (int tag_num : test_sizes) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); int x_sz = seq_len * tag_num; int w_sz = (tag_num + state_trans_base_idx) * tag_num; std::vector<T> x(x_sz), w(w_sz), alpharef(x_sz); std::vector<int> trackref(x_sz); RandomVec<T>(x_sz, x.data()); RandomVec<T>(w_sz, w.data()); ref(seq_len, (const T*)x.data(), (const T*)w.data(), alpharef.data(), trackref.data(), tag_num); auto verifier = []( const typename KernelTuple::func_type tgt, const int& seq_len, const std::vector<T>& x, const std::vector<T>& w, const std::vector<T>& alpharef, const std::vector<int>& trackref, const typename KernelTuple::attr_type& tag_num) { constexpr int state_trans_base_idx = 2; EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(x.size(), static_cast<size_t>(seq_len * tag_num)); EXPECT_EQ(w.size(), static_cast<size_t>( (tag_num + state_trans_base_idx) * tag_num)); EXPECT_EQ(alpharef.size(), static_cast<size_t>(seq_len * tag_num)); EXPECT_EQ(trackref.size(), static_cast<size_t>(seq_len * tag_num)); std::vector<T> alphatgt(alpharef.size()); std::vector<int> tracktgt(trackref.size()); memcpy(tracktgt.data(), trackref.data(), tag_num * sizeof(int)); tgt(seq_len, (const T*)x.data(), (const T*)w.data(), alphatgt.data(), tracktgt.data(), tag_num); ExpectEQ<T>(alpharef.data(), alphatgt.data(), seq_len * tag_num); ExpectEQ<int>(trackref.data(), tracktgt.data(), seq_len * tag_num); }; TestAllImpls<KernelTuple, PlaceType>(tag_num, verifier, seq_len, x, w, alpharef, trackref, tag_num); } } } template <typename KernelTuple, typename PlaceType> void TestKernelSeqPool() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); std::vector<jit::SeqPoolType> pool_types = { jit::SeqPoolType::kSum, jit::SeqPoolType::kAvg, jit::SeqPoolType::kSqrt}; auto test_sizes = TestSizes(); test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000)); for (auto type : pool_types) { for (int w : test_sizes) { jit::seq_pool_attr_t attr(w, type); for (int h : test_sizes) { attr.h = h; auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(h * w), yref(w); RandomVec<T>(h * w, x.data()); const T* x_data = x.data(); T* yref_data = yref.data(); ref(x_data, yref_data, &attr); VLOG(10) << attr; auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const std::vector<T>& yref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(x.size() % yref.size(), static_cast<size_t>(0)); int w = yref.size(); std::vector<T> y(w); const T* x_data = x.data(); const T* yref_data = yref.data(); T* y_data = y.data(); tgt(x_data, y_data, &attr); ExpectEQ<T>(y_data, yref_data, w); }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, x, yref, attr); } } } } template <typename KernelTuple, typename PlaceType> void TestKernelEmbSeqPool() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); int64_t tbl_h = 1e4; std::vector<jit::SeqPoolType> pool_types = { jit::SeqPoolType::kSum}; // only support sum yet auto test_sizes = TestSizes(); test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000)); for (int tbl_w : test_sizes) { std::vector<T> table(tbl_h * tbl_w); RandomVec<T>(tbl_h * tbl_w, table.data()); const T* table_data = table.data(); for (auto type : pool_types) { for (int idx_w : {1, 2, 10, 16}) { for (int idx_h : {1, 2, 9, 13, 16}) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<int64_t> idx(idx_h * idx_w); RandomVec<int64_t>(idx_h * idx_w, idx.data(), 0, tbl_h - 1); int64_t out_w = tbl_w * idx_w; std::vector<T> oref(out_w); const int64_t* idx_data = idx.data(); T* o_data = oref.data(); jit::emb_seq_pool_attr_t attr(tbl_h, tbl_w, idx_h, idx_w, out_w, type); ref(table_data, idx_data, o_data, &attr); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& table, const std::vector<int64_t>& idx, const std::vector<T>& oref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(table.size(), static_cast<size_t>(attr.table_height * attr.table_width)); EXPECT_EQ(idx.size(), static_cast<size_t>(attr.index_height * attr.index_width)); EXPECT_EQ(oref.size(), static_cast<size_t>(attr.table_width * attr.index_width)); const T* table_data = table.data(); const int64_t* idx_data = idx.data(); const T* oref_data = oref.data(); int o_w = oref.size(); std::vector<T> out(o_w); T* o_data = out.data(); tgt(table_data, idx_data, o_data, &attr); ExpectEQ<T>(o_data, oref_data, o_w); }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, table, idx, oref, attr); } } } } } template <typename KernelTuple, typename PlaceType> void TestKernelMatMul() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); auto last_acc = FLAGS_acc; // export MKL_CBWR=AVX would make MKL force to use AVX // export KMP_DETERMINISTIC_REDUCTION=yes would make the result deterministic FLAGS_acc = 1e-3; for (int m : {1, 2, 3, 4}) { for (int n : {1, 2, 3, 4}) { for (int k : TestSizes()) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> a(m * k), b(k * n), c(m * n); RandomVec<T>(m * k, a.data()); RandomVec<T>(k * n, b.data()); const T* a_data = a.data(); const T* b_data = b.data(); T* c_data = c.data(); const jit::matmul_attr_t attr{m, n, k}; ref(a_data, b_data, c_data, &attr); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& a, const std::vector<T>& b, const std::vector<T>& cref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(a.size(), static_cast<size_t>(attr.m * attr.k)); EXPECT_EQ(b.size(), static_cast<size_t>(attr.k * attr.n)); EXPECT_EQ(cref.size(), static_cast<size_t>(attr.m * attr.n)); std::vector<T> c(cref.size()); const T* a_data = a.data(); const T* b_data = b.data(); const T* cref_data = cref.data(); T* c_data = c.data(); tgt(a_data, b_data, c_data, &attr); ExpectEQ<T>(c_data, cref_data, attr.m * attr.n); }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, a, b, c, attr); } } } FLAGS_acc = last_acc; } template <typename KernelTuple, typename PlaceType> void TestKernelSoftmax() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int bs : {1, 2, 10}) { for (int n : TestSizes()) { for (int m : {1, 2, 3}) { // remain if (m > n || n % m != 0) { continue; } auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(bs * n), y(bs * n); RandomVec<T>(bs * n, x.data()); const T* x_data = x.data(); T* y_data = y.data(); std::vector<T> xinp(x.size()); // inplace test std::copy(x.begin(), x.end(), xinp.begin()); ref(x_data, y_data, n, bs, m); T* xinp_data = xinp.data(); ref(xinp_data, xinp_data, n, bs, m); ExpectEQ<T>(xinp_data, y_data, n * bs); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const std::vector<T>& yref, int n, int bs, int m) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(yref.size(), x.size()); EXPECT_EQ(x.size(), static_cast<size_t>(n * bs)); const T* x_data = x.data(); const T* yref_data = yref.data(); std::vector<T> ytgt(n * bs); T* ytgt_data = ytgt.data(); // test normal tgt(x_data, ytgt_data, n, bs, m); ExpectEQ<T>(ytgt_data, yref_data, n * bs); // test inplace x std::copy(x.begin(), x.end(), ytgt.begin()); tgt(ytgt_data, ytgt_data, n, bs, m); ExpectEQ<T>(ytgt_data, yref_data, n * bs); }; TestAllImpls<KernelTuple, PlaceType>(n, verifier, x, y, n, bs, m); } } } } template <typename KernelTuple, typename PlaceType> void TestKernelStrideASum() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int d : TestSizes()) { for (int m : {1, 2, 3}) { // stride if (m > d || d % m != 0) { continue; } auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> x(d); RandomVec<T>(d, x.data()); T ref_res; ref(x.data(), &ref_res, d, m); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const T ref_res, const int m) { EXPECT_TRUE(tgt != nullptr); T tgt_res; tgt(x.data(), &tgt_res, x.size(), m); ExpectEQ<T>(&tgt_res, &ref_res, 1); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, ref_res, m); } } } template <typename KernelTuple, typename PlaceType> void TestKernelStrideScal() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int d : TestSizes()) { for (int m : {1, 2, 3}) { // stride if (m > d || d % m != 0) { continue; } auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); const T a = static_cast<T>(3); std::vector<T> x(d), yref(d); std::vector<T> xinp(d); // inplace test RandomVec<T>(d, x.data()); std::copy(x.begin(), x.end(), xinp.begin()); const T* x_data = x.data(); T* yref_data = yref.data(); T* xinp_data = xinp.data(); // test refer code inplace ref(&a, x_data, yref_data, d, m); ref(&a, xinp_data, xinp_data, d, m); ExpectEQ<T>(xinp_data, yref_data, d); auto verifier = [](const typename KernelTuple::func_type tgt, const T a, const std::vector<T>& x, const std::vector<T>& yref, const int m) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(yref.size(), x.size()); const T* x_data = x.data(); const T* yref_data = yref.data(); const int d = yref.size(); std::vector<T> ytgt(d); T* ytgt_data = ytgt.data(); // test normal tgt(&a, x_data, ytgt_data, d, m); ExpectEQ<T>(ytgt_data, yref_data, d); // test inplace x std::copy(x.begin(), x.end(), ytgt.begin()); tgt(&a, ytgt_data, ytgt_data, d, m); ExpectEQ<T>(ytgt_data, yref_data, d); }; TestAllImpls<KernelTuple, PlaceType>(d, verifier, a, x, yref, m); } } } template <typename KernelTuple, typename PlaceType> void TestKernelSgd() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); const T lr = 0.1; auto UnDuplicatedRandomVec = [](int n, const int64_t lower, const int64_t upper) -> std::vector<int64_t> { PADDLE_ENFORCE_LE(static_cast<size_t>(upper - lower), n - 1, paddle::platform::errors::InvalidArgument( "The range of Sgd (upper - lower) should be lower " "than n-1 (Sgd size -1). But the upper - lower is %d " "and n-1 is %d.", static_cast<size_t>(upper - lower), n - 1)); PADDLE_ENFORCE_GT( n, 0, paddle::platform::errors::InvalidArgument( "The Sgd size should be larger than 0. But the n is %d.", n)); std::vector<int64_t> all, out; for (int i = 0; i < n; ++i) { all.push_back(i); } std::random_device rnd; int64_t seed_tmp = rnd(); std::default_random_engine rng(seed_tmp); std::shuffle(all.begin(), all.end(), rng); out.insert(out.begin(), all.begin(), all.begin() + n); return out; }; for (int param_h : {1, 10}) { for (int grad_w : TestSizes()) { std::vector<T> param(param_h * grad_w); std::vector<T> param_out(param_h * grad_w); RandomVec<T>(param_h * grad_w, param.data()); const T* param_data = param.data(); T* out_data = param_out.data(); for (int rows_size = 1; rows_size <= param_h; ++rows_size) { std::vector<T> grad(rows_size * grad_w); std::vector<int64_t> rows = UnDuplicatedRandomVec(rows_size, 0, rows_size - 1); RandomVec<T>(rows_size * grad_w, grad.data()); const int64_t* rows_data = rows.data(); const T* grad_data = grad.data(); auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); jit::sgd_attr_t attr(param_h, grad_w, rows_size, grad_w, rows_size); ref(&lr, param_data, grad_data, rows_data, out_data, &attr); // inplace test std::vector<T> inp(param.size()); std::copy(param.begin(), param.end(), inp.begin()); T* inp_data = inp.data(); ref(&lr, inp_data, grad_data, rows_data, inp_data, &attr); // only the selected rows should be equal for (int i = 0; i < rows_size; ++i) { ExpectEQ<T>(inp_data + rows[i] * grad_w, out_data + rows[i] * grad_w, grad_w); } auto verifier = []( const typename KernelTuple::func_type tgt, const T lr, const std::vector<T>& param, const std::vector<T>& grad, const std::vector<int64_t>& rows, const std::vector<T>& oref, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(param.size(), static_cast<size_t>(attr.param_height * attr.param_width)); EXPECT_EQ(grad.size(), static_cast<size_t>(attr.grad_height * attr.grad_width)); EXPECT_EQ(rows.size(), static_cast<size_t>(attr.selected_rows_size)); EXPECT_EQ(param.size(), oref.size()); const T* param_data = param.data(); const T* grad_data = grad.data(); const int64_t* rows_data = rows.data(); const T* oref_data = oref.data(); std::vector<T> out(oref.size()); T* o_data = out.data(); tgt(&lr, param_data, grad_data, rows_data, o_data, &attr); // only the selected rows should be equal for (size_t i = 0; i < rows.size(); ++i) { ExpectEQ<T>(o_data + rows[i] * attr.grad_width, oref_data + rows[i] * attr.grad_width, attr.grad_width); } // inplace std::copy(param.begin(), param.end(), out.begin()); tgt(&lr, o_data, grad_data, rows_data, o_data, &attr); for (size_t i = 0; i < rows.size(); ++i) { ExpectEQ<T>(o_data + rows[i] * attr.grad_width, oref_data + rows[i] * attr.grad_width, attr.grad_width); } }; TestAllImpls<KernelTuple, PlaceType>(attr, verifier, lr, param, grad, rows, param_out, attr); } } } } template <typename KernelTuple, typename PlaceType> void TestKernelVBroadcast() { using T = typename KernelTuple::data_type; VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type); for (int w : TestSizes()) { std::vector<T> x(w); RandomVec<T>(w, x.data()); const T* x_data = x.data(); for (int64_t h : {1, 2, 6}) { auto ref = jit::GetReferFunc<KernelTuple>(); EXPECT_TRUE(ref != nullptr); std::vector<T> y(w * h); T* y_data = y.data(); ref(x_data, y_data, h, w); auto verifier = [](const typename KernelTuple::func_type tgt, const std::vector<T>& x, const std::vector<T>& yref, const int64_t& h, const typename KernelTuple::attr_type& attr) { EXPECT_TRUE(tgt != nullptr); EXPECT_EQ(x.size(), static_cast<size_t>(attr)); EXPECT_EQ(yref.size(), x.size() * h); std::vector<T> y(yref.size()); const T* x_data = x.data(); const T* yref_data = yref.data(); T* y_data = y.data(); tgt(x_data, y_data, h, attr); ExpectEQ<T>(y_data, yref_data, yref.size()); }; TestAllImpls<KernelTuple, PlaceType>(static_cast<int64_t>(w), verifier, x, y, h, static_cast<int64_t>(w)); } } } // test pool TEST(JITKernel_pool, jitcreator) { const auto& jitcreators = jit::JitCodeCreatorPool::Instance().AllCreators(); #if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__) EXPECT_EQ(jitcreators.size(), 0UL); #else EXPECT_EQ(jitcreators.size(), 25UL); #endif } TEST(JITKernel_pool, jitpool) { // jitpool is related with attr const auto& kers = jit::JitCodePool<jit::kVAdd>().Instance().AllKernels(); EXPECT_EQ(kers.size(), 0UL); jit::GetAllCandidateKernels<jit::VAddTuple<float>, CPUPlace>(3); // after call GetAllCandidateKernels, it will create jitcode Automatically #if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__) EXPECT_EQ(kers.size(), 0UL); #else EXPECT_EQ(kers.size(), 1UL); #endif } TEST(JITKernel_pool, more) { const auto& kers = jit::KernelPool::Instance().AllKernels(); size_t target_num = 8; #ifdef __AVX__ target_num += 2; #endif #ifdef PADDLE_WITH_MKLML target_num += 12; #endif EXPECT_EQ(kers.size(), target_num); } TEST(JITKernel_pool, refer) { const auto& kers = jit::ReferKernelPool::Instance().AllKernels(); EXPECT_EQ(kers.size(), 31UL); } // test helper TEST(JITKernel_helper, GetAllCandidateKernels) { auto fp_kers = jit::GetAllCandidateKernels<jit::VExpTuple<float>, CPUPlace>(10); #if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__) EXPECT_GE(fp_kers.size(), 1UL); // refer #else #ifdef PADDLE_WITH_MKLML EXPECT_GE(fp_kers.size(), 3UL); // jitcode, mkl, refer #else EXPECT_GE(fp_kers.size(), 2UL); // jitcode, refer #endif #endif auto db_kers = jit::GetAllCandidateKernels<jit::VExpTuple<double>, CPUPlace>(10); #if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__) EXPECT_GE(db_kers.size(), 1UL); // refer #else #ifdef PADDLE_WITH_MKLML EXPECT_GE(db_kers.size(), 2UL); // mkl, refer #else EXPECT_GE(db_kers.size(), 1UL); // refer #endif #endif } TEST(JITKernel_helper, GetAllCandidateFuncsWithTypes) { auto fp_kers = jit::GetAllCandidateFuncsWithTypes<jit::VExpTuple<float>, CPUPlace>(10); #if defined(__APPLE__) || defined(__OSX__) EXPECT_GE(fp_kers.size(), 1UL); // refer #else #if !defined(PADDLE_WITH_MKLML) || defined(_WIN32) EXPECT_GE(fp_kers.size(), 2UL); // jitcode/mkl, refer #else EXPECT_GE(fp_kers.size(), 3UL); // jitcode, mkl, refer #endif #endif auto db_kers = jit::GetAllCandidateFuncsWithTypes<jit::VExpTuple<double>, CPUPlace>(10); #if defined(__APPLE__) || defined(__OSX__) || !defined(PADDLE_WITH_MKLML) EXPECT_GE(db_kers.size(), 1UL); // refer #else EXPECT_GE(db_kers.size(), 2UL); // mkl, refer #endif } TEST(JITKernel_helper, KernelFuncs) { auto f1 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache().At(3); auto f2 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache()[3]; EXPECT_TRUE(f1 != nullptr); EXPECT_TRUE(f1 == f2); auto f3 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache()[5]; #if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__) EXPECT_TRUE(f2 == f3); #else EXPECT_TRUE(f2 != f3); #endif } TEST(JITKernel_helper, GetAllCandidateFuncs) { auto funcs = jit::GetAllCandidateFuncs<jit::VExpTuple<float>, CPUPlace>(10); auto kers = jit::GetAllCandidateKernels<jit::VExpTuple<float>, CPUPlace>(10); EXPECT_EQ(funcs.size(), kers.size()); std::vector<float> x(10), tgt(10); RandomVec<float>(10, x.data()); auto best = jit::GetDefaultBestFunc<jit::VExpTuple<float>, CPUPlace>(10); best(x.data(), tgt.data(), 10); for (auto f : funcs) { std::vector<float> y(10); f(x.data(), y.data(), 10); ExpectEQ<float>(y.data(), tgt.data(), 10); } } TEST(JITKernel_helper, pack_weights) { const int N = 8 * 60, K = 2; float src[K][N], yref[K][N], y[K * N]; float* x = &(src[0][0]); float* ref = &(yref[0][0]); for (int i = 0; i < N * K; ++i) { *(x + i) = static_cast<float>(i); } int block = 0; std::vector<int> groups; if (paddle::platform::MayIUse(paddle::platform::avx512f)) { block = ZMM_FLOAT_BLOCK; groups.push_back(30); } else { block = YMM_FLOAT_BLOCK; groups.insert(groups.end(), {14, 14, 14, 14, 4}); } int offset = 0; int acc = 0; for (int g : groups) { g = g * block; for (int k = 0; k < K; ++k) { for (int i = 0; i < g; ++i) { *(ref + offset) = src[k][i + acc]; offset++; } } acc += g; } jit::pack_weights<float>(x, y, N, K); ExpectEQ<float>(y, ref, N * K); } TEST(JITKernel_helper, attr) { std::ostringstream out; // KernelTypes out << jit::to_string(jit::kNone) << jit::to_string(jit::kCRFDecoding) << jit::to_string(jit::kEmbSeqPool) << jit::to_string(jit::kGRUH1) << jit::to_string(jit::kGRUHtPart1) << jit::to_string(jit::kGRUHtPart2) << jit::to_string(jit::kHSum) << jit::to_string(jit::kHMax) << jit::to_string(jit::kLSTMCtHt) << jit::to_string(jit::kLSTMC1H1) << jit::to_string(jit::kLayerNorm) << jit::to_string(jit::kMatMul) << jit::to_string(jit::kNCHW16CMulNC) << jit::to_string(jit::kSeqPool) << jit::to_string(jit::kSoftmax) << jit::to_string(jit::kVAdd) << jit::to_string(jit::kVAddBias) << jit::to_string(jit::kVAddRelu) << jit::to_string(jit::kVBroadcast) << jit::to_string(jit::kVCopy) << jit::to_string(jit::kVExp) << jit::to_string(jit::kVIdentity) << jit::to_string(jit::kVMul) << jit::to_string(jit::kVRelu) << jit::to_string(jit::kVScal) << jit::to_string(jit::kSgd) << jit::to_string(jit::kVSigmoid) << jit::to_string(jit::kVSquare) << jit::to_string(jit::kVSub) << jit::to_string(jit::kVTanh); EXPECT_EQ(out.str().size(), 234UL); // SeqPoolTypes out.str(""); out << jit::to_string(jit::kSum) << jit::to_string(jit::kAvg) << jit::to_string(jit::kSqrt); EXPECT_EQ(out.str().size(), 13UL); EXPECT_EQ(jit::to_kerneltype("relu"), jit::kVRelu); EXPECT_EQ(jit::to_kerneltype("Identity"), jit::kVIdentity); EXPECT_EQ(jit::to_kerneltype("VEXP"), jit::kVExp); EXPECT_EQ(jit::to_kerneltype("SigmoiD"), jit::kVSigmoid); EXPECT_EQ(jit::to_kerneltype("VTanh"), jit::kVTanh); out.str(""); out << jit::lstm_attr_t(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh); EXPECT_EQ(out.str().size(), 89UL); out.str(""); out << jit::gru_attr_t(8, jit::kVIdentity, jit::kVSigmoid); EXPECT_EQ(out.str().size(), 52UL); out.str(""); out << jit::seq_pool_attr_t(8, jit::SeqPoolType::kSum); EXPECT_EQ(out.str().size(), 44UL); out.str(""); out << jit::emb_seq_pool_attr_t(1, 2, 3, 4, 5, jit::SeqPoolType::kAvg); EXPECT_EQ(out.str().size(), 93UL); out.str(""); out << jit::sgd_attr_t(1, 2, 3, 4, 5); EXPECT_EQ(out.str().size(), 81UL); out.str(""); out << jit::matmul_attr_t(1, 2, 3); EXPECT_EQ(out.str().size(), 14UL); } // test keys TEST(JITKernel_key, int) { EXPECT_TRUE(jit::JitCodeKey<int>(2) == jit::JitCodeKey<int>(2)); EXPECT_TRUE(jit::JitCodeKey<int>(2) == jit::JitCodeKey<int64_t>(2)); EXPECT_TRUE(jit::JitCodeKey<int>(2) != jit::JitCodeKey<int>(3)); } TEST(JITKernel_key, gru) { jit::gru_attr_t attr1(8, jit::kVSigmoid, jit::kVTanh); jit::gru_attr_t attr2(8, jit::kVSigmoid, jit::kVTanh); jit::gru_attr_t attr3(9, jit::kVSigmoid, jit::kVTanh); jit::gru_attr_t attr4(9, jit::kVSigmoid, jit::kVIdentity); jit::gru_attr_t attr5(9, jit::kVTanh, jit::kVIdentity); auto key1 = jit::JitCodeKey<jit::gru_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::gru_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::gru_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::gru_attr_t>(attr4); auto key5 = jit::JitCodeKey<jit::gru_attr_t>(attr5); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 != key3); EXPECT_TRUE(key2 != key4); EXPECT_TRUE(key2 != key5); EXPECT_TRUE(key3 != key4); EXPECT_TRUE(key3 != key5); EXPECT_TRUE(key4 != key5); } TEST(JITKernel_key, lstm) { jit::lstm_attr_t attr1(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh); jit::lstm_attr_t attr2(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh); jit::lstm_attr_t attr3(9, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh); jit::lstm_attr_t attr4(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh); jit::lstm_attr_t attr5(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh, true); jit::lstm_attr_t attr6(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh, true); auto key1 = jit::JitCodeKey<jit::lstm_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::lstm_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::lstm_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::lstm_attr_t>(attr4); auto key5 = jit::JitCodeKey<jit::lstm_attr_t>(attr5); auto key6 = jit::JitCodeKey<jit::lstm_attr_t>(attr6); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 != key3); EXPECT_TRUE(key2 != key4); EXPECT_TRUE(key2 != key5); EXPECT_TRUE(key3 != key4); EXPECT_TRUE(key3 != key5); EXPECT_TRUE(key4 != key5); EXPECT_TRUE(key5 == key6); } TEST(JITKernel_key, seq_pool) { jit::seq_pool_attr_t attr1(2, jit::SeqPoolType::kSum, 1); jit::seq_pool_attr_t attr2(2, jit::SeqPoolType::kSum, 3); jit::seq_pool_attr_t attr3(3, jit::SeqPoolType::kSum, 3); jit::seq_pool_attr_t attr4(3, jit::SeqPoolType::kAvg, 3); auto key1 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr4); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 != key3); EXPECT_TRUE(key2 != key4); EXPECT_TRUE(key3 != key4); } TEST(JITKernel_key, matmul) { jit::matmul_attr_t attr1(1, 2, 3); jit::matmul_attr_t attr2(1, 2, 3); jit::matmul_attr_t attr3(1, 3, 3); jit::matmul_attr_t attr4(2, 3, 4); auto key1 = jit::JitCodeKey<jit::matmul_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::matmul_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::matmul_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::matmul_attr_t>(attr4); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 != key3); EXPECT_TRUE(key2 != key4); EXPECT_TRUE(key3 != key4); } TEST(JITKernel_key, emb_seq_pool) { jit::emb_seq_pool_attr_t attr1(1, 2, 3, 4, 5, jit::SeqPoolType::kSum); jit::emb_seq_pool_attr_t attr2(1, 2, 3, 4, 5, jit::SeqPoolType::kSum); jit::emb_seq_pool_attr_t attr3(10, 2, 9, 8, 7, jit::SeqPoolType::kAvg); jit::emb_seq_pool_attr_t attr4(10, 3, 9, 8, 7, jit::SeqPoolType::kSum); jit::emb_seq_pool_attr_t attr5(1, 6, 3, 4, 5, jit::SeqPoolType::kSum); auto key1 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr4); auto key5 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr5); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 == key3); EXPECT_TRUE(key2 != key4); EXPECT_TRUE(key2 != key5); EXPECT_TRUE(key4 != key5); } TEST(JITKernel_key, sgd) { jit::sgd_attr_t attr1(1, 2, 3, 4, 5); jit::sgd_attr_t attr2(1, 2, 3, 4, 5); jit::sgd_attr_t attr3(9, 8, 7, 4, 6); jit::sgd_attr_t attr4(1, 2, 3, 6, 5); jit::sgd_attr_t attr5(10, 9, 8, 7, 6); auto key1 = jit::JitCodeKey<jit::sgd_attr_t>(attr1); auto key2 = jit::JitCodeKey<jit::sgd_attr_t>(attr2); auto key3 = jit::JitCodeKey<jit::sgd_attr_t>(attr3); auto key4 = jit::JitCodeKey<jit::sgd_attr_t>(attr4); auto key5 = jit::JitCodeKey<jit::sgd_attr_t>(attr5); EXPECT_TRUE(key1 == key2); EXPECT_TRUE(key2 == key3); EXPECT_TRUE(key3 != key4); EXPECT_TRUE(key3 != key5); EXPECT_TRUE(key4 != key5); } // test kernerls #define TestKernelVMul TestKernelXYZN #define TestKernelVAdd TestKernelXYZN #define TestKernelVAddRelu TestKernelXYZN #define TestKernelVSub TestKernelXYZN #define TestKernelVScal TestKernelAXYN #define TestKernelVAddBias TestKernelAXYN #define TestKernelVRelu TestKernelXYN #define TestKernelVIdentity TestKernelXYN #define TestKernelVSquare TestKernelXYN #define TestKernelVExp TestKernelXYN #define TestKernelVSigmoid TestKernelXYN #define TestKernelVTanh TestKernelXYN #define TestKernelVCopy TestKernelXYN #define TestKernelHMax TestKernelXRN #define TestKernelHSum TestKernelXRN #define TestKernelLSTMCtHt TestKernelLSTM #define TestKernelLSTMC1H1 TestKernelLSTM #define TestKernelGRUH1 TestKernelGRU #define TestKernelGRUHtPart1 TestKernelGRU #define TestKernelGRUHtPart2 TestKernelGRU #define TEST_CPU_KERNEL(kernel_type) \ TEST(JITKernel, kernel_type) { \ TestKernel##kernel_type<jit::kernel_type##Tuple<float>, CPUPlace>(); \ TestKernel##kernel_type<jit::kernel_type##Tuple<double>, CPUPlace>(); \ } TEST_CPU_KERNEL(VMul); TEST_CPU_KERNEL(VAdd); TEST_CPU_KERNEL(VAddRelu); TEST_CPU_KERNEL(VSub); TEST_CPU_KERNEL(VScal); TEST_CPU_KERNEL(VAddBias); TEST_CPU_KERNEL(VRelu); TEST_CPU_KERNEL(VIdentity); TEST_CPU_KERNEL(VSquare); TEST_CPU_KERNEL(VExp); TEST_CPU_KERNEL(VSigmoid); TEST_CPU_KERNEL(VTanh); TEST_CPU_KERNEL(VCopy); TEST_CPU_KERNEL(HMax); TEST_CPU_KERNEL(HSum); TEST_CPU_KERNEL(LSTMCtHt); TEST_CPU_KERNEL(LSTMC1H1); TEST_CPU_KERNEL(GRUH1); TEST_CPU_KERNEL(GRUHtPart1); TEST_CPU_KERNEL(GRUHtPart2); TEST_CPU_KERNEL(NCHW16CMulNC); TEST_CPU_KERNEL(LayerNorm); TEST_CPU_KERNEL(CRFDecoding); TEST_CPU_KERNEL(SeqPool); TEST_CPU_KERNEL(EmbSeqPool); TEST_CPU_KERNEL(MatMul); TEST_CPU_KERNEL(Softmax); TEST_CPU_KERNEL(Sgd); TEST_CPU_KERNEL(VBroadcast); TEST_CPU_KERNEL(StrideASum); TEST_CPU_KERNEL(StrideScal);
// STL #include <chrono> #include <vector> #include <cstdlib> #include <iostream> // GL3W #include <GL/gl3w.h> // SDL2 #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> // GLM #include <glm/vec3.hpp> #include <glm/matrix.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // assimp #include <assimp/scene.h> #include <assimp/Importer.hpp> enum GL3D { SUCCESS = 0 }; enum class ShaderResult : std::uint32_t { FAILURE = std::numeric_limits<std::uint32_t>::max() }; enum class ProgramResult : std::uint32_t { FAILURE = std::numeric_limits<std::uint32_t>::max() }; enum class SDL_GL : int { ADAPTIVE_VSYNC = -1, IMMEDIATE = 0, SYNCHRONIZED = 1 }; static void DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *pUserParam) { (void)type; (void)id; (void)severity; (void)length; (void)pUserParam; constexpr std::array ignoreWarrings = {33350}; if(std::any_of(std::cbegin(ignoreWarrings), std::cend(ignoreWarrings), [source](auto current) -> bool { return static_cast<int>(source) == current; })) { return; } std::cout << source << " : " << message << '\n'; } static const char *vertexShaderSource = R"GLSL( #version 450 core layout (location = 0) in vec4 iPosition; layout (location = 0) uniform mat4 MVP; void main() { gl_Position = MVP * iPosition; } )GLSL"; static const char *fragmentShaderSource = R"GLSL( #version 450 core layout (location = 0) out vec4 oColor; void main() { oColor = vec4(1.0, 0, 0, 1.0); } )GLSL"; struct Model { GLuint vao; GLuint vbo[3]; void draw() const { glBindVertexArray(vao); { glDrawArrays(GL_TRIANGLES, 0, mVertices.size() / 3); } glBindVertexArray(0); } std::vector<float> mVertices; }; struct Scene { std::vector<Model> mModels; void initialize() { for(auto &model : mModels) { glGenVertexArrays(1, &model.vao); glBindVertexArray(model.vao); { glGenBuffers(2, model.vbo); glBindBuffer(GL_ARRAY_BUFFER, model.vbo[0]); glBufferData(GL_ARRAY_BUFFER, model.mVertices.size() * 3 * sizeof(float), model.mVertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, nullptr); } glBindVertexArray(0); } } void draw() const { for(const auto &model : mModels) { model.draw(); } } }; static auto LoadMesh(const aiMesh *pMesh) -> Model { Model model; model.mVertices.resize(pMesh->mNumVertices * 3); glm::vec3 *pVertex = reinterpret_cast<glm::vec3 *>(model.mVertices.data()); for(auto i = 0U; i < pMesh->mNumVertices; i++) { const aiVector3D *pPos = &(pMesh->mVertices[i]); *pVertex = {pPos->x, pPos->y, pPos->z}; ++pVertex; } return model; } static auto LoadFile(const std::string &fileName) -> Scene { Assimp::Importer importer; const auto pScene = importer.ReadFile(fileName, 0); if(pScene == nullptr) { std::cerr << "Can not load \"" << fileName << "\"!\n"; std::exit(EXIT_FAILURE); } Scene scene; scene.mModels.reserve(pScene->mNumMeshes); for(auto i = 0U; i < pScene->mNumMeshes; ++i) { const auto &mesh = pScene->mMeshes[i]; scene.mModels.push_back(LoadMesh(mesh)); } return scene; } static auto checkShaderCompilation(GLuint shader) -> bool { GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if(compiled != GL_TRUE) { GLsizei log_length = 0; GLchar message[1024]; glGetShaderInfoLog(shader, 1024, &log_length, message); std::cerr << "ERROR: " << message << '\n'; return false; } return true; } static auto createShader(GLenum shaderType, const char *shaderSource) -> GLuint { auto shader = glCreateShader(shaderType); auto vertexShaderSourcePtr = &shaderSource; glShaderSource(shader, 1, vertexShaderSourcePtr, nullptr); glCompileShader(shader); if(!checkShaderCompilation(shader)) { return static_cast<std::uint32_t>(ShaderResult::FAILURE); } return shader; } static auto checkProgramLinkage(GLuint program) -> bool { GLint program_linked; glGetProgramiv(program, GL_LINK_STATUS, &program_linked); if(program_linked != GL_TRUE) { GLsizei log_length = 0; GLchar message[1024]; glGetProgramInfoLog(program, 1024, &log_length, message); std::cerr << "ERROR: " << message << '\n'; return false; } return true; } static auto createProgram(GLuint vertexShader, GLuint fragmentShader) -> GLuint { auto program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); if(!checkProgramLinkage(program)) { return static_cast<std::uint32_t>(ProgramResult::FAILURE); } return program; } enum class TimerType { CPU, GPU }; template<TimerType Type> struct Timer; template<> struct Timer<TimerType::CPU> { void start() { mStart = std::chrono::high_resolution_clock::now(); } auto stop() -> long { const auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(end - mStart).count(); } auto stopAndRestart() -> long { const auto time = stop(); start(); return time; } private: std::chrono::high_resolution_clock::time_point mStart; }; template<> struct Timer<TimerType::GPU> { Timer() { glGenQueries(2, mQueries); } void start() { glQueryCounter(mQueries[0], GL_TIMESTAMP); } auto stop() -> long { glQueryCounter(mQueries[1], GL_TIMESTAMP); // wait until the results are available int stopTimerAvailable = 0; while(!stopTimerAvailable) { glGetQueryObjectiv(mQueries[1], GL_QUERY_RESULT_AVAILABLE, &stopTimerAvailable); } GLuint64 startTime, stopTime; // get query results glGetQueryObjectui64v(mQueries[0], GL_QUERY_RESULT, &startTime); glGetQueryObjectui64v(mQueries[1], GL_QUERY_RESULT, &stopTime); return static_cast<long>(stopTime - startTime) / 1000000; } auto stopAndRestart() -> long { const auto time = stop(); start(); return time; } GLuint mQueries[2]; }; constexpr auto gTitle = "Scene"; constexpr auto gWidth = 640U; constexpr auto gHeight = 480U; constexpr auto SDL_SUCCESS = 0; auto main() -> int { if(SDL_Init(SDL_INIT_VIDEO) != SDL_SUCCESS) { std::cerr << "Can not initialize \"" << SDL_GetError() << "\"\n"; return EXIT_FAILURE; } // Enable Debug OpenGL int contextFlags; SDL_GL_GetAttribute(SDL_GL_CONTEXT_FLAGS, &contextFlags); contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; // OpenGL 3.3 Core Profile SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, contextFlags); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); auto pWindow = SDL_CreateWindow(gTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gWidth, gHeight, SDL_WINDOW_OPENGL); if(pWindow == nullptr) { std::cerr << "Can not create window \"" << SDL_GetError() << "\"\n"; return EXIT_FAILURE; } auto context = SDL_GL_CreateContext(pWindow); if(context == nullptr) { std::cerr << "Can not create context \"" << SDL_GetError() << "\"\n"; return EXIT_FAILURE; } if(gl3wInit() != GL3D::SUCCESS) { std::cerr << "Can not initialize GL3W!\n"; return EXIT_FAILURE; } // Set OpenGL Debug Callback if(glDebugMessageCallback) { std::cout << "Debug is enabled\n"; glDebugMessageCallback(DebugCallback, nullptr); } // Enable Immediate update if(SDL_GL_SetSwapInterval(static_cast<int>(SDL_GL::SYNCHRONIZED)) != SDL_SUCCESS) { std::cerr << "Can not set Immediate update!\n"; } Scene scene = LoadFile("sphere.obj"); scene.initialize(); GLuint program = 0U; { auto vertexShader = createShader(GL_VERTEX_SHADER, vertexShaderSource); auto fragmentShader = createShader(GL_FRAGMENT_SHADER, fragmentShaderSource); if(vertexShader == static_cast<std::uint32_t>(ShaderResult::FAILURE) || fragmentShader == static_cast<std::uint32_t>(ShaderResult::FAILURE)) { return EXIT_FAILURE; } program = createProgram(vertexShader, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } const auto ratio = static_cast<float>(gWidth) / static_cast<float>(gHeight); const auto prespective = glm::perspective(45.F, ratio, 0.001F, 1000.F); const auto view = glm::lookAt(glm::vec3{5, 5, 5}, glm::vec3{}, glm::vec3{0, 1, 0}); const auto MVP = prespective * view; Timer<TimerType::CPU> cpuTimer; Timer<TimerType::GPU> gpuTimer; glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); bool bRunning = true; while(bRunning) { SDL_Event event; while(SDL_PollEvent(&event) != 0) { if(event.type == SDL_QUIT) { bRunning = false; } } cpuTimer.start(); gpuTimer.start(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program); { glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(MVP)); scene.draw(); } glUseProgram(0); SDL_GL_SwapWindow(pWindow); const float cpuTime = static_cast<float>(cpuTimer.stop()); const float gpuTime = static_cast<float>(gpuTimer.stop()); printf("\rCPU: FPS: %.3F, Time: %.3F, GPU: FPS: %.3F, Time: %.3F", static_cast<double>(1000.F / cpuTime), static_cast<double>(cpuTime), static_cast<double>(1000.F / gpuTime), static_cast<double>(gpuTime)); } SDL_GL_DeleteContext(context); SDL_DestroyWindow(pWindow); SDL_Quit(); return EXIT_SUCCESS; }
/* * Copyright (C) 2017-2018 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/os_interface/linux/device_command_stream.inl" #include "runtime/os_interface/linux/drm_command_stream.inl" #include "runtime/command_stream/command_stream_receiver_with_aub_dump.inl" namespace OCLRT { template class DeviceCommandStreamReceiver<CNLFamily>; template class DrmCommandStreamReceiver<CNLFamily>; template class CommandStreamReceiverWithAUBDump<DrmCommandStreamReceiver<CNLFamily>>; } // namespace OCLRT
#ifndef _MNIST_HPP_ #define _MNIST_HPP_ // MNIST構造体 typedef struct mnist_data { double image[IMG_WIDTH][IMG_HEIGHT]; // 28x28 の画素値 unsigned int label; // 0~9のラベル } mnist_data; int load_mnist(const string image_filename, const string label_filename, mnist_data *data); void mnist_one_hot(mnist_data *data, double *arr); void mnist_flatten(mnist_data *data, double *arr); #endif /* _MNIST_HPP_ */
#include "Params.h" Params::Params(std::string pathToInstance, int nbVeh, int seedRNG) : nbVehicles(nbVeh) { std::string content, content2, content3; double serviceTimeData = 0.; nbClients = 0; totalDemand = 0.; maxDemand = 0.; durationLimit = 1.e30; vehicleCapacity = 1.e30; isRoundingInteger = true; isDurationConstraint = false; // Initialize RNG srand(seedRNG); // Read INPUT dataset std::ifstream inputFile(pathToInstance); if (inputFile.is_open()) { getline(inputFile, content); getline(inputFile, content); getline(inputFile, content); for (inputFile >> content ; content != "NODE_COORD_SECTION" ; inputFile >> content) { if (content == "DIMENSION") { inputFile >> content2 >> nbClients; nbClients--; } // Need to substract the depot from the number of nodes else if (content == "EDGE_WEIGHT_TYPE") inputFile >> content2 >> content3; else if (content == "CAPACITY") inputFile >> content2 >> vehicleCapacity; else if (content == "DISTANCE") { inputFile >> content2 >> durationLimit; isDurationConstraint = true; } else if (content == "SERVICE_TIME") inputFile >> content2 >> serviceTimeData; else throw std::string("Unexpected data in input file: " + content); } if (nbClients <= 0) throw std::string("Number of nodes is undefined"); if (vehicleCapacity == 1.e30) throw std::string("Vehicle capacity is undefined"); // Reading client coordinates cli = std::vector<Client>(nbClients + 1); for (int i = 0; i <= nbClients; i++) { inputFile >> cli[i].custNum >> cli[i].coordX >> cli[i].coordY; cli[i].custNum--; cli[i].polarAngle = CircleSector::positive_mod(32768.*atan2(cli[i].coordY - cli[0].coordY, cli[i].coordX - cli[0].coordX) / PI); } // Reading demand information inputFile >> content; if (content != "DEMAND_SECTION") throw std::string("Unexpected data in input file: " + content); for (int i = 0; i <= nbClients; i++) { inputFile >> content >> cli[i].demand; cli[i].serviceDuration = (i == 0) ? 0. : serviceTimeData ; if (cli[i].demand > maxDemand) maxDemand = cli[i].demand; totalDemand += cli[i].demand; } // Reading depot information (in all current instances the depot is represented as node 1, the program will return an error otherwise) inputFile >> content >> content2 >> content3 >> content3; if (content != "DEPOT_SECTION") throw std::string("Unexpected data in input file: " + content); if (content2 != "1") throw std::string("Expected depot index 1 instead of " + content2); if (content3 != "EOF") throw std::string("Unexpected data in input file: " + content3); } else throw std::invalid_argument("Impossible to open instance file: " + pathToInstance); // Default initialization if the number of vehicles has not been provided by the user if (nbVehicles == INT_MAX) { nbVehicles = std::ceil(1.2*totalDemand/vehicleCapacity) + 2; // Safety margin: 20% + 2 more vehicles than the trivial bin packing LB std::cout << "----- FLEET SIZE WAS NOT SPECIFIED: DEFAULT INITIALIZATION TO " << nbVehicles << " VEHICLES" << std::endl; } else { std::cout << "----- FLEET SIZE SPECIFIED IN THE COMMANDLINE: SET TO " << nbVehicles << " VEHICLES" << std::endl; } // Calculation of the distance matrix maxDist = 0.; timeCost = std::vector < std::vector< double > >(nbClients + 1, std::vector <double>(nbClients + 1)); for (int i = 0; i <= nbClients; i++) { for (int j = 0; j <= nbClients; j++) { double d = std::sqrt((cli[i].coordX - cli[j].coordX)*(cli[i].coordX - cli[j].coordX) + (cli[i].coordY - cli[j].coordY)*(cli[i].coordY - cli[j].coordY)); if (isRoundingInteger) { d += 0.5; d = (double)(int)d; } // integer rounding if (d > maxDist) maxDist = d; timeCost[i][j] = d; } } // Calculation of the correlated vertices for each customer (for the granular restriction) correlatedVertices = std::vector < std::vector < int > >(nbClients + 1); std::vector < std::set < int > > setCorrelatedVertices = std::vector < std::set <int> >(nbClients + 1); std::vector < std::pair <double, int> > orderProximity; for (int i = 1; i <= nbClients; i++) { orderProximity.clear(); for (int j = 1; j <= nbClients; j++) if (i != j) orderProximity.push_back(std::pair <double, int>(timeCost[i][j], j)); std::sort(orderProximity.begin(), orderProximity.end()); for (int j = 0; j < std::min<int>(nbGranular, nbClients - 1); j++) { // If i is correlated with j, then j should be correlated with i setCorrelatedVertices[i].insert(orderProximity[j].second); setCorrelatedVertices[orderProximity[j].second].insert(i); } } // Filling the vector of correlated vertices for (int i = 1; i <= nbClients; i++) for (int x : setCorrelatedVertices[i]) correlatedVertices[i].push_back(x); // Safeguards to avoid possible numerical instability in case of instances containing arbitrarily small or large numerical values if (maxDist < 0.1 || maxDist > 100000) throw std::string("The distances are of very small or large scale. This could impact numerical stability. Please rescale the dataset and run again."); if (maxDemand < 0.1 || maxDemand > 100000) throw std::string("The demand quantities are of very small or large scale. This could impact numerical stability. Please rescale the dataset and run again."); if (nbVehicles < std::ceil(totalDemand / vehicleCapacity)) throw std::string("Fleet size is insufficient to service the considered clients."); // A reasonable scale for the initial values of the penalties penaltyDuration = 1; penaltyCapacity = std::max<double>(0.1, std::min<double>(1000., maxDist / maxDemand)); }
/* ------------------------------------------------------------------------- * * explain.cpp * Explain query execution plans * * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994-5, Regents of the University of California * * IDENTIFICATION * src/gausskernel/optimizer/commands/explain.cpp * * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "access/tableam.h" #include "access/xact.h" #include "catalog/indexing.h" #include "catalog/namespace.h" #include "catalog/pg_collation.h" #include "catalog/gs_obsscaninfo.h" #include "catalog/pg_obsscaninfo.h" #include "catalog/pg_type.h" #include "commands/createas.h" #include "commands/defrem.h" #include "commands/prepare.h" #include "executor/execStream.h" #include "executor/hashjoin.h" #include "executor/lightProxy.h" #include "executor/nodeAgg.h" #include "executor/nodeRecursiveunion.h" #include "executor/nodeSetOp.h" #include "foreign/dummyserver.h" #include "foreign/fdwapi.h" #include "nodes/print.h" #include "opfusion/opfusion_util.h" #include "opfusion/opfusion.h" #include "optimizer/cost.h" #include "optimizer/clauses.h" #include "optimizer/dataskew.h" #include "optimizer/dynsmp.h" #include "optimizer/ml_model.h" #include "optimizer/nodegroups.h" #include "optimizer/streamplan.h" #include "optimizer/planmem_walker.h" #include "optimizer/planner.h" #include "optimizer/randomplan.h" #include "parser/parse_hint.h" #include "parser/parsetree.h" #include "rewrite/rewriteHandler.h" #include "tcop/tcopprot.h" #include "utils/builtins.h" #include "utils/hotkey.h" #include "utils/json.h" #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/rel_gs.h" #include "utils/snapmgr.h" #include "utils/tuplesort.h" #include "utils/typcache.h" #include "utils/xml.h" #include "utils/batchsort.h" #include "vecexecutor/vechashagg.h" #include "vecexecutor/vechashjoin.h" #include "vecexecutor/vecsetop.h" #include "vectorsonic/vsonichashagg.h" #include "workload/cpwlm.h" #include "workload/workload.h" #include "pgxc/execRemote.h" #ifdef PGXC #include "pgxc/groupmgr.h" #include "catalog/pgxc_node.h" #include "pgxc/pgxc.h" #endif /* Thread local variables for plan_table. */ THR_LOCAL bool OnlySelectFromPlanTable = false; THR_LOCAL bool OnlyDeleteFromPlanTable = false; THR_LOCAL bool PTFastQueryShippingStore = true; THR_LOCAL bool IsExplainPlanStmt = false; THR_LOCAL bool IsExplainPlanSelectForUpdateStmt = false; /* Hook for plugins to get control in explain_get_index_name() */ THR_LOCAL explain_get_index_name_hook_type explain_get_index_name_hook = NULL; extern TrackDesc trackdesc[]; extern sortMessage sortmessage[]; /* Array to record plan table column names, type, etc */ static const PlanTableEntry plan_table_cols[] = {{"id", PLANID, INT4OID, ANAL_OPT}, {"operation", PLAN, TEXTOID, ANAL_OPT}, {"A-time", ACTUAL_TIME, TEXTOID, ANAL_OPT}, {"P-time", PREDICT_TIME, TEXTOID, PRED_OPT_TIME}, {"A-rows", ACTUAL_ROWS, FLOAT8OID, ANAL_OPT}, {"P-rows", PREDICT_ROWS, FLOAT8OID, PRED_OPT_ROW}, {"E-rows", ESTIMATE_ROWS, FLOAT8OID, COST_OPT}, {"E-distinct", ESTIMATE_DISTINCT, TEXTOID, VERBOSE_OPT}, {"Peak Memory", ACTUAL_MEMORY, TEXTOID, ANAL_OPT}, {"P-memory", PREDICT_MEMORY, TEXTOID, PRED_OPT_MEM}, {"E-memory", ESTIMATE_MEMORY, TEXTOID, COST_OPT}, {"A-width", ACTUAL_WIDTH, TEXTOID, ANAL_OPT}, {"E-width", ESTIMATE_WIDTH, INT4OID, COST_OPT}, {"E-costs", ESTIMATE_COSTS, TEXTOID, COST_OPT} }; #define NUM_VER_COLS 1 #define NUM_ANALYZE_COLS 4 #define NUM_COST_COLS 4 #define MIN_FILE_NUM 1024 #define MIN_DISK_USED 1024 /* OR-able flags for ExplainXMLTag() */ #define X_OPENING 0 #define X_CLOSING 1 #define X_CLOSE_IMMEDIATE 2 #define X_NOWHITESPACE 4 #define PUSHDOWN_PREDICATE_FLAG "Pushdown Predicate Filter" #define PUSHDOWN_FILTER_INFORMATIONAL_CONSTRAINT_FLAG "Pushdown Predicate Filter(Informational Constraint Optimization)" #define FILTER_INFORMATIONAL_CONSTRAINT_FLAG "Filter(Informational Constraint Optimization)" #define FILTER_FLAG "Filter" static void ExplainOneQuery( Query* query, IntoClause* into, ExplainState* es, const char* queryString, DestReceiver *dest, ParamListInfo params); static void report_triggers(ResultRelInfo* rInfo, bool show_relname, ExplainState* es); template <bool is_pretty> static void ExplainNode( PlanState* planstate, List* ancestors, const char* relationship, const char* plan_name, ExplainState* es); static void CalculateProcessedRows( PlanState* planstate, int idx, int smpIdx, const uint64* innerRows, const uint64* outterRows, uint64* processedrows); static void show_plan_execnodes(PlanState* planstate, ExplainState* es); static void show_plan_tlist(PlanState* planstate, List* ancestors, ExplainState* es); static bool ContainRlsQualInRteWalker(Node* node, void* unused_info); static void show_expression( Node* node, const char* qlabel, PlanState* planstate, List* ancestors, bool useprefix, ExplainState* es); static void show_qual( List* qual, const char* qlabel, PlanState* planstate, List* ancestors, bool useprefix, ExplainState* es); static void show_scan_qual(List* qual, const char* qlabel, PlanState* planstate, List* ancestors, ExplainState* es); static void show_skew_optimization(const PlanState* planstate, ExplainState* es); template <bool generate> static void show_bloomfilter(Plan* plan, PlanState* planstate, List* ancestors, ExplainState* es); template <bool generate> static void show_bloomfilter_number(const List* filterNumList, ExplainState* es); /** * @Description: Show pushdown quals in the flag identifier. * @in planstate: Keep the current state of the plan node. * @in ancestors: A list of parent PlanState nodes, most-closely-nested first. * @in identifier: The label of pushdown predicate clause. * @in es: A ExplainState struct. * @return None. */ static void show_pushdown_qual(PlanState* planstate, List* ancestors, ExplainState* es, const char* identifier); static void show_upper_qual(List* qual, const char* qlabel, PlanState* planstate, List* ancestors, ExplainState* es); static void show_groupby_keys(AggState* aggstate, List* ancestors, ExplainState* es); static void show_sort_keys(SortState* sortstate, List* ancestors, ExplainState* es); static void show_merge_append_keys(MergeAppendState* mstate, List* ancestors, ExplainState* es); static void show_merge_sort_keys(PlanState* state, List* ancestors, ExplainState* es); static void show_sort_info(SortState* sortstate, ExplainState* es); static void show_hash_info(HashState* hashstate, ExplainState* es); static void show_vechash_info(VecHashJoinState* hashstate, ExplainState* es); static void show_instrumentation_count(const char* qlabel, int which, const PlanState* planstate, ExplainState* es); static void show_removed_rows(int which, const PlanState* planstate, int idx, int smpIdx, int* removeRows); static void show_foreignscan_info(ForeignScanState* fsstate, ExplainState* es); static void show_dfs_block_info(PlanState* planstate, ExplainState* es); static void show_detail_storage_info_text(Instrumentation* instr, StringInfo instr_info); static void show_detail_storage_info_json(Instrumentation* instr, StringInfo instr_info, ExplainState* es); static void show_storage_filter_info(PlanState* planstate, ExplainState* es); static void show_llvm_info(const PlanState* planstate, ExplainState* es); static void show_modifytable_merge_info(const PlanState* planstate, ExplainState* es); static void show_recursive_info(RecursiveUnionState* rustate, ExplainState* es); static const char* explain_get_index_name(Oid indexId); static void ExplainIndexScanDetails(Oid indexid, ScanDirection indexorderdir, ExplainState* es); static void ExplainScanTarget(Scan* plan, ExplainState* es); static void ExplainModifyTarget(ModifyTable* plan, ExplainState* es); static void ExplainTargetRel(Plan* plan, Index rti, ExplainState* es); static void show_on_duplicate_info(ModifyTableState* mtstate, ExplainState* es); #ifndef PGXC static void show_modifytable_info(ModifyTableState* mtstate, ExplainState* es); #endif /* PGXC */ static void ExplainMemberNodes(const List* plans, PlanState** planstates, List* ancestors, ExplainState* es); static void ExplainSubPlans(List* plans, List* ancestors, const char* relationship, ExplainState* es); static void ExplainProperty(const char* qlabel, const char* value, bool numeric, ExplainState* es); static void ExplainOpenGroup(const char* objtype, const char* labelname, bool labeled, ExplainState* es); static void ExplainCloseGroup(const char* objtype, const char* labelname, bool labeled, ExplainState* es); static void ExplainDummyGroup(const char* objtype, const char* labelname, ExplainState* es); #ifdef PGXC static void ExplainExecNodes(const ExecNodes* en, ExplainState* es); static void ExplainRemoteQuery(RemoteQuery* plan, PlanState* planstate, List* ancestors, ExplainState* es); #endif static void ExplainXMLTag(const char* tagname, unsigned int flags, ExplainState* es); static void ExplainJSONLineEnding(ExplainState* es); static void ExplainYAMLLineStarting(ExplainState* es); static void escape_yaml(StringInfo buf, const char* str); template <bool is_detail> static void show_time(ExplainState* es, const Instrumentation* instrument, int idx); static void show_cpu(ExplainState* es, const Instrumentation* instrument, double innerCycles, double outerCycles, int nodeIdx, int smpIdx, uint64 proRows); static void show_detail_cpu(ExplainState* es, PlanState* planstate); static void show_datanode_buffers(ExplainState* es, PlanState* planstate); static void show_buffers(ExplainState* es, StringInfo infostr, const Instrumentation* instrument, bool is_datanode, int nodeIdx, int smpIdx, const char* nodename); static void show_datanode_time(ExplainState* es, PlanState* planstate); static void ShowStreamRunNodeInfo(Stream* stream, ExplainState* es); static void ShowRunNodeInfo(const ExecNodes* en, ExplainState* es, const char* qlabel); template <bool is_detail> static void show_datanode_hash_info(ExplainState* es, int nbatch, int nbatch_original, int nbuckets, long spacePeakKb); static void ShowRoughCheckInfo(ExplainState* es, Instrumentation* instrument, int nodeIdx, int smpIdx); static void show_hashAgg_info(AggState* hashaggstate, ExplainState* es); static void ExplainPrettyList(List* data, ExplainState* es); static void show_pretty_time(ExplainState* es, Instrumentation* instrument, char* node_name, int nodeIdx, int smpIdx, int dop, bool executed = true); static void show_analyze_buffers(ExplainState* es, const PlanState* planstate, StringInfo infostr, int nodeNum); inline static void show_cpu_info(StringInfo infostr, double incCycles, double exCycles, uint64 proRows); static void show_track_time_info(ExplainState* es); template <bool datanode> static void show_child_cpu_cycles_and_rows(PlanState* planstate, int idx, int smpIdx, double* outerCycles, double* innerCycles, uint64* outterRows, uint64* innerRows); template <bool datanode> static void CalCPUMemberNode(const List* plans, PlanState** planstates, int idx, int smpIdx, double* Cycles); static void showStreamnetwork(Stream* stream, ExplainState* es); static int get_digit(int value); template <bool datanode> static void get_oper_time(ExplainState* es, PlanState* planstate, const Instrumentation* instr, int nodeIdx, int smpIdx); static void show_peak_memory(ExplainState* es, int plan_size); static bool get_execute_mode(const ExplainState* es, int idx); static void show_setop_info(SetOpState* setopstate, ExplainState* es); static void show_grouping_sets(PlanState* planstate, Agg* agg, List* ancestors, ExplainState* es); static void show_group_keys(GroupState* gstate, List* ancestors, ExplainState* es); static void show_sort_group_keys(PlanState* planstate, const char* qlabel, int nkeys, const AttrNumber* keycols, const Oid* sortOperators, const Oid* collations, const bool* nullsFirst, List* ancestors, ExplainState* es); static void show_sortorder_options(StringInfo buf, const Node* sortexpr, Oid sortOperator, Oid collation, bool nullsFirst); static void show_grouping_set_keys(PlanState* planstate, Agg* aggnode, Sort* sortnode, List* context, bool useprefix, List* ancestors, ExplainState* es); static void show_dn_executor_time(ExplainState* es, int plan_node_id, ExecutorTime stage); static void show_stream_send_time(ExplainState* es, const PlanState* planstate); static void append_datanode_name(ExplainState* es, char* node_name, int dop, int j); static void show_tablesample(Plan* plan, PlanState* planstate, List* ancestors, ExplainState* es); void insert_obsscaninfo( uint64 queryid, const char* rel_name, int64 file_count, double scan_data_size, double total_time, int format); extern List* get_str_targetlist(List* fdw_private); static void show_wlm_explain_name(ExplainState* es, const char* plan_name, const char* pname, int plan_node_id); extern unsigned char pg_toupper(unsigned char ch); static char* set_strtoupper(const char* str, uint32 len); #ifdef ENABLE_MULTIPLE_NODES static bool show_scan_distributekey(const Plan* plan) { return ( IsA(plan, CStoreScan) || IsA(plan, CStoreIndexScan) || IsA(plan, CStoreIndexHeapScan) || IsA(plan, SeqScan) || IsA(plan, DfsScan) || IsA(plan, IndexScan) || IsA(plan, IndexOnlyScan) || IsA(plan, CteScan) || IsA(plan, ForeignScan) || IsA(plan, VecForeignScan) || IsA(plan, BitmapHeapScan) || IsA(plan, TsStoreScan) ); } #endif /* ENABLE_MULTIPLE_NODES */ static void show_unique_check_info(PlanState *planstate, ExplainState *es); /* * ExplainQuery - * execute an EXPLAIN command */ void ExplainQuery( ExplainStmt* stmt, const char* queryString, ParamListInfo params, DestReceiver* dest, char* completionTag) { ExplainState es; TupOutputState* tstate = NULL; List* rewritten = NIL; ListCell* lc = NULL; bool timing_set = false; /* Initialize ExplainState. */ ExplainInitState(&es); /* Parse options list. */ foreach (lc, stmt->options) { DefElem* opt = (DefElem*)lfirst(lc); /* * For explain plan stmt: * 1.Cache the plan instead of printing it, and return 'EXPLAIN SUCCESS'. * 2.Insert the cached info into plan_table, then user can get plan info when select from table; * 3.As the explain option "PLAN" cannot work with other options, * when other options are detected, report as an error. * 4.And we do not support execute it on DN now. * */ if (strcmp(opt->defname, "plan") == 0) { es.plan = defGetBoolean(opt); if (es.plan) { #ifdef ENABLE_MULTIPLE_NODES /* We do not support execute explain plan on pgxc datanode or single node. */ if (IS_PGXC_DATANODE || IS_SINGLE_NODE) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXPLAIN PLAN does not support on datanode or single node."))); #endif /* If explain option is "PLAN", it must only has one option. */ if (list_length(stmt->options) != 1) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("EXPLAIN option 'PLAN' can not work with other options."))); /* For explain plan stmt: we mark it to generate plan node id for cte case. */ IsExplainPlanStmt = true; /* * To collect plan info for explain plan, we don't use FQS. * However, select for update can only run when enable_fast_query_shipping = on, * so we should set IsExplainPlanSelectForUpdateStmt = true to make enable_fast_query_shipping work. */ if (IsA(stmt->query, Query) && ((Query*)stmt->query)->hasForUpdate) IsExplainPlanSelectForUpdateStmt = true; /* Trun off fast_query_shipping to collect more plan info. */ if (PTFastQueryShippingStore == true && IsExplainPlanSelectForUpdateStmt == false) PTFastQueryShippingStore = false; /* Get statement_id from ExplainStmt. */ if (stmt->statement == NULL) es.statement_id = NULL; else { Value v = ((A_Const*)stmt->statement)->val; if (v.type == T_Null) es.statement_id = NULL; else es.statement_id = v.val.str; } /* results are discarded for explain plan we will returen "EXPLAIN SUCCESS" */ dest->mydest = DestNone; t_thrd.explain_cxt.explain_perf_mode = EXPLAIN_PRETTY; /* set completionTag */ errno_t errorno = snprintf_s(completionTag, COMPLETION_TAG_BUFSIZE, COMPLETION_TAG_BUFSIZE - 1, "EXPLAIN SUCCESS"); securec_check_ss(errorno, "\0", "\0"); } } else if (strcmp(opt->defname, "analyze") == 0) es.analyze = defGetBoolean(opt); else if (strcmp(opt->defname, "verbose") == 0) es.verbose = defGetBoolean(opt); else if (strcmp(opt->defname, "costs") == 0) es.costs = defGetBoolean(opt); else if (strcmp(opt->defname, "buffers") == 0) es.buffers = defGetBoolean(opt); #ifdef ENABLE_MULTIPLE_NODES #ifdef PGXC else if (strcmp(opt->defname, "nodes") == 0) es.nodes = defGetBoolean(opt); else if (strcmp(opt->defname, "num_nodes") == 0) es.num_nodes = defGetBoolean(opt); #endif /* PGXC */ #endif /* ENABLE_MULTIPLE_NODES */ else if (strcmp(opt->defname, "timing") == 0) { timing_set = true; es.timing = defGetBoolean(opt); } else if (pg_strcasecmp(opt->defname, "cpu") == 0) es.cpu = defGetBoolean(opt); else if (pg_strcasecmp(opt->defname, "detail") == 0) es.detail = defGetBoolean(opt); else if (pg_strcasecmp(opt->defname, "performance") == 0) es.performance = defGetBoolean(opt); else if (strcmp(opt->defname, "format") == 0) { char* p = defGetString(opt); if (strcmp(p, "text") == 0) es.format = EXPLAIN_FORMAT_TEXT; else if (strcmp(p, "xml") == 0) es.format = EXPLAIN_FORMAT_XML; else if (strcmp(p, "json") == 0) es.format = EXPLAIN_FORMAT_JSON; else if (strcmp(p, "yaml") == 0) es.format = EXPLAIN_FORMAT_YAML; else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unrecognized value for EXPLAIN option \"%s\": \"%s\"", opt->defname, p))); #ifndef ENABLE_MULTIPLE_NODES } else if (strcmp(opt->defname, "predictor") == 0) { es.opt_model_name = defGetString(opt); #endif } else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unrecognized EXPLAIN option \"%s\"", opt->defname))); } if (es.performance) { es.analyze = true; es.buffers = true; es.costs = true; es.cpu = true; es.detail = true; #ifdef ENABLE_MULTIPLE_NODES #ifdef PGXC es.nodes = true; es.num_nodes = true; #endif /* PGXC */ #endif /* ENABLE_MULTIPLE_NODES */ es.timing = true; es.verbose = true; } if (es.buffers && !es.analyze) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EXPLAIN option BUFFERS requires ANALYZE"))); if (es.cpu && !es.analyze) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EXPLAIN option CPU requires ANALYZE"))); if (es.detail && !es.analyze) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EXPLAIN option DETAIL requires ANALYZE"))); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es.format != EXPLAIN_FORMAT_TEXT) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("explain_perf_mode requires FORMAT TEXT"))); /* if the timing was not set explicitly, set default value */ es.timing = (timing_set) ? es.timing : es.analyze; /* check that timing is used with EXPLAIN ANALYZE */ if (es.timing && !es.analyze) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EXPLAIN option TIMING requires ANALYZE"))); /* * Parse analysis was done already, but we still have to run the rule * rewriter. We do not do AcquireRewriteLocks: we assume the query either * came straight from the parser, or suitable locks were acquired by * plancache.c. * * Because the rewriter and planner tend to scribble on the input, we make * a preliminary copy of the source querytree. This prevents problems in * the case that the EXPLAIN is in a portal or plpgsql function and is * executed repeatedly. (See also the same hack in DECLARE CURSOR and * PREPARE.) */ AssertEreport(IsA(stmt->query, Query), MOD_EXECUTOR, "unexpect query type"); rewritten = QueryRewrite((Query*)copyObject(stmt->query)); /* emit opening boilerplate */ ExplainBeginOutput(&es); if (rewritten == NIL) { /* * In the case of an INSTEAD NOTHING, tell at least that. But in * non-text format, the output is delimited, so this isn't necessary. */ if (es.format == EXPLAIN_FORMAT_TEXT) appendStringInfoString(es.str, "Query rewrites to nothing\n"); } else { ListCell* l = NULL; /* Specially, not explain LightCN when explain analyze */ t_thrd.explain_cxt.explain_light_proxy = IS_PGXC_COORDINATOR && !IsConnFromCoord() && u_sess->attr.attr_sql.enable_light_proxy && (list_length(rewritten) == 1) && !es.analyze; /* For explain auto-analyze time */ if (u_sess->attr.attr_sql.enable_autoanalyze && es.analyze && t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { /* can be not NULL if last-time explain reports error */ MemoryContext oldcontext = MemoryContextSwitchTo(u_sess->temp_mem_cxt); u_sess->analyze_cxt.autoanalyze_timeinfo = makeStringInfo(); (void)MemoryContextSwitchTo(oldcontext); } else u_sess->analyze_cxt.autoanalyze_timeinfo = NULL; /* show real running datanodes if analyze/performance for pbe */ if (IS_PGXC_COORDINATOR && !IsConnFromCoord() && es.analyze) { t_thrd.postgres_cxt.mark_explain_analyze = true; t_thrd.postgres_cxt.mark_explain_only = false; } else { t_thrd.postgres_cxt.mark_explain_analyze = false; t_thrd.postgres_cxt.mark_explain_only = true; } /* Explain every plan */ foreach (l, rewritten) { ExplainOneQuery((Query*)lfirst(l), NULL, &es, queryString, None_Receiver, params); /* Separate plans with an appropriate separator */ if (lnext(l) != NULL) ExplainSeparatePlans(&es); } t_thrd.explain_cxt.explain_light_proxy = false; } /* emit closing boilerplate */ ExplainEndOutput(&es); AssertEreport(es.indent == 0, MOD_EXECUTOR, "unexpect es.indent value"); /* Do not print plan when option is 'plan' and mydest should be set to 'DestNone'. */ if (!es.plan) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { es.planinfo->dump(dest); } else { /* output tuples */ tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt)); if (es.format == EXPLAIN_FORMAT_TEXT) (void)do_text_output_multiline(tstate, es.str->data); else do_text_output_oneline(tstate, es.str->data); end_tup_output(tstate); } } #ifdef ENABLE_MULTIPLE_NODES if (u_sess->instr_cxt.global_instr != NULL) { delete u_sess->instr_cxt.global_instr; u_sess->instr_cxt.thread_instr = NULL; u_sess->instr_cxt.global_instr = NULL; } #endif /* ENABLE_MULTIPLE_NODES */ if (u_sess->analyze_cxt.autoanalyze_timeinfo != NULL) { pfree_ext(u_sess->analyze_cxt.autoanalyze_timeinfo->data); pfree_ext(u_sess->analyze_cxt.autoanalyze_timeinfo); u_sess->analyze_cxt.autoanalyze_timeinfo = NULL; } stmt->planinfo = es.planinfo; pfree_ext(es.str->data); list_free_deep(rewritten); } /* * Initialize ExplainState. */ void ExplainInitState(ExplainState* es) { /* Set default options. */ errno_t rc = memset_s(es, sizeof(ExplainState), 0, sizeof(ExplainState)); securec_check(rc, "\0", "\0"); es->costs = true; #ifdef ENABLE_MULTIPLE_NODES #ifdef PGXC es->nodes = true; #endif /* PGXC */ #endif /* ENABLE_MULTIPLE_NODES */ /* Prepare output buffer. */ es->str = makeStringInfo(); es->planinfo = NULL; es->from_dn = false; es->sql_execute = true; es->isexplain_execute = false; es->datanodeinfo.all_datanodes = true; es->datanodeinfo.len_nodelist = 0; es->datanodeinfo.node_index = NULL; es->indent = 0; es->pindent = 0; es->wlm_statistics_plan_max_digit = NULL; /* Reset flag for plan_table. */ IsExplainPlanStmt = false; IsExplainPlanSelectForUpdateStmt = false; } /* * ExplainResultDesc - * construct the result tupledesc for an EXPLAIN */ TupleDesc ExplainResultDesc(ExplainStmt* stmt) { TupleDesc tupdesc = NULL; ListCell* lc = NULL; Oid result_type = TEXTOID; char* attributeName = NULL; char RandomPlanName[NAMEDATALEN] = {0}; bool explain_plan = false; /* for explain plan stmt */ /* Check for XML format option */ foreach (lc, stmt->options) { DefElem* opt = (DefElem*)lfirst(lc); if (strcmp(opt->defname, "format") == 0) { char* p = defGetString(opt); if (strcmp(p, "xml") == 0) result_type = XMLOID; else if (strcmp(p, "json") == 0) result_type = JSONOID; else result_type = TEXTOID; /* don't "break", as ExplainQuery will use the last value */ } else if (strcmp(opt->defname, "plan") == 0 && defGetBoolean(opt) && list_length(stmt->options) == 1) { /* For explain plan */ explain_plan = true; } } if (!explain_plan) { /* Need a tuple descriptor representing a single TEXT or XML column */ tupdesc = CreateTemplateTupleDesc(1, false, TAM_HEAP); /* If current plan is set as random plan, explain desc should show random seed value */ if (u_sess->attr.attr_sql.plan_mode_seed != OPTIMIZE_PLAN) { int rc = 0; rc = snprintf_s( RandomPlanName, NAMEDATALEN, NAMEDATALEN - 1, "QUERY PLAN (RANDOM seed %u)", get_inital_plan_seed()); securec_check_ss(rc, "\0", "\0"); } attributeName = ((OPTIMIZE_PLAN == u_sess->attr.attr_sql.plan_mode_seed) ? (char*)"QUERY PLAN" : RandomPlanName); TupleDescInitEntry(tupdesc, (AttrNumber)1, attributeName, result_type, -1, 0); } return tupdesc; } /* * ExplainOneQuery - * print out the execution plan for one Query * * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt. */ static void ExplainOneQuery( Query* query, IntoClause* into, ExplainState* es, const char* queryString, DestReceiver *dest, ParamListInfo params) { /* only use t_thrd.explain_cxt.explain_light_proxy once */ if (t_thrd.explain_cxt.explain_light_proxy) { ExecNodes* single_exec_node = lightProxy::checkLightQuery(query); if (single_exec_node == NULL || list_length(single_exec_node->nodeList) + list_length(single_exec_node->primarynodelist) != 1) { t_thrd.explain_cxt.explain_light_proxy = false; } CleanHotkeyCandidates(true); } u_sess->exec_cxt.remotequery_list = NIL; /* planner will not cope with utility statements */ if (query->commandType == CMD_UTILITY) { if (IsA(query->utilityStmt, CreateTableAsStmt)) { CreateTableAsStmt* ctas = (CreateTableAsStmt*)query->utilityStmt; List* rewritten = NIL; // INSERT INTO statement needs target table to be created first, // so we just support EXPLAIN ANALYZE. // if (!es->analyze) { const char* stmt = ctas->is_select_into ? "SELECT INTO" : "CREATE TABLE AS SELECT"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EXPLAIN %s requires ANALYZE", stmt))); } // CREATE TABLE AS SELECT and SELECT INTO are rewritten so that the // target table is created first. The SELECT query is then transformed // into an INSERT INTO statement. // rewritten = QueryRewriteCTAS(query); ExplainOneQuery((Query*)linitial(rewritten), ctas->into, es, queryString, dest, params); return; } ExplainOneUtility(query->utilityStmt, into, es, queryString, params); return; } /* * Query is not actually executed when declaring a cursor, but will generate a plan. * So we can use explain to print the plan, but can not use explain analyze to execute the query. */ if (query->utilityStmt && IsA(query->utilityStmt, DeclareCursorStmt)) { const char* s = es->performance ? "PERFORMANCE" : "ANALYZE"; if (es->analyze) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("EXPLAIN %s is not supported when declaring a cursor.", s), errdetail("Query is not actually executed when declaring a cursor."))); } PlannedStmt* plan = NULL; /* plan the query */ plan = pg_plan_query(query, 0, params, true); CleanHotkeyCandidates(true); check_gtm_free_plan((PlannedStmt *)plan, es->analyze ? ERROR : WARNING); check_plan_mergeinto_replicate(plan, es->analyze ? ERROR : WARNING); es->is_explain_gplan = true; /* run it (if needed) and produce output */ ExplainOnePlan(plan, into, es, queryString, dest, params); } /* * ExplainOneUtility - * print out the execution plan for one utility statement * (In general, utility statements don't have plans, but there are some * we treat as special cases) * * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt. * * This is exported because it's called back from prepare.c in the * EXPLAIN EXECUTE case. */ void ExplainOneUtility( Node* utilityStmt, IntoClause* into, ExplainState* es, const char* queryString, ParamListInfo params) { if (utilityStmt == NULL) return; if (IsA(utilityStmt, ExecuteStmt)) ExplainExecuteQuery((ExecuteStmt*)utilityStmt, into, es, queryString, params); else if (IsA(utilityStmt, NotifyStmt)) { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoString(es->str, "NOTIFY\n"); else ExplainDummyGroup("Notify", NULL, es); } else { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoString(es->str, "Utility statements have no plan structure\n"); else ExplainDummyGroup("Utility Statement", NULL, es); } } /* * @Description: read data from channel and get data before print performance data * @in estate - estate information * @out - void */ static void ExecRemoteprocessPlan(EState* estate) { ListCell* lc = NULL; foreach (lc, estate->es_remotequerystates) { PlanState* ps = (PlanState*)lfirst(lc); ExecEndRemoteQuery((RemoteQueryState*)ps, true); } } /* * @Description: Find real exec dn nodes within all RemoteQuery PlanNodes. * @in qd - queryDesc information * @out - void */ static void GetNodeList(QueryDesc* qd) { ListCell* lc = NULL; ListCell* lc2 = NULL; RemoteQuery* rq = NULL; foreach (lc, u_sess->exec_cxt.remotequery_list) { rq = (RemoteQuery*)lfirst(lc); /* * when execute pbe query, rq->exec_nodes->nodeList could be NIL, * so we should get nodeLists through FindExecNodesInPBE function. */ if (rq->exec_nodes != NULL && rq->exec_nodes->nodeList == NIL) { foreach (lc2, qd->estate->es_remotequerystates) { RemoteQueryState* rqs = (RemoteQueryState*)lfirst(lc2); /* find node_lists and fill in exec_nodes */ FindExecNodesInPBE(rqs, rq->exec_nodes, EXEC_ON_DATANODES); } } } } /* * @Description: Reorganize the executed query which will be pushed down to DN node. * @in es - explainstate information * @in rq - remote query plannode * @in queryString - prepared sql statement in pbe or simple queryString * @in explain_sql - executed sql statement in pbe * @in nodeoid - DN nodeoid * @out - void */ void ReorganizeSqlStatement( ExplainState* es, RemoteQuery* rq, const char* queryString, const char* explain_sql, Oid nodeoid) { const char* perf_mode = NULL; switch (u_sess->attr.attr_sql.guc_explain_perf_mode) { case EXPLAIN_NORMAL: perf_mode = "normal"; break; case EXPLAIN_PRETTY: perf_mode = "pretty"; break; case EXPLAIN_SUMMARY: perf_mode = "summary"; break; case EXPLAIN_RUN: perf_mode = "run"; break; default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for parameter explain_perf_mode."))); break; } const char* format = NULL; switch (es->format) { case EXPLAIN_FORMAT_TEXT: format = "text"; break; case EXPLAIN_FORMAT_XML: format = "xml"; break; case EXPLAIN_FORMAT_JSON: format = "json"; break; case EXPLAIN_FORMAT_YAML: format = "yaml"; break; default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unrecognized value for EXPLAIN option \"format\"."))); break; } const char* verbose = es->verbose ? "on" : "off"; const char* costs = es->costs ? "on" : "off"; const char* num_nodes = es->num_nodes ? "on" : "off"; StringInfo prefix = makeStringInfo(); appendStringInfo(prefix, "set explain_perf_mode=%s; " "explain (format %s, verbose %s, costs %s, nodes off, num_nodes %s)", perf_mode, format, verbose, costs, num_nodes); if (es->isexplain_execute && !CheckPrepared(rq, nodeoid)) { /* * When execute firstly explain pbe statement in dfx, we should send * prepared statement and execute statement at the same time. * Also, we should not need to deallocate prepare statement, because * prepared statement in DN will only be sent once. */ StringInfo sql = makeStringInfo(); appendStringInfo(sql, "%s %s %s", queryString, prefix->data, explain_sql); rq->execute_statement = sql->data; } else { StringInfo sql = makeStringInfo(); appendStringInfo(sql, "%s %s", prefix->data, explain_sql); rq->execute_statement = sql->data; } } /* * @Description: Execute FQS query in DN * @in es - explainstate information * @in queryString - prepared sql statement in pbe or simple queryString * @out - void */ static void ExecFQSQueryinDn(ExplainState* es, const char* queryString) { ListCell* lc = NULL; foreach (lc, u_sess->exec_cxt.remotequery_list) { RemoteQuery* rq = (RemoteQuery*)lfirst(lc); int dnnum = 0; StringInfo* rs = SendExplainToDNs(es, rq, &dnnum, queryString); for (int i = 0; i < dnnum; i++) { appendStringInfo(es->str, "%s\n", rs[i]->data); } } } /* * ExplainOnePlan - * given a planned query, execute it if needed, and then print * EXPLAIN output * * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt, * in which case executing the query should result in creating that table. * * Since we ignore any DeclareCursorStmt that might be attached to the query, * if you say EXPLAIN ANALYZE DECLARE CURSOR then we'll actually run the * query. This is different from pre-8.3 behavior but seems more useful than * not running the query. No cursor will be created, however. * * This is exported because it's called back from prepare.c in the * EXPLAIN EXECUTE case, and because an index advisor plugin would need * to call it. */ void ExplainOnePlan( PlannedStmt* plannedstmt, IntoClause* into, ExplainState* es, const char* queryString, DestReceiver *dest, ParamListInfo params) { QueryDesc* queryDesc = NULL; instr_time starttime; instr_time exec_starttime; /* executor init start time */ double exec_totaltime = 0; /* executor init total time */ double execrun_totaltime = 0; /* executor run total time */ double execend_totaltime = 0; /* executor end total time */ double totaltime = 0; int eflags; int instrument_option = 0; if (es->analyze && es->timing) instrument_option |= INSTRUMENT_TIMER; else if (es->analyze) instrument_option |= INSTRUMENT_ROWS; if (es->buffers) instrument_option |= INSTRUMENT_BUFFERS; INSTR_TIME_SET_CURRENT(starttime); /* * Use a snapshot with an updated command ID to ensure this query sees * results of any previously executed queries. */ PushCopiedSnapshot(GetActiveSnapshot()); UpdateActiveSnapshotCommandId(); /* Create a QueryDesc for the query */ queryDesc = CreateQueryDesc( plannedstmt, queryString, GetActiveSnapshot(), InvalidSnapshot, dest, params, instrument_option); queryDesc->plannedstmt->instrument_option = instrument_option; /* Select execution options */ if (es->analyze) eflags = 0; /* default run-to-completion flags */ else eflags = EXEC_FLAG_EXPLAIN_ONLY; if (into != NULL) eflags |= GetIntoRelEFlags(into); #ifdef STREAMPLAN /* * u_sess->exec_cxt.under_stream_runtime is set to true in ExecInitRemoteQuery() if * node->is_simple is true. ExecInitRemoteQuery() will be called during * calling ExecutorStart(queryDesc, eflags). * light performance is changed to allocate streaminstrumentation firstly, * and than calling ExecutorStart for ExecInitNode in CN. */ /* only stream plan can use u_sess->instr_cxt.global_instr to collect executor info */ #ifdef ENABLE_MULTIPLE_NODES if (IS_PGXC_COORDINATOR && #else if (StreamTopConsumerAmI() && #endif queryDesc->plannedstmt->is_stream_plan == true && check_stream_support() && instrument_option != 0 && u_sess->instr_cxt.global_instr == NULL && queryDesc->plannedstmt->num_nodes != 0) { int dop = queryDesc->plannedstmt->query_dop; u_sess->instr_cxt.global_instr = StreamInstrumentation::InitOnCn(queryDesc, dop); // u_sess->instr_cxt.thread_instr in CN u_sess->instr_cxt.thread_instr = u_sess->instr_cxt.global_instr->allocThreadInstrumentation(queryDesc->plannedstmt->planTree->plan_node_id); { AutoContextSwitch cxtGuard(SESS_GET_MEM_CXT_GROUP(MEMORY_CONTEXT_OPTIMIZER)); u_sess->instr_cxt.obs_instr = New(CurrentMemoryContext) OBSInstrumentation(); } } #endif /* call ExecutorStart to prepare the plan for execution */ INSTR_TIME_SET_CURRENT(exec_starttime); if (ENABLE_WORKLOAD_CONTROL && (IS_PGXC_COORDINATOR || IS_SINGLE_NODE)) { /* Check if need track resource */ u_sess->exec_cxt.need_track_resource = ((unsigned int)eflags & EXEC_FLAG_EXPLAIN_ONLY) ? false : WLMNeedTrackResource(queryDesc); } ExecutorStart(queryDesc, eflags); if (u_sess->attr.attr_common.max_datanode_for_plan > 0 && IS_PGXC_COORDINATOR && !IsConnFromCoord() && !es->analyze) { GetNodeList(queryDesc); } exec_totaltime += elapsed_time(&exec_starttime); #ifdef STREAMPLAN /* * Init planinfo when: * 1. explain_perf_mode is not EXPLAIN_NORMAL and it`s a stream plan. * 2. For EXPLAIN PLAN, we still collect plan info. */ if ((t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && IS_STREAM_PLAN && u_sess->exec_cxt.under_stream_runtime) || es->plan) { es->planinfo = (PlanInformation*)palloc0(sizeof(PlanInformation)); es->planinfo->init(es, plannedstmt->num_plannodes, plannedstmt->num_nodes, (plannedstmt->query_mem[0] > 0)); } else t_thrd.explain_cxt.explain_perf_mode = EXPLAIN_NORMAL; #endif /* workload client manager */ if (ENABLE_WORKLOAD_CONTROL && (IS_PGXC_COORDINATOR || IS_SINGLE_NODE)) { if (!((unsigned int)eflags & EXEC_FLAG_EXPLAIN_ONLY)) { WLMInitQueryPlan(queryDesc); dywlm_client_manager(queryDesc); } else if (DY_MEM_ADJ(queryDesc->plannedstmt)) { /* for explain statement, dywlm will not adjust the mem, so adjust it here */ bool use_tenant = (u_sess->wlm_cxt->wlm_params.rpdata.rpoid != DEFAULT_POOL_OID); CalculateQueryMemMain(queryDesc->plannedstmt, use_tenant, true); } } /* Execute the plan for statistics if asked for */ if (es->analyze) { ScanDirection dir; /* EXPLAIN ANALYZE CREATE TABLE AS WITH NO DATA is weird */ if (into != NULL && into->skipData) { dir = NoMovementScanDirection; es->sql_execute = false; } else dir = ForwardScanDirection; if (u_sess->exec_cxt.need_track_resource) { ExplainNodeFinish(queryDesc->planstate, queryDesc->plannedstmt, 0.0, true); } INSTR_TIME_SET_CURRENT(exec_starttime); /* run the plan */ ExecutorRun(queryDesc, dir, 0L); execrun_totaltime += elapsed_time(&exec_starttime); /* run cleanup too */ ExecutorFinish(queryDesc); INSTR_TIME_SET_CURRENT(exec_starttime); /* run cleanup for limit node */ ExecRemoteprocessPlan(queryDesc->estate); execend_totaltime += elapsed_time(&exec_starttime); /* SQL Self-Tuning : Analyze query plan issues based on runtime info when query execution is finished */ if (u_sess->exec_cxt.need_track_resource && u_sess->attr.attr_resource.resource_track_level == RESOURCE_TRACK_OPERATOR) { List* issueResults = PlanAnalyzerOperator(queryDesc, queryDesc->planstate); /* If plan issue is found, store it in sysview gs_wlm_session_history */ if (issueResults != NIL) { RecordQueryPlanIssues(issueResults); } } if (u_sess->exec_cxt.need_track_resource) { u_sess->instr_cxt.can_record_to_table = true; ExplainNodeFinish(queryDesc->planstate, queryDesc->plannedstmt, GetCurrentTimestamp(), false); } /* We can't run ExecutorEnd 'till we're done printing the stats... */ totaltime += elapsed_time(&starttime); } #ifndef ENABLE_MULTIPLE_NODES SetNullPrediction(queryDesc->planstate); /* Call machine learning prediction routine for test */ if (es->opt_model_name != NULL && PredictorIsValid((const char*)es->opt_model_name)) { char* file_name = PreModelPredict(queryDesc->planstate, queryDesc->plannedstmt); ModelPredictForExplain(queryDesc->planstate, file_name, (const char*)es->opt_model_name); } #endif /* ENABLE_MULTIPLE_NODES */ ExplainOpenGroup("Query", NULL, true, es); if (IS_PGXC_DATANODE && u_sess->attr.attr_sql.enable_opfusion == true && es->format == EXPLAIN_FORMAT_TEXT && u_sess->attr.attr_sql.enable_hypo_index == false) { FusionType type = OpFusion::getFusionType(NULL, params, list_make1(queryDesc->plannedstmt)); if (!es->is_explain_gplan) type = NOBYPASS_NO_CPLAN; if (type < BYPASS_OK && type > NONE_FUSION) { appendStringInfo(es->str, "[Bypass]\n"); } else if (u_sess->attr.attr_sql.opfusion_debug_mode == BYPASS_LOG) { appendStringInfo(es->str, "[No Bypass]"); const char* bypass_reason = getBypassReason(type); appendStringInfo(es->str, "reason: %s.\n", bypass_reason); } } /* Create textual dump of plan tree */ ExplainPrintPlan(es, queryDesc); /* for explain plan: after explained all nodes */ if (es->plan && es->planinfo != NULL) { es->planinfo->m_planTableData->set_plan_table_ids(queryDesc->plannedstmt->queryId, es); /* insert all nodes` tuple into table. */ es->planinfo->m_planTableData->insert_plan_table_tuple(); } #ifdef STREAMPLAN if (u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->needTrack() && u_sess->instr_cxt.global_instr->isTrack()) { if (es->format == EXPLAIN_FORMAT_TEXT && t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) show_track_time_info(es); } if (u_sess->instr_cxt.obs_instr) { u_sess->instr_cxt.obs_instr->insertData(queryDesc->plannedstmt->queryId); } #endif /* Print info about runtime of triggers */ if (es->analyze) { ResultRelInfo* rInfo = NULL; bool show_relname = false; int numrels = queryDesc->estate->es_num_result_relations; List* targrels = queryDesc->estate->es_trig_target_relations; int nr; ListCell* l = NULL; ExplainOpenGroup("Triggers", "Triggers", false, es); show_relname = (numrels > 1 || targrels != NIL); rInfo = queryDesc->estate->es_result_relations; for (nr = 0; nr < numrels; rInfo++, nr++) report_triggers(rInfo, show_relname, es); foreach (l, targrels) { rInfo = (ResultRelInfo*)lfirst(l); report_triggers(rInfo, show_relname, es); } ExplainCloseGroup("Triggers", "Triggers", false, es); } /* Check plan was influenced by row level security or not, here need to skip remote dummy node */ if (range_table_walker( plannedstmt->rtable, (bool (*)())ContainRlsQualInRteWalker, NULL, QTW_EXAMINE_RTES | QTW_IGNORE_DUMMY)) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL && es->planinfo->m_detailInfo != NULL) { appendStringInfo(es->planinfo->m_detailInfo->info_str, "Notice: This query is influenced by row level security feature\n"); } ExplainPropertyText("Notice", "This query is influenced by row level security feature", es); } /* traverse all remote query nodes and exec fqs query */ if (u_sess->exec_cxt.remotequery_list != NIL) { if (u_sess->attr.attr_common.max_datanode_for_plan > 0 && IS_PGXC_COORDINATOR && !IsConnFromCoord() && !es->analyze) { ExecFQSQueryinDn(es, queryString); } u_sess->exec_cxt.remotequery_list = NIL; } /* * Close down the query and free resources. Include time for this in the * total runtime (although it should be pretty minimal). */ INSTR_TIME_SET_CURRENT(starttime); ExecutorEnd(queryDesc); execend_totaltime += elapsed_time(&starttime); FreeQueryDesc(queryDesc); PopActiveSnapshot(); /* We need a CCI just in case query expanded to multiple plans */ if (es->analyze) CommandCounterIncrement(); totaltime += elapsed_time(&starttime); if (es->analyze) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) appendStringInfo(es->str, "Total runtime: %.3f ms\n", 1000.0 * totaltime); else if (es->planinfo != NULL && es->planinfo->m_query_summary) { appendStringInfo(es->planinfo->m_query_summary->info_str, "Coordinator executor start time: %.3f ms\n", 1000.0 * exec_totaltime); appendStringInfo(es->planinfo->m_query_summary->info_str, "Coordinator executor run time: %.3f ms\n", 1000.0 * execrun_totaltime); appendStringInfo(es->planinfo->m_query_summary->info_str, "Coordinator executor end time: %.3f ms\n", 1000.0 * execend_totaltime); if (es->planinfo->m_runtimeinfo && es->planinfo->m_query_summary->m_size) { long spacePeakKb = (es->planinfo->m_query_summary->m_size + 1023) / 1024; appendStringInfo(es->planinfo->m_query_summary->info_str, "Total network : %ldkB\n", spacePeakKb); } es->planinfo->m_query_summary->m_size = 0; /* show auto-analyze time */ if (u_sess->analyze_cxt.autoanalyze_timeinfo && u_sess->analyze_cxt.autoanalyze_timeinfo->len > 0) { appendStringInfo(es->planinfo->m_query_summary->info_str, "Autoanalyze runtime: %s\n", u_sess->analyze_cxt.autoanalyze_timeinfo->data); } appendStringInfo(es->planinfo->m_query_summary->info_str, "Planner runtime: %.3f ms\n", 1000.0 * plannedstmt->plannertime); appendStringInfo(es->planinfo->m_query_summary->info_str, "Plan size: %d byte\n", u_sess->instr_cxt.plan_size); appendStringInfo(es->planinfo->m_query_summary->info_str, "Query Id: %lu\n", u_sess->debug_query_id); appendStringInfo( es->planinfo->m_query_summary->info_str, "Total runtime: %.3f ms\n", 1000.0 * totaltime); } } else ExplainPropertyFloat("Total Runtime", 1000.0 * totaltime, 3, es); } output_hint_warning(plannedstmt->plan_hint_warning, WARNING); /* output warning for no-analyzed relation name if set explain verbose. */ if (es->verbose) output_noanalyze_rellist_to_log(WARNING); ExplainCloseGroup("Query", NULL, true, es); } /* * ExplainPrintPlan - * convert a QueryDesc's plan tree to text and append it to es->str * * The caller should have set up the options fields of *es, as well as * initializing the output buffer es->str. Other fields in *es are * initialized here. * * NB: will not work on utility statements */ void ExplainPrintPlan(ExplainState* es, QueryDesc* queryDesc) { AssertEreport(queryDesc->plannedstmt != NULL, MOD_EXECUTOR, "unexpect null value"); es->pstmt = queryDesc->plannedstmt; es->rtable = queryDesc->plannedstmt->rtable; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL) { es->planinfo->m_query_id = queryDesc->plannedstmt->queryId; /* print peak memory info if analyze is on */ if (es->analyze && es->planinfo->m_staticInfo) show_peak_memory(es, es->planinfo->m_planInfo->m_size); ExplainNode<true>(queryDesc->planstate, NIL, NULL, NULL, es); /* print other info, like random seed, query mem info, etc */ if (u_sess->attr.attr_sql.plan_mode_seed != OPTIMIZE_PLAN) { appendStringInfo(es->planinfo->m_query_summary->info_str, "Random seed: %u\n", get_inital_plan_seed()); } if (es->pstmt->query_mem[0] != 0) { if (es->pstmt->assigned_query_mem[0] > 0) appendStringInfo(es->planinfo->m_query_summary->info_str, "System available mem: %dKB\n", es->pstmt->assigned_query_mem[0]); if (es->pstmt->assigned_query_mem[1] > 0) appendStringInfo( es->planinfo->m_query_summary->info_str, "Query Max mem: %dKB\n", es->pstmt->assigned_query_mem[1]); appendStringInfo( es->planinfo->m_query_summary->info_str, "Query estimated mem: %dKB\n", es->pstmt->query_mem[0]); } if (es->pstmt->is_dynmaic_smp) { if (g_instance.wlm_cxt->dynamic_workload_inited) { appendStringInfo(es->planinfo->m_query_summary->info_str, "Avail/Max core: %d/%d\n", es->pstmt->dynsmp_avail_cpu, es->pstmt->dynsmp_max_cpu); appendStringInfo(es->planinfo->m_query_summary->info_str, "Cpu util: %d\n", es->pstmt->dynsmp_cpu_util); appendStringInfo(es->planinfo->m_query_summary->info_str, "Active statement: %d\n", es->pstmt->dynsmp_active_statement); } else { appendStringInfo(es->planinfo->m_query_summary->info_str, "Avail/Max core: NA/NA\n"); appendStringInfo(es->planinfo->m_query_summary->info_str, "Cpu util: NA\n"); appendStringInfo(es->planinfo->m_query_summary->info_str, "Active statement: NA\n"); } appendStringInfo(es->planinfo->m_query_summary->info_str, "Query estimated cpu: %.1lf\n", es->pstmt->dynsmp_query_estimate_cpu_usge); appendStringInfo( es->planinfo->m_query_summary->info_str, "Mem allowed dop: %d\n", es->pstmt->dynsmp_dop_mem_limit); if (es->pstmt->dynsmp_min_non_spill_dop == DYNMSP_ALREADY_SPILLED) { appendStringInfo(es->planinfo->m_query_summary->info_str, "Min non-spill dop: already spilled\n"); } else if (es->pstmt->dynsmp_min_non_spill_dop == DYNMSP_SPILL_IF_USE_HIGHER_DOP) { appendStringInfo( es->planinfo->m_query_summary->info_str, "Min non-spill dop: spill if use higher dop\n"); } else { appendStringInfo(es->planinfo->m_query_summary->info_str, "Min non-spill dop: %d\n", es->pstmt->dynsmp_min_non_spill_dop); } appendStringInfo( es->planinfo->m_query_summary->info_str, "Initial dop: %d\n", es->pstmt->dynsmp_plan_original_dop); appendStringInfo( es->planinfo->m_query_summary->info_str, "Final dop: %d\n", es->pstmt->dynsmp_plan_optimal_dop); } } else ExplainNode<false>(queryDesc->planstate, NIL, NULL, NULL, es); } /* * ExplainQueryText - * add a "Query Text" node that contains the actual text of the query * * The caller should have set up the options fields of *es, as well as * initializing the output buffer es->str. * */ void ExplainQueryText(ExplainState* es, QueryDesc* queryDesc) { if (queryDesc->sourceText) ExplainPropertyText("Query Text", queryDesc->sourceText, es); } /* * Explain a list of children of a ExtensiblePlan. */ static void ExplainExtensibleChildren(ExtensiblePlanState* planState, List* ancestors, ExplainState* es) { ListCell* cell = NULL; const char* label = (list_length(planState->extensible_ps) != 1 ? "children" : "child"); foreach (cell, planState->extensible_ps) ExplainNode<false>((PlanState*)lfirst(cell), ancestors, label, NULL, es); } /* * ExplainOneQueryForStatistic - * print out the execution plan for one Query for wlm statistics * in - queryDesc: query plan description. */ void ExplainOneQueryForStatistics(QueryDesc* queryDesc) { ExplainState es; ExplainInitState(&es); es.costs = true; es.nodes = false; es.format = EXPLAIN_FORMAT_TEXT; int before_explain_perf_mode = t_thrd.explain_cxt.explain_perf_mode; t_thrd.explain_cxt.explain_perf_mode = EXPLAIN_NORMAL; if (queryDesc->plannedstmt == NULL || queryDesc->planstate == NULL) return; es.pstmt = queryDesc->plannedstmt; es.rtable = queryDesc->plannedstmt->rtable; int max_plan_id = queryDesc->plannedstmt->num_plannodes; int wlm_statistics_plan_max_digit = get_digit(max_plan_id); es.wlm_statistics_plan_max_digit = &wlm_statistics_plan_max_digit; #ifndef ENABLE_MULTIPLE_NODES /* avoid showing prediction info for wlm statistics */ SetNullPrediction(queryDesc->planstate); #endif /* adaptation for active sql */ StreamInstrumentation* oldInstr = u_sess->instr_cxt.global_instr; u_sess->instr_cxt.global_instr = NULL; u_sess->exec_cxt.under_auto_explain = true; appendStringInfo(es.str, "Coordinator Name: %s\n", g_instance.attr.attr_common.PGXCNodeName); ExplainNode<false>(queryDesc->planstate, NIL, NULL, NULL, &es); u_sess->exec_cxt.under_auto_explain = false; u_sess->instr_cxt.global_instr = oldInstr; AutoContextSwitch memSwitch(g_instance.wlm_cxt->query_resource_track_mcxt); t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->query_plan = (char*)palloc0(es.str->len + 1 + 1); errno_t rc = memcpy_s(t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->query_plan, es.str->len, es.str->data, es.str->len); securec_check(rc, "\0", "\0"); t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->query_plan[es.str->len] = '\n'; t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->query_plan[es.str->len + 1] = '\0'; t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->plan_size = es.str->len + 1 + 1; t_thrd.explain_cxt.explain_perf_mode = before_explain_perf_mode; } /* * report_triggers - * report execution stats for a single relation's triggers */ static void report_triggers(ResultRelInfo* rInfo, bool show_relname, ExplainState* es) { int nt; if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument) return; for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++) { Trigger* trig = rInfo->ri_TrigDesc->triggers + nt; Instrumentation* instr = rInfo->ri_TrigInstrument + nt; char* relname = NULL; char* conname = NULL; /* Must clean up instrumentation state */ InstrEndLoop(instr); /* * We ignore triggers that were never invoked; they likely aren't * relevant to the current query type. */ if (instr->ntuples == 0) continue; ExplainOpenGroup("Trigger", NULL, true, es); relname = RelationGetRelationName(rInfo->ri_RelationDesc); if (OidIsValid(trig->tgconstraint)) conname = get_constraint_name(trig->tgconstraint); /* * In text format, we avoid printing both the trigger name and the * constraint name unless VERBOSE is specified. In non-text formats * we just print everything. */ if (es->format == EXPLAIN_FORMAT_TEXT) { if (es->verbose || conname == NULL) appendStringInfo(es->str, "Trigger %s", trig->tgname); else appendStringInfoString(es->str, "Trigger"); if (conname != NULL) appendStringInfo(es->str, " for constraint %s", conname); if (show_relname) appendStringInfo(es->str, " on %s", relname); appendStringInfo(es->str, ": time=%.3f calls=%.0f\n", 1000.0 * instr->total, instr->ntuples); } else { ExplainPropertyText("Trigger Name", trig->tgname, es); if (conname != NULL) ExplainPropertyText("Constraint Name", conname, es); ExplainPropertyText("Relation", relname, es); ExplainPropertyFloat("Time", 1000.0 * instr->total, 3, es); ExplainPropertyFloat("Calls", instr->ntuples, 0, es); } if (conname != NULL) pfree_ext(conname); ExplainCloseGroup("Trigger", NULL, true, es); } } /* Compute elapsed time in seconds since given timestamp */ double elapsed_time(instr_time* starttime) { instr_time endtime; INSTR_TIME_SET_CURRENT(endtime); INSTR_TIME_SUBTRACT(endtime, *starttime); return INSTR_TIME_GET_DOUBLE(endtime); } static void show_bucket_info(PlanState* planstate, ExplainState* es, bool is_pretty) { Scan* scanplan = (Scan*)planstate->plan; BucketInfo* bucket_info = scanplan->bucketInfo; int selected_buckets = list_length(bucket_info->buckets); #ifdef ENABLE_MULTIPLE_NODES CheckBucketMapLenValid(); #endif if (selected_buckets == 0) { /* 0 means all buckets */ selected_buckets = BUCKETDATALEN; } if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty) { es->planinfo->m_detailInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_detailInfo->info_str, "Selected Buckets %d of %d : %s\n", selected_buckets, BUCKETDATALEN, bucketInfoToString(bucket_info)); } else { if (es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); } else { appendStringInfoSpaces(es->str, es->indent * 2); } appendStringInfo(es->str, "Selected Buckets %d of %d : %s\n", selected_buckets, BUCKETDATALEN, bucketInfoToString(bucket_info)); } } } static void show_pruning_info(PlanState* planstate, ExplainState* es, bool is_pretty) { Scan* scanplan = (Scan*)planstate->plan; bool print_number = false; bool print_twodots = false; bool print_comma = false; bool print_prev = false; int partID = 0; int partID_prev = 0; if (es->format == EXPLAIN_FORMAT_TEXT) { int i = 0; if (is_pretty == false) { if (es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); } else { appendStringInfoSpaces(es->str, es->indent * 2); } appendStringInfo(es->str, "Selected Partitions: "); } else { es->planinfo->m_detailInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_detailInfo->info_str, "Selected Partitions: "); } if (scanplan->itrs <= 0) { if (is_pretty == false) appendStringInfo(es->str, "NONE"); else appendStringInfo(es->planinfo->m_detailInfo->info_str, "NONE"); } else if (scanplan->pruningInfo->expr != NULL) { appendStringInfo(es->str, "%s", "PART"); } else { ListCell* cell = NULL; List* part_seqs = scanplan->pruningInfo->ls_rangeSelectedPartitions; AssertEreport(scanplan->itrs == scanplan->pruningInfo->ls_rangeSelectedPartitions->length, MOD_EXECUTOR, "unexpect list length"); foreach (cell, part_seqs) { // store the prev first partID if (i > 0) { partID_prev = partID; } partID = lfirst_int(cell); if (partID < 0) break; // set print flags for the current and the previouse partition number if (i == 0) { print_prev = false; print_number = true; print_twodots = false; print_comma = false; } else if (partID - partID_prev == 1) { // the last partition if (i == scanplan->itrs - 1) { print_prev = false; print_number = true; print_twodots = true; print_comma = false; } else { print_prev = false; print_number = false; print_twodots = false; print_comma = false; } } else { // the previous has not been printed if (!print_number) print_prev = true; else print_prev = false; print_number = true; print_twodots = false; print_comma = true; } if (is_pretty) { // first check whether print the previous partition number if (print_prev) { appendStringInfoString(es->planinfo->m_detailInfo->info_str, ".."); appendStringInfo(es->planinfo->m_detailInfo->info_str, "%d", partID_prev + 1); } // then print the current partition number if (print_twodots) appendStringInfoString(es->planinfo->m_detailInfo->info_str, ".."); else if (print_comma) appendStringInfoString(es->planinfo->m_detailInfo->info_str, ","); if (print_number) appendStringInfo(es->planinfo->m_detailInfo->info_str, "%d", partID + 1); } else { // first check whether print the previous partition number if (print_prev) { appendStringInfoString(es->str, ".."); appendStringInfo(es->str, "%d", partID_prev + 1); } // then print the current partition number if (print_twodots) appendStringInfoString(es->str, ".."); else if (print_comma) appendStringInfoString(es->str, ","); if (print_number) appendStringInfo(es->str, "%d", partID + 1); } i++; } } if (is_pretty) appendStringInfoChar(es->planinfo->m_detailInfo->info_str, '\n'); else appendStringInfoChar(es->str, '\n'); } else { if (scanplan->itrs <= 0) { ExplainPropertyText("Selected Partitions", "NONE", es); } else if (scanplan->pruningInfo->expr != NULL) { ExplainPropertyText("Selected Partitions", "PART", es); } else { int i = 0; StringInfo strif; ListCell* cell = NULL; List* part_seqs = scanplan->pruningInfo->ls_rangeSelectedPartitions; AssertEreport(scanplan->itrs == scanplan->pruningInfo->ls_rangeSelectedPartitions->length, MOD_EXECUTOR, "unexpect list length"); /*form a tring of partition numbers, by 2 charaters space splitted*/ strif = makeStringInfo(); foreach (cell, part_seqs) { // store the prev first partID if (i > 0) { partID_prev = partID; } partID = lfirst_int(cell); if (partID < 0) break; // set print flags for the current and the previouse partition number if (i == 0) { print_prev = false; print_number = true; print_twodots = false; print_comma = false; } else if (partID - partID_prev == 1) { // the last partition if (i == scanplan->itrs - 1) { print_prev = false; print_number = true; print_twodots = true; print_comma = false; } else { print_prev = false; print_number = false; print_twodots = false; print_comma = false; } } else { // the previous has not been printed if (!print_number) { print_prev = true; } else { print_prev = false; } print_number = true; print_twodots = false; print_comma = true; } // first check whether print the previous partition number if (print_prev) { appendStringInfoString(strif, ".."); appendStringInfo(strif, "%d", partID_prev + 1); } // then print the current partition number if (print_twodots) appendStringInfoString(strif, ".."); else if (print_comma) appendStringInfoString(strif, ","); if (print_number) appendStringInfo(strif, "%d", partID + 1); i++; } /*print out the partition numbers string*/ ExplainPropertyText("Selected Partitions", strif->data, es); pfree_ext(strif->data); pfree_ext(strif); } } } static void ExplainNodePartition(const Plan* plan, ExplainState* es) { int flag = 0; switch (nodeTag(plan->lefttree)) { case T_SeqScan: if (((SeqScan*)plan->lefttree)->pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; case T_IndexScan: if (((IndexScan*)plan->lefttree)->scan.pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; case T_IndexOnlyScan: if (((IndexOnlyScan*)plan->lefttree)->scan.pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; case T_BitmapIndexScan: if (((BitmapIndexScan*)plan->lefttree)->scan.pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; case T_BitmapHeapScan: if (((BitmapHeapScan*)plan->lefttree)->scan.pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; case T_CStoreScan: if (((CStoreScan*)plan->lefttree)->pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: if (((TsStoreScan*)plan->lefttree)->pruningInfo->expr != NULL) { appendStringInfo(es->str, "Iterations: %s", "PART"); flag = 1; } break; #endif default: appendStringInfo(es->str, "Iterations: %d", ((PartIterator*)plan)->itrs); flag = 1; break; } if (flag == 0) { appendStringInfo(es->str, "Iterations: %d", ((PartIterator*)plan)->itrs); } appendStringInfoChar(es->str, '\n'); } #ifndef ENABLE_MULTIPLE_NODES static void PredAppendInfo(Plan* plan, StringInfoData buf, ExplainState* es) { if (plan->pred_total_time >= 0) { initStringInfo(&buf); appendStringInfo(&buf, "%.0f", plan->pred_total_time); es->planinfo->m_planInfo->put(PREDICT_TIME, PointerGetDatum(cstring_to_text(buf.data))); pfree_ext(buf.data); } if (plan->pred_rows >= 0) { es->planinfo->m_planInfo->put(PREDICT_ROWS, DirectFunctionCall1(dround, Float8GetDatum(plan->pred_rows))); } if (plan->pred_max_memory >= 0) { es->planinfo->m_planInfo->put(PREDICT_MEMORY, DirectFunctionCall1(pg_size_pretty, Int64GetDatum(plan->pred_max_memory))); } } static void PredGetInfo(Plan* plan, ExplainState* es) { if (plan->pred_startup_time >= 0) { ExplainPropertyFloat("Pred Startup Time", plan->pred_startup_time, 2, es); } if (plan->pred_total_time >= 0) { ExplainPropertyFloat("Pred Total Time", plan->pred_total_time, 2, es); } if (plan->pred_rows >= 0) { ExplainPropertyFloat("Pred Rows", plan->pred_rows, 0, es); } if (plan->pred_max_memory >= 0) { ExplainPropertyLong("Pred Peak Memory", plan->pred_max_memory, es); } } #endif /* * ExplainNode - * Appends a description of a plan tree to es->str * * planstate points to the executor state node for the current plan node. * We need to work from a PlanState node, not just a Plan node, in order to * get at the instrumentation data (if any) as well as the list of subplans. * * ancestors is a list of parent PlanState nodes, most-closely-nested first. * These are needed in order to interpret PARAM_EXEC Params. * * relationship describes the relationship of this plan node to its parent * (eg, "Outer", "Inner"); it can be null at top level. plan_name is an * optional name to be attached to the node. * * In text format, es->indent is controlled in this function since we only * want it to change at plan-node boundaries. In non-text formats, es->indent * corresponds to the nesting depth of logical output groups, and therefore * is controlled by ExplainOpenGroup/ExplainCloseGroup. */ template <bool is_pretty> static void ExplainNode( PlanState* planstate, List* ancestors, const char* relationship, const char* plan_name, ExplainState* es) { Plan* plan = planstate->plan; char* pname = NULL; /* node type name for text output */ char* sname = NULL; /* node type name for non-text output */ char* strategy = NULL; char* operation = NULL; int save_indent = es->indent; int save_pindent = es->pindent; bool haschildren = false; int plan_node_id = planstate->plan->plan_node_id; int parentid = planstate->plan->parent_node_id; StringInfo tmpName; bool from_datanode = false; bool old_dn_flag = false; /* For plan_table column */ char* pt_operation = NULL; char* pt_options = NULL; const char* pt_index_name = NULL; const char* pt_index_owner = NULL; if (is_pretty) { if (plan->plan_node_id == 0) goto runnext; tmpName = &es->planinfo->m_planInfo->m_pname; resetStringInfo(tmpName); } if (is_pretty) { es->planinfo->set_id(plan_node_id); es->planinfo->m_planInfo->put(PLANID, plan_node_id); if (es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->m_plan_node_id = plan_node_id; es->planinfo->m_runtimeinfo->put(-1, -1, PLAN_PARENT_ID, parentid); es->planinfo->m_runtimeinfo->put(-1, -1, QUERY_ID, es->planinfo->m_query_id); es->planinfo->m_runtimeinfo->put(-1, -1, PLAN_NODE_ID, plan_node_id); es->planinfo->m_runtimeinfo->put(-1, -1, PLAN_TYPE, nodeTag(plan)); from_datanode = es->from_dn; es->planinfo->m_runtimeinfo->put(-1, -1, FROM_DATANODE, from_datanode); } if (es->analyze && (IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery))) { show_dn_executor_time(es, plan_node_id, DN_START_TIME); /* print executor start time */ show_dn_executor_time(es, plan_node_id, DN_RUN_TIME); /* print executor run time */ show_dn_executor_time(es, plan_node_id, DN_END_TIME); /* print executor end time */ } } /* Fetch plan node's plain text info */ GetPlanNodePlainText(plan, &pname, &sname, &strategy, &operation, &pt_operation, &pt_options); ExplainOpenGroup("Plan", relationship ? NULL : "Plan", true, es); if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty) { appendStringInfoString(tmpName, pname); } else { if (es->wlm_statistics_plan_max_digit) { show_wlm_explain_name(es, plan_name, pname, plan_node_id); } else { if (plan_name != NULL) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "%s\n", plan_name); es->indent++; } if (es->indent) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoString(es->str, "-> "); es->indent += 2; } appendStringInfoString(es->str, pname); es->indent++; } } } else { ExplainPropertyText("Node Type", sname, es); if (strategy != NULL) ExplainPropertyText("Strategy", strategy, es); if (operation != NULL) ExplainPropertyText("Operation", operation, es); if (relationship != NULL) ExplainPropertyText("Parent Relationship", relationship, es); if (plan_name != NULL) ExplainPropertyText("Subplan Name", plan_name, es); } switch (nodeTag(plan)) { case T_SeqScan: case T_CStoreScan: case T_DfsScan: #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: #endif /* ENABLE_MULTIPLE_NODES */ case T_BitmapHeapScan: case T_CStoreIndexHeapScan: case T_TidScan: case T_SubqueryScan: case T_VecSubqueryScan: case T_FunctionScan: case T_ValuesScan: case T_CteScan: case T_WorkTableScan: case T_ForeignScan: case T_VecForeignScan: ExplainScanTarget((Scan*)plan, es); break; case T_ExtensiblePlan: if (((Scan*)plan)->scanrelid > 0) ExplainScanTarget((Scan*)plan, es); break; #ifdef PGXC case T_RemoteQuery: case T_VecRemoteQuery: /* Emit node execution list */ ExplainExecNodes(((RemoteQuery*)plan)->exec_nodes, es); #ifdef STREAMPLAN if (!IS_STREAM) #endif ExplainScanTarget((Scan*)plan, es); break; #endif case T_IndexScan: { IndexScan* indexscan = (IndexScan*)plan; ExplainIndexScanDetails(indexscan->indexid, indexscan->indexorderdir, es); ExplainScanTarget((Scan*)indexscan, es); pt_index_name = explain_get_index_name(indexscan->indexid); pt_index_owner = get_namespace_name(get_rel_namespace(indexscan->indexid)); } break; case T_IndexOnlyScan: { IndexOnlyScan* indexonlyscan = (IndexOnlyScan*)plan; ExplainIndexScanDetails(indexonlyscan->indexid, indexonlyscan->indexorderdir, es); ExplainScanTarget((Scan*)indexonlyscan, es); pt_index_name = explain_get_index_name(indexonlyscan->indexid); pt_index_owner = get_namespace_name(get_rel_namespace(indexonlyscan->indexid)); } break; case T_BitmapIndexScan: { BitmapIndexScan* bitmapindexscan = (BitmapIndexScan*)plan; const char* indexname = explain_get_index_name(bitmapindexscan->indexid); if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfo(es->str, " on %s", indexname); else ExplainPropertyText("Index Name", indexname, es); pt_index_name = indexname; pt_index_owner = get_namespace_name(get_rel_namespace(bitmapindexscan->indexid)); } break; case T_DfsIndexScan: { DfsIndexScan* indexscan = (DfsIndexScan*)plan; ExplainIndexScanDetails(indexscan->indexid, indexscan->indexorderdir, es); ExplainScanTarget((Scan*)indexscan, es); pt_index_name = explain_get_index_name(indexscan->indexid); pt_index_owner = get_namespace_name(get_rel_namespace(indexscan->indexid)); } break; case T_CStoreIndexScan: { CStoreIndexScan* indexscan = (CStoreIndexScan*)plan; ExplainIndexScanDetails(indexscan->indexid, indexscan->indexorderdir, es); ExplainScanTarget((Scan*)indexscan, es); pt_index_name = explain_get_index_name(indexscan->indexid); pt_index_owner = get_namespace_name(get_rel_namespace(indexscan->indexid)); } break; case T_CStoreIndexCtidScan: { CStoreIndexCtidScan* bitmapindexscan = (CStoreIndexCtidScan*)plan; const char* indexname = explain_get_index_name(bitmapindexscan->indexid); if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfo(es->str, " on %s", indexname); else ExplainPropertyText("Index Name", indexname, es); pt_index_name = indexname; pt_index_owner = get_namespace_name(get_rel_namespace(bitmapindexscan->indexid)); } break; case T_ModifyTable: case T_VecModifyTable: ExplainModifyTarget((ModifyTable*)plan, es); break; case T_NestLoop: case T_VecNestLoop: case T_VecMergeJoin: case T_MergeJoin: case T_HashJoin: case T_VecHashJoin: { const char* jointype = NULL; switch (((Join*)plan)->jointype) { case JOIN_INNER: jointype = pt_options = "Inner"; break; case JOIN_LEFT: jointype = pt_options = "Left"; break; case JOIN_FULL: jointype = pt_options = "Full"; break; case JOIN_RIGHT: jointype = pt_options = "Right"; break; case JOIN_SEMI: jointype = pt_options = "Semi"; break; case JOIN_ANTI: jointype = pt_options = "Anti"; break; case JOIN_RIGHT_SEMI: jointype = pt_options = "Right Semi"; break; case JOIN_RIGHT_ANTI: jointype = pt_options = "Right Anti"; break; case JOIN_LEFT_ANTI_FULL: jointype = pt_options = "Left Anti Full"; break; case JOIN_RIGHT_ANTI_FULL: jointype = pt_options = "Right Anti Full"; break; default: jointype = pt_options = "?\?\?"; break; } /* In order to adapt join option 'CARTESIAN' in A db, we reset 'options' here. */ if (es->plan && es->planinfo != NULL) es->planinfo->m_planTableData->set_plan_table_join_options(plan, &pt_options); if (es->format == EXPLAIN_FORMAT_TEXT) { /* * For historical reasons, the join type is interpolated * into the node type name... */ if (is_pretty == false) { if (((Join*)plan)->jointype != JOIN_INNER) { appendStringInfo(es->str, " %s Join", jointype); } else if (!(IsA(plan, NestLoop) || IsA(plan, VecNestLoop))) { appendStringInfo(es->str, " Join"); } } else { if (((Join*)plan)->jointype != JOIN_INNER) { appendStringInfo(tmpName, " %s Join (%d, %d)", jointype, planstate->lefttree->plan->plan_node_id, planstate->righttree->plan->plan_node_id); } else if (!(IsA(plan, NestLoop) || IsA(plan, VecNestLoop))) { appendStringInfo(tmpName, " Join (%d,%d)", planstate->lefttree->plan->plan_node_id, planstate->righttree->plan->plan_node_id); } else { appendStringInfo(tmpName, " (%d,%d)", planstate->lefttree->plan->plan_node_id, planstate->righttree->plan->plan_node_id); } } } else ExplainPropertyText("Join Type", jointype, es); } break; case T_SetOp: case T_VecSetOp: { const char* setopcmd = NULL; switch (((SetOp*)plan)->cmd) { case SETOPCMD_INTERSECT: setopcmd = "Intersect"; break; case SETOPCMD_INTERSECT_ALL: setopcmd = "Intersect All"; break; case SETOPCMD_EXCEPT: setopcmd = "Except"; break; case SETOPCMD_EXCEPT_ALL: setopcmd = "Except All"; break; default: setopcmd = "?\?\?"; break; } if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty == false) appendStringInfo(es->str, " %s", setopcmd); else appendStringInfo(tmpName, " %s", setopcmd); } else ExplainPropertyText("Command", setopcmd, es); } break; case T_PartIterator: { const char* scandir = NULL; if (ScanDirectionIsBackward(((PartIterator*)plan)->direction)) scandir = "Scan Backward"; if (scandir != NULL) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty == false) { appendStringInfo(es->str, " %s", scandir); } else { appendStringInfo(tmpName, " %s", scandir); } } else { ExplainPropertyText("Scan Direction", scandir, es); } } } break; case T_Append: case T_VecAppend: { if (is_pretty) { /* print append plan's subplan node id, like Vector Append(6, 7) */ int nplans = list_length(((Append*)plan)->appendplans); PlanState** append_planstate = ((AppendState*)planstate)->appendplans; bool first = true; appendStringInfo(tmpName, "("); for (int j = 0; j < nplans; j++) { if (first == false) appendStringInfoString(tmpName, ", "); appendStringInfo(tmpName, "%d", append_planstate[j]->plan->plan_node_id); first = false; } appendStringInfo(tmpName, ")"); } } break; case T_RecursiveUnion: { if (es->format == EXPLAIN_FORMAT_TEXT && is_pretty) appendStringInfo(tmpName, " (%d,%d)", planstate->lefttree->plan->plan_node_id, planstate->righttree->plan->plan_node_id); } break; default: break; } /* For recursive query consideration */ if (GET_CONTROL_PLAN_NODEID(plan) != 0 && u_sess->attr.attr_sql.enable_stream_recursive) { appendStringInfo( es->str, " <<ruid:[%d] ctlid:[%d]", GET_RECURSIVE_UNION_PLAN_NODEID(plan), GET_CONTROL_PLAN_NODEID(plan)); if (is_pretty) appendStringInfo(tmpName, " <<ruid:[%d] ctlid:[%d]", GET_RECURSIVE_UNION_PLAN_NODEID(plan), GET_CONTROL_PLAN_NODEID(plan)); if (plan->is_sync_plannode) { appendStringInfo(es->str, " (SYNC)"); if (is_pretty) appendStringInfo(tmpName, " (SYNC)"); } appendStringInfo(es->str, ">>"); if (is_pretty) appendStringInfo(tmpName, ">>"); } if (u_sess->attr.attr_sql.enable_stream_recursive && IsA(plan, Stream) && ((Stream*)plan)->stream_level > 0 && plan->recursive_union_plan_nodeid != 0) { Stream* stream_plan = (Stream*)plan; appendStringInfo(es->str, " stream_level:%d ", stream_plan->stream_level); if (is_pretty) appendStringInfo(tmpName, " stream_level:%d ", stream_plan->stream_level); } if (is_pretty) { StringInfoData pretty_plan_name; initStringInfo(&pretty_plan_name); appendStringInfoSpaces(&pretty_plan_name, es->pindent); appendStringInfoString(&pretty_plan_name, "-> "); es->pindent += 2; appendStringInfoString(&pretty_plan_name, es->planinfo->m_planInfo->m_pname.data); if (plan_name != NULL) { appendStringInfoSpaces(&pretty_plan_name, 2); appendStringInfo(&pretty_plan_name, "[%d, %s]", plan->parent_node_id, plan_name); } es->planinfo->m_planInfo->put(PLAN, PointerGetDatum(cstring_to_text(pretty_plan_name.data))); pfree_ext(pretty_plan_name.data); es->pindent++; es->planinfo->append_str_info("%3d --%s\n", plan_node_id, es->planinfo->m_planInfo->m_pname.data); es->planinfo->set_pname(es->planinfo->m_planInfo->m_pname.data); if (es->planinfo->m_runtimeinfo) es->planinfo->m_runtimeinfo->put( -1, -1, PLAN_NAME, PointerGetDatum(cstring_to_text(es->planinfo->m_planInfo->m_pname.data))); } if (es->costs) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty == false) { appendStringInfo( es->str, " (cost=%.2f..%.2f rows=%.0f ", plan->startup_cost, plan->total_cost, plan->plan_rows); #ifndef ENABLE_MULTIPLE_NODES if (plan->pred_total_time >= 0) { appendStringInfo(es->str, "p-time=%.0f ", plan->pred_total_time); } if (plan->pred_rows >= 0) { appendStringInfo(es->str, "p-rows=%.0f ", plan->pred_rows); } #endif /* ENABLE_MULTIPLE_NODES */ if ((IsA(plan, HashJoin) || IsA(plan, VecHashJoin)) && es->verbose) appendStringInfo(es->str, "distinct=[%.0f, %.0f] ", plan->outerdistinct > 0 ? ceil(plan->outerdistinct) : 1.0, plan->innerdistinct > 0 ? ceil(plan->innerdistinct) : 1.0); appendStringInfo(es->str, "width=%d)", plan->plan_width); } else { StringInfoData buf; initStringInfo(&buf); appendStringInfo(&buf, "%.2f", plan->total_cost); es->planinfo->m_planInfo->put(ESTIMATE_COSTS, PointerGetDatum(cstring_to_text(buf.data))); pfree_ext(buf.data); #ifndef ENABLE_MULTIPLE_NODES PredAppendInfo(plan, buf, es); #endif /* Here we need call round function, avoid E_rows appear decimal fraction.*/ es->planinfo->m_planInfo->put( ESTIMATE_ROWS, DirectFunctionCall1(dround, Float8GetDatum(plan->plan_rows))); if ((IsA(plan, HashJoin) || IsA(plan, VecHashJoin)) && es->verbose) { char opdist[130] = "\0"; int rc = EOK; rc = sprintf_s(opdist, sizeof(opdist), "%.0f, %.0f", plan->outerdistinct > 1 ? ceil(plan->outerdistinct) : 1.0, plan->innerdistinct > 1 ? ceil(plan->innerdistinct) : 1.0); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ESTIMATE_DISTINCT, PointerGetDatum(cstring_to_text(opdist))); } es->planinfo->m_planInfo->put(ESTIMATE_WIDTH, plan->plan_width); if (es->planinfo->m_planInfo->m_query_mem_mode) { char memstr[50] = "\0"; if (plan->operatorMemKB[0] > 0) { int rc = 0; if (plan->operatorMemKB[0] < 1024) rc = sprintf_s(memstr, sizeof(memstr), "%dKB", (int)plan->operatorMemKB[0]); else { if (plan->operatorMemKB[0] > MIN_OP_MEM && plan->operatorMaxMem > plan->operatorMemKB[0]) rc = sprintf_s(memstr, sizeof(memstr), "%dMB(%dMB)", (int)plan->operatorMemKB[0] / 1024, (int)plan->operatorMaxMem / 1024); else rc = sprintf_s(memstr, sizeof(memstr), "%dMB", (int)plan->operatorMemKB[0] / 1024); } securec_check_ss(rc, "\0", "\0"); } es->planinfo->m_planInfo->put(ESTIMATE_MEMORY, PointerGetDatum(cstring_to_text(memstr))); } } } else { ExplainPropertyFloat("Startup Cost", plan->startup_cost, 2, es); ExplainPropertyFloat("Total Cost", plan->total_cost, 2, es); ExplainPropertyFloat("Plan Rows", plan->plan_rows, 0, es); ExplainPropertyInteger("Plan Width", plan->plan_width, es); #ifndef ENABLE_MULTIPLE_NODES PredGetInfo(plan, es); #endif } } /* * We have to forcibly clean up the instrumentation state because we * haven't done ExecutorEnd yet. This is pretty grotty ... */ if (planstate->instrument) InstrEndLoop(planstate->instrument); if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { show_datanode_time(es, planstate); show_stream_send_time(es, planstate); } else { if (is_pretty) { if (!es->from_dn) { show_pretty_time(es, planstate->instrument, NULL, -1, -1, 0); if (es->planinfo->m_runtimeinfo != NULL) { if (unlikely(planstate->instrument == NULL)) { ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("invalid planstate->instrument value."))); } get_oper_time<false>(es, planstate, planstate->instrument, -1, -1); } } } else { show_time<false>(es, planstate->instrument, -1); } } /* target list */ if (es->verbose || es->plan) show_plan_tlist(planstate, ancestors, es); /* Show exec nodes of plan nodes when it's not a single installation group scenario */ if (es->nodes && es->verbose && ng_enable_nodegroup_explain()) { show_plan_execnodes(planstate, es); } /* quals, sort keys, etc */ switch (nodeTag(plan)) { case T_IndexScan: show_scan_qual(((IndexScan*)plan)->indexqualorig, "Index Cond", planstate, ancestors, es); if (((IndexScan*)plan)->indexqualorig) show_instrumentation_count("Rows Removed by Index Recheck", 2, planstate, es); show_scan_qual(((IndexScan*)plan)->indexorderbyorig, "Order By", planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); break; case T_IndexOnlyScan: show_scan_qual(((IndexOnlyScan*)plan)->indexqual, "Index Cond", planstate, ancestors, es); if (((IndexOnlyScan*)plan)->indexqual) show_instrumentation_count("Rows Removed by Index Recheck", 2, planstate, es); show_scan_qual(((IndexOnlyScan*)plan)->indexorderby, "Order By", planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); if (es->analyze) ExplainPropertyLong("Heap Fetches", ((IndexOnlyScanState*)planstate)->ioss_HeapFetches, es); break; case T_BitmapIndexScan: show_scan_qual(((BitmapIndexScan*)plan)->indexqualorig, "Index Cond", planstate, ancestors, es); break; case T_CStoreIndexCtidScan: show_scan_qual(((CStoreIndexCtidScan*)plan)->indexqualorig, "Index Cond", planstate, ancestors, es); break; case T_CStoreIndexScan: show_scan_qual(((CStoreIndexScan*)plan)->indexqualorig, "Index Cond", planstate, ancestors, es); if (((CStoreIndexScan*)plan)->indexqualorig) show_instrumentation_count("Rows Removed by Index Recheck", 2, planstate, es); show_scan_qual(((CStoreIndexScan*)plan)->indexorderbyorig, "Order By", planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); show_llvm_info(planstate, es); break; case T_DfsIndexScan: show_scan_qual(((DfsIndexScan*)plan)->indexqualorig, "Index Cond", planstate, ancestors, es); if (((DfsIndexScan*)plan)->indexqualorig) show_instrumentation_count("Rows Removed by Index Recheck", 2, planstate, es); show_scan_qual(((DfsIndexScan*)plan)->indexorderbyorig, "Order By", planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); show_pushdown_qual(planstate, ancestors, es, PUSHDOWN_PREDICATE_FLAG); show_llvm_info(planstate, es); break; #ifdef PGXC case T_ModifyTable: case T_VecModifyTable: { /* Remote query planning on DMLs */ ModifyTable* mt = (ModifyTable*)plan; ListCell* elt = NULL; ListCell* lc = NULL; if (mt->operation == CMD_MERGE) { if (es->analyze) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL && es->planinfo->m_detailInfo != NULL) { es->planinfo->m_detailInfo->set_plan_name<true, false>(); } show_instrumentation_count("Merge Inserted", 1, planstate, es); show_instrumentation_count("Merge Updated", 2, planstate, es); show_instrumentation_count("Merge Deleted", 3, planstate, es); } show_modifytable_merge_info(planstate, es); foreach (lc, mt->mergeActionList) { MergeAction* action = (MergeAction*)lfirst(lc); if (action->matched) { if (mt->remote_update_plans) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "WHEN MATCHED\n"); es->indent++; foreach (elt, mt->remote_update_plans) { if (lfirst(elt)) { ExplainRemoteQuery((RemoteQuery*)lfirst(elt), planstate, ancestors, es); } } es->indent--; } else show_scan_qual((List*)action->qual, "Update Cond", planstate, ancestors, es); } else if (!action->matched) { if (mt->remote_insert_plans) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "WHEN NOT MATCHED\n"); es->indent++; foreach (elt, mt->remote_insert_plans) { if (lfirst(elt)) { ExplainRemoteQuery((RemoteQuery*)lfirst(elt), planstate, ancestors, es); } } es->indent--; } else show_scan_qual((List*)action->qual, "Insert Cond", planstate, ancestors, es); } } } else { /* upsert cases */ ModifyTableState* mtstate = (ModifyTableState*)planstate; if (mtstate->mt_upsert != NULL && mtstate->mt_upsert->us_action != UPSERT_NONE && mtstate->resultRelInfo->ri_NumIndices > 0) { show_on_duplicate_info(mtstate, es); } /* non-merge cases */ foreach (elt, mt->remote_plans) { if (lfirst(elt)) { ExplainRemoteQuery((RemoteQuery*)lfirst(elt), planstate, ancestors, es); } } } } break; case T_RemoteQuery: case T_VecRemoteQuery: /* Remote query */ show_merge_sort_keys(planstate, ancestors, es); ExplainRemoteQuery((RemoteQuery*)plan, planstate, ancestors, es); show_scan_qual(plan->qual, "Coordinator quals", planstate, ancestors, es); break; #else case T_ModifyTable: show_modifytable_info((ModifyTableState*)planstate, es); break; #endif case T_BitmapHeapScan: case T_CStoreIndexHeapScan: show_scan_qual(((BitmapHeapScan*)plan)->bitmapqualorig, "Recheck Cond", planstate, ancestors, es); if (((BitmapHeapScan*)plan)->bitmapqualorig) show_instrumentation_count("Rows Removed by Index Recheck", 2, planstate, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); show_llvm_info(planstate, es); break; case T_SeqScan: case T_CStoreScan: #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: #endif /* ENABLE_MULTIPLE_NODES */ case T_ValuesScan: case T_CteScan: case T_WorkTableScan: case T_SubqueryScan: case T_VecSubqueryScan: show_tablesample(plan, planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); show_llvm_info(planstate, es); break; case T_DfsScan: { show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); show_pushdown_qual(planstate, ancestors, es, PUSHDOWN_PREDICATE_FLAG); show_bloomfilter<false>(plan, planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); show_storage_filter_info(planstate, es); show_dfs_block_info(planstate, es); show_llvm_info(planstate, es); break; } /* FALL THRU */ case T_Stream: case T_VecStream: { show_merge_sort_keys(planstate, ancestors, es); ShowStreamRunNodeInfo((Stream*)plan, es); if (is_pretty && es->planinfo->m_query_summary) { showStreamnetwork((Stream*)plan, es); } } break; case T_FunctionScan: if (es->verbose) show_expression( ((FunctionScan*)plan)->funcexpr, "Function Call", planstate, ancestors, es->verbose, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); break; case T_TidScan: { /* * The tidquals list has OR semantics, so be sure to show it * as an OR condition. */ List* tidquals = ((TidScan*)plan)->tidquals; if (list_length(tidquals) > 1) tidquals = list_make1(make_orclause(tidquals)); show_scan_qual(tidquals, "TID Cond", planstate, ancestors, es); show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); } break; case T_ForeignScan: case T_VecForeignScan: { ForeignScan* fScan = (ForeignScan*)plan; /* * show_predicate_flag represents the label of non-pushdown * predicate restriction clause on foreign scan level. */ char* show_predicate_flag = NULL; /* * show_pushdown_flag represents the label of pushdown predicate * restriction clause on ORC reader level. */ char* show_pushdown_flag = NULL; if (fScan->scan.scan_qual_optimized) { show_predicate_flag = FILTER_INFORMATIONAL_CONSTRAINT_FLAG; } else { show_predicate_flag = FILTER_FLAG; } if (fScan->scan.predicate_pushdown_optimized) { show_pushdown_flag = PUSHDOWN_FILTER_INFORMATIONAL_CONSTRAINT_FLAG; } else { show_pushdown_flag = PUSHDOWN_PREDICATE_FLAG; } show_scan_qual(plan->qual, show_predicate_flag, planstate, ancestors, es); show_pushdown_qual(planstate, ancestors, es, show_pushdown_flag); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); if (es->wlm_statistics_plan_max_digit == NULL) { show_foreignscan_info((ForeignScanState*)planstate, es); } show_storage_filter_info(planstate, es); show_dfs_block_info(planstate, es); show_llvm_info(planstate, es); if (IsA(plan, VecForeignScan)) { show_bloomfilter<false>(plan, planstate, ancestors, es); } } break; case T_VecNestLoop: case T_NestLoop: { NestLoop* nestLoop = (NestLoop*)plan; if (nestLoop->join.optimizable) { show_upper_qual(((NestLoop*)plan)->join.joinqual, "Join Filter(Informational Constraint Optimization)", planstate, ancestors, es); } else { show_upper_qual(((NestLoop*)plan)->join.joinqual, "Join Filter", planstate, ancestors, es); } if (((NestLoop*)plan)->join.joinqual) show_instrumentation_count("Rows Removed by Join Filter", 1, planstate, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 2, planstate, es); show_llvm_info(planstate, es); show_skew_optimization(planstate, es); } break; case T_VecMergeJoin: case T_MergeJoin: { MergeJoin* mergeJoin = (MergeJoin*)plan; if (mergeJoin->join.optimizable) { show_upper_qual(((MergeJoin*)plan)->mergeclauses, "Merge Cond(Informational Constraint Optimization)", planstate, ancestors, es); } else { show_upper_qual(((MergeJoin*)plan)->mergeclauses, "Merge Cond", planstate, ancestors, es); } show_upper_qual(((MergeJoin*)plan)->join.joinqual, "Join Filter", planstate, ancestors, es); if (((MergeJoin*)plan)->join.joinqual) show_instrumentation_count("Rows Removed by Join Filter", 1, planstate, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 2, planstate, es); show_llvm_info(planstate, es); show_skew_optimization(planstate, es); } break; case T_HashJoin: { show_upper_qual(((HashJoin*)plan)->hashclauses, "Hash Cond", planstate, ancestors, es); show_upper_qual(((HashJoin*)plan)->join.joinqual, "Join Filter", planstate, ancestors, es); if (((HashJoin*)plan)->join.joinqual) show_instrumentation_count("Rows Removed by Join Filter", 1, planstate, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 2, planstate, es); show_skew_optimization(planstate, es); } break; case T_VecHashJoin: { show_upper_qual(((HashJoin*)plan)->hashclauses, "Hash Cond", planstate, ancestors, es); show_upper_qual(((HashJoin*)plan)->join.joinqual, "Join Filter", planstate, ancestors, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); show_llvm_info(planstate, es); show_bloomfilter<true>(plan, planstate, ancestors, es); show_skew_optimization(planstate, es); } show_vechash_info((VecHashJoinState*)planstate, es); break; case T_VecAgg: case T_Agg: show_groupby_keys((AggState*)planstate, ancestors, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); switch (((Agg*)plan)->aggstrategy) { case AGG_HASHED: { show_hashAgg_info((AggState*)planstate, es); show_llvm_info(planstate, es); } break; case AGG_SORTED: { show_llvm_info(planstate, es); } break; default: break; } show_skew_optimization(planstate, es); show_unique_check_info(planstate, es); break; case T_Group: case T_VecGroup: show_group_keys((GroupState*)planstate, ancestors, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); break; case T_Sort: case T_VecSort: show_sort_keys((SortState*)planstate, ancestors, es); show_sort_info((SortState*)planstate, es); show_llvm_info(planstate, es); break; case T_MergeAppend: show_merge_append_keys((MergeAppendState*)planstate, ancestors, es); break; case T_BaseResult: case T_VecResult: show_upper_qual((List*)((BaseResult*)plan)->resconstantqual, "One-Time Filter", planstate, ancestors, es); show_upper_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); break; case T_Hash: show_hash_info((HashState*)planstate, es); break; case T_SetOp: case T_VecSetOp: switch (((SetOp*)plan)->strategy) { case SETOP_HASHED: show_setop_info((SetOpState*)planstate, es); break; default: break; } break; case T_RecursiveUnion: show_recursive_info((RecursiveUnionState*)planstate, es); break; default: break; } switch (nodeTag(plan)) { case T_VecNestLoop: case T_NestLoop: case T_VecMergeJoin: case T_MergeJoin: case T_Group: case T_VecGroup: case T_BaseResult: case T_VecResult: case T_Append: case T_Unique: case T_VecUnique: case T_Limit: case T_PartIterator: case T_VecPartIterator: case T_VecToRow: case T_RowToVec: case T_VecAppend: case T_VecLimit: case T_MergeAppend: case T_SubqueryScan: case T_VecSubqueryScan: case T_ValuesScan: break; default: { /* Show buffer usage */ if (es->buffers) { if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) show_datanode_buffers(es, planstate); else if (!es->from_dn) { if (is_pretty && es->planinfo->m_IOInfo) show_buffers(es, es->planinfo->m_IOInfo->info_str, planstate->instrument, false, -1, -1, NULL); else show_buffers(es, es->str, planstate->instrument, false, -1, -1, NULL); } } } break; } /* if 'cpu' is specified, display the cpu cost */ if (es->cpu) { uint64 proRows = 0; double incCycles = 0.0; double exCycles = 0.0; double outerCycles = 0.0; double innerCycles = 0.0; uint64 outterRows = 0; uint64 innerRows = 0; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->detail) { ExplainOpenGroup("Cpus In Detail", "Cpus In Detail", false, es); int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (int j = 0; j < dop; j++) { outerCycles = 0.0; innerCycles = 0.0; ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr == NULL) continue; append_datanode_name(es, node_name, dop, j); show_child_cpu_cycles_and_rows<true>( planstate, i, j, &outerCycles, &innerCycles, &outterRows, &innerRows); if (es->planinfo != NULL && es->planinfo->m_runtimeinfo != NULL && instr != NULL && instr->nloops > 0) { es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); es->planinfo->m_datanodeInfo->set_datanode_name(node_name, j, dop); } proRows = (long)(instr->ntuples); CalculateProcessedRows(planstate, i, j, &innerRows, &outterRows, &proRows); show_cpu(es, instr, innerCycles, outerCycles, i, j, proRows); ExplainCloseGroup("Plan", NULL, true, es); } } ExplainCloseGroup("Cpus In Detail", "Cpus In Detail", false, es); } else show_detail_cpu(es, planstate); } else if (!es->from_dn) { const CPUUsage* usage = &planstate->instrument->cpuusage; show_child_cpu_cycles_and_rows<false>(planstate, 0, 0, &outerCycles, &innerCycles, &outterRows, &innerRows); incCycles = usage->m_cycles; exCycles = incCycles - outerCycles - innerCycles; proRows = (long)(planstate->instrument->ntuples); CalculateProcessedRows(planstate, 0, 0, &innerRows, &outterRows, &proRows); if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty) { int64 ex_cyc_rows = proRows != 0 ? (long)(exCycles / proRows) : 0; if (es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(-1, -1, EX_CYC, Int64GetDatum(exCycles)); es->planinfo->m_runtimeinfo->put(-1, -1, INC_CYC, Int64GetDatum(incCycles)); es->planinfo->m_runtimeinfo->put(-1, -1, EX_CYC_PER_ROWS, Int64GetDatum(ex_cyc_rows)); appendStringInfoSpaces(es->planinfo->m_datanodeInfo->info_str, 8); show_cpu_info(es->planinfo->m_datanodeInfo->info_str, incCycles, exCycles, proRows); } if (es->planinfo->m_IOInfo) { es->planinfo->m_IOInfo->set_plan_name<true, true>(); show_cpu_info(es->planinfo->m_IOInfo->info_str, incCycles, exCycles, proRows); } } else { appendStringInfoSpaces(es->str, es->indent * 2); show_cpu_info(es->str, incCycles, exCycles, proRows); } } else { ExplainPropertyLong("Exclusive Cycles Per Row", proRows != 0 ? (long)(exCycles / proRows) : 0, es); ExplainPropertyLong("Exclusive Cycles", (long)exCycles, es); ExplainPropertyLong("Inclusive Cycles", (long)incCycles, es); } } } /* in text format, partition line start here */ switch (nodeTag(plan)) { case T_SeqScan: case T_CStoreScan: #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: #endif /* ENABLE_MULTIPLE_NODES */ case T_IndexScan: case T_IndexOnlyScan: case T_BitmapHeapScan: case T_BitmapIndexScan: case T_CStoreIndexScan: case T_CStoreIndexHeapScan: case T_TidScan: { if (((Scan*)plan)->isPartTbl) { show_pruning_info(planstate, es, is_pretty); } if (es->verbose && ((Scan*)plan)->bucketInfo != NULL) { show_bucket_info(planstate, es, is_pretty); } } break; case T_PartIterator: case T_VecPartIterator: if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_pretty == false) { if (es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); } else { appendStringInfoSpaces(es->str, es->indent * 2); } ExplainNodePartition(plan, es); } else { es->planinfo->m_detailInfo->set_plan_name<true, true>(); appendStringInfo( es->planinfo->m_detailInfo->info_str, "Iterations: %d", ((PartIterator*)plan)->itrs); appendStringInfoChar(es->planinfo->m_detailInfo->info_str, '\n'); } } else { ExplainPropertyInteger("Iterations", ((PartIterator*)plan)->itrs, es); } break; default: break; } runnext: /* Get ready to display the child plans */ haschildren = planstate->initPlan || outerPlanState(planstate) || innerPlanState(planstate) || IsA(plan, ModifyTable) || IsA(plan, VecModifyTable) || IsA(plan, Append) || IsA(plan, VecAppend) || IsA(plan, MergeAppend) || IsA(plan, VecMergeAppend) || IsA(plan, BitmapAnd) || IsA(plan, BitmapOr) || IsA(plan, SubqueryScan) || IsA(plan, VecSubqueryScan) || (IsA(planstate, ExtensiblePlanState) && ((ExtensiblePlanState*)planstate)->extensible_ps != NIL) || planstate->subPlan; if (haschildren) { ExplainOpenGroup("Plans", "Plans", false, es); /* Pass current PlanState as head of ancestors list for children */ ancestors = lcons(planstate, ancestors); } /* initPlan-s */ if (planstate->initPlan) ExplainSubPlans(planstate->initPlan, ancestors, "InitPlan", es); /* Cte distributed support */ if (IS_STREAM_PLAN && IsA(plan, CteScan)) { CteScanState* css = (CteScanState*)planstate; if (css->cteplanstate) { ExplainNode<is_pretty>(css->cteplanstate, ancestors, "CTE Sub", NULL, es); } } old_dn_flag = es->from_dn; /* lefttree */ if (outerPlanState(planstate)) { if (IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery)) es->from_dn = true; ExplainNode<is_pretty>(outerPlanState(planstate), ancestors, "Outer", NULL, es); } es->from_dn = old_dn_flag; /* righttree */ if (innerPlanState(planstate)) { if (IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery)) es->from_dn = true; ExplainNode<is_pretty>(innerPlanState(planstate), ancestors, "Inner", NULL, es); } es->from_dn = old_dn_flag; /* special child plans */ switch (nodeTag(plan)) { case T_ModifyTable: case T_VecModifyTable: ExplainMemberNodes(((ModifyTable*)plan)->plans, ((ModifyTableState*)planstate)->mt_plans, ancestors, es); break; case T_VecAppend: case T_Append: ExplainMemberNodes(((Append*)plan)->appendplans, ((AppendState*)planstate)->appendplans, ancestors, es); break; case T_MergeAppend: ExplainMemberNodes( ((MergeAppend*)plan)->mergeplans, ((MergeAppendState*)planstate)->mergeplans, ancestors, es); break; case T_BitmapAnd: ExplainMemberNodes( ((BitmapAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, ancestors, es); break; case T_BitmapOr: ExplainMemberNodes(((BitmapOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, ancestors, es); break; case T_CStoreIndexAnd: ExplainMemberNodes( ((CStoreIndexAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, ancestors, es); break; case T_CStoreIndexOr: ExplainMemberNodes( ((CStoreIndexOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, ancestors, es); break; case T_SubqueryScan: case T_VecSubqueryScan: ExplainNode<is_pretty>(((SubqueryScanState*)planstate)->subplan, ancestors, "Subquery", NULL, es); break; case T_ExtensiblePlan: ExplainExtensibleChildren((ExtensiblePlanState*)planstate, ancestors, es); break; default: break; } /* subPlan-s */ if (planstate->subPlan) ExplainSubPlans(planstate->subPlan, ancestors, "SubPlan", es); /* end of child plans */ if (haschildren) { ancestors = list_delete_first(ancestors); ExplainCloseGroup("Plans", "Plans", false, es); } /* in text format, undo whatever indentation we added */ if (es->format == EXPLAIN_FORMAT_TEXT) { es->indent = save_indent; es->pindent = save_pindent; } ExplainCloseGroup("Plan", relationship ? NULL : "Plan", true, es); /* Set info for explain plan. Note that we do not deal with query shipping except "explain plan for select for * update". */ if (es->plan && (planstate->plan->plan_node_id != 0 || IsExplainPlanSelectForUpdateStmt)) { /* * 1.Handle the case for select for update. * Step 1: Check if it's a select for update case. */ if (planstate->plan->plan_node_id == 0 && IsExplainPlanSelectForUpdateStmt) { /* Step 2: Set operation for plan table. */ GetPlanNodePlainText(plan, &pname, &sname, &strategy, &operation, &pt_operation, &pt_options); /* Step 3: Set object_type for plan table. */ RangeTblEntry* rte = (RangeTblEntry*)llast(es->rtable); char* objectname = rte->relname; const char* object_type = "REMOTE_QUERY"; es->planinfo->m_planTableData->set_plan_table_objs(plan->plan_node_id, objectname, object_type, NULL); /* Step 4: Set projection for plan table. */ show_plan_tlist(planstate, ancestors, es); } /* 2.set operation and options, for 'stream' type, operation will be null */ if (pt_operation == NULL && pname != NULL) es->planinfo->m_planTableData->set_plan_table_streaming_ops(pname, &pt_operation, &pt_options); es->planinfo->m_planTableData->set_plan_table_ops(planstate->plan->plan_node_id, pt_operation, pt_options); /* * 3.set object info for index. * For index scan we cannot get its object info from ExplainTargetRel. We only can get the info from * ExplainNode. */ if (strcmp(pt_operation, "INDEX") == 0 && pt_index_name != NULL && pt_index_owner != NULL) es->planinfo->m_planTableData->set_plan_table_objs( planstate->plan->plan_node_id, pt_index_name, pt_operation, pt_index_owner); } } /* * CalculateProcessedRows * The input processed tuple number equals to the returned tuple number * of the current node. Here we modify the iput processed tuple rows more precisely. * For Example in SeqScan, the processed tuple number should add the tuple number * removed by filter. * @param (in) innerRows: * returned tuple number for right child node. * @param (in) outterRows: * returned tuple number for left child node. * @param (in) processedrows: * returned tuple number for current node. * @param (out) processedrows: * the processed tuple number for the current node. */ static void CalculateProcessedRows( PlanState* planstate, int idx, int smpIdx, const uint64* inner_rows, const uint64* outter_rows, uint64* processed_rows) { int removed_rows = 0; Plan* plan = planstate->plan; switch (nodeTag(plan)) { case T_SeqScan: case T_CStoreScan: #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: #endif /* ENABLE_MULTIPLE_NODES */ case T_DfsScan: show_removed_rows(1, planstate, idx, smpIdx, &removed_rows); *processed_rows += removed_rows; break; case T_NestLoop: case T_VecNestLoop: case T_VecMergeJoin: case T_MergeJoin: case T_HashJoin: case T_VecHashJoin: *processed_rows = (*inner_rows) + (*outter_rows); break; case T_Agg: case T_Sort: case T_SetOp: case T_VecSetOp: case T_VecAgg: case T_VecSort: *processed_rows = *outter_rows; break; default: break; } } /* * show_plan_execnodes * show exec nodes information of a plan node * * @param (in) planstate: * the plan state * @param (in) es: * the explain state * * @return: void */ static void show_plan_execnodes(PlanState* planstate, ExplainState* es) { Plan* plan = planstate->plan; if (IsA(plan, Stream) || IsA(plan, VecStream) || IsA(plan, ModifyTable) || IsA(plan, VecModifyTable) || IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery) || u_sess->pgxc_cxt.NumDataNodes == 0) { return; } ShowRunNodeInfo(plan->exec_nodes, es, "Exec Nodes"); return; } /* * Show the targetlist of a plan node */ static void show_plan_tlist(PlanState* planstate, List* ancestors, ExplainState* es) { Plan* plan = planstate->plan; List* context = NIL; List* result = NIL; bool useprefix = false; ListCell* lc = NULL; /* No work if empty tlist (this occurs eg in bitmap indexscans) */ if (plan->targetlist == NIL) return; /* The tlist of an Append isn't real helpful, so suppress it */ if (IsA(plan, Append) || IsA(plan, VecAppend)) return; /* Likewise for MergeAppend and RecursiveUnion */ if (IsA(plan, MergeAppend) || IsA(plan, VecMergeAppend)) return; if (IsA(plan, RecursiveUnion) || IsA(plan, VecRecursiveUnion)) return; /* Set up deparsing context */ context = deparse_context_for_planstate((Node*)planstate, ancestors, es->rtable); useprefix = list_length(es->rtable) > 1; /* Deparse each result column (we now include resjunk ones) */ foreach (lc, plan->targetlist) { TargetEntry* tle = (TargetEntry*)lfirst(lc); result = lappend(result, deparse_expression((Node*)tle->expr, context, useprefix, false)); } if (IsA(plan, ForeignScan) || IsA(plan, VecForeignScan)) { ForeignScan* fscan = (ForeignScan*)plan; if (IsSpecifiedFDWFromRelid(fscan->scan_relid, GC_FDW)) { List* str_targetlist = get_str_targetlist(fscan->fdw_private); if (str_targetlist != NULL) result = str_targetlist; } } /* Print results */ ExplainPropertyList("Output", result, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_verboseInfo->info_str, "Output: "); ExplainPrettyList(result, es); } /* For explain plan */ if (es->plan) es->planinfo->m_planTableData->set_plan_table_projection(plan->plan_node_id, result); #ifdef ENABLE_MULTIPLE_NODES /* show distributeKey of scan */ if (plan->distributed_keys != NIL && show_scan_distributekey(plan)) { List* distKey = NIL; List* keyList = NIL; keyList = plan->distributed_keys; foreach (lc, keyList) { Var* distriVar = (Var*)lfirst(lc); distKey = lappend(distKey, deparse_expression((Node*)distriVar, context, useprefix, false)); } ExplainPropertyList("Distribute Key", distKey, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfoString(es->planinfo->m_verboseInfo->info_str, "Distribute Key: "); ExplainPrettyList(distKey, es); } } #endif #ifdef STREAMPLAN if ((IsA(plan, Stream) || IsA(plan, VecStream)) && (is_redistribute_stream((Stream*)plan) || is_hybid_stream((Stream*)plan)) && ((Stream*)plan)->distribute_keys != NIL) { List* distKey = NIL; List* keyList = NIL; keyList = ((Stream*)plan)->distribute_keys; foreach (lc, keyList) { Var* distriVar = (Var*)lfirst(lc); distKey = lappend(distKey, deparse_expression((Node*)distriVar, context, useprefix, false)); } ExplainPropertyList("Distribute Key", distKey, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfoString(es->planinfo->m_verboseInfo->info_str, "Distribute Key: "); ExplainPrettyList(distKey, es); } list_free_deep(distKey); } #endif } /* * ContainRteInRlsPolicyWalker * Check node whether contain specified RangeTblEntry * * @param (in)node: Node info * @param (in)unused_info: do not use this infor * @return: Find row level security policy in this RangeTblEntry or not */ static bool ContainRlsQualInRteWalker(Node* node, void* unused_info) { if (node == NULL) { return false; } /* Check range table entry */ if (IsA(node, RangeTblEntry)) { RangeTblEntry* rte = (RangeTblEntry*)node; if ((rte->rtekind == RTE_RELATION) && (rte->securityQuals != NIL)) { return true; } return false; } /* Check Query */ if (IsA(node, Query)) { /* Check RTE and skip remote dummy node */ return range_table_walker(((Query*)node)->rtable, (bool (*)())ContainRlsQualInRteWalker, unused_info, QTW_EXAMINE_RTES | QTW_IGNORE_DUMMY); } return expression_tree_walker(node, (bool (*)())ContainRlsQualInRteWalker, unused_info); } /* * Show a generic expression */ static void show_expression( Node* node, const char* qlabel, PlanState* planstate, List* ancestors, bool useprefix, ExplainState* es) { List* context = NIL; char* exprstr = NULL; /* Set up deparsing context */ context = deparse_context_for_planstate((Node*)planstate, ancestors, es->rtable); /* Deparse the expression */ exprstr = deparse_expression(node, context, useprefix, false); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_detailInfo) { es->planinfo->m_detailInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_detailInfo->info_str, "%s: %s\n", qlabel, exprstr); } /* And add to es->str */ ExplainPropertyText(qlabel, exprstr, es); } /* * Show a qualifier expression (which is a List with implicit AND semantics) */ static void show_qual( List* qual, const char* qlabel, PlanState* planstate, List* ancestors, bool useprefix, ExplainState* es) { Node* node = NULL; /* No work if empty qual */ if (qual == NIL) return; /* Convert AND list to explicit AND */ node = (Node*)make_ands_explicit(qual); /* And show it */ show_expression(node, qlabel, planstate, ancestors, useprefix, es); } /* * Show a qualifier expression for a scan plan node */ static void show_scan_qual(List* qual, const char* qlabel, PlanState* planstate, List* ancestors, ExplainState* es) { bool useprefix = false; useprefix = (IsA(planstate->plan, SubqueryScan) || IsA(planstate->plan, VecSubqueryScan) || es->verbose); show_qual(qual, qlabel, planstate, ancestors, useprefix, es); } /* * @Description: Show bloom filter index info. * @in filterNumList: Index list. * @in es: Explain state. */ template <bool generate> static void show_bloomfilter_number(const List* filterNumList, ExplainState* es) { if (filterNumList != NULL) { StringInfo str = NULL; StringInfoData index_info; initStringInfo(&index_info); bool first = true; ListCell* l = NULL; foreach (l, filterNumList) { if (first) { appendStringInfo(&index_info, "%d", lfirst_int(l)); } else { appendStringInfo(&index_info, ", %d", lfirst_int(l)); } first = false; } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { es->planinfo->m_detailInfo->set_plan_name<false, true>(); str = es->planinfo->m_detailInfo->info_str; } else { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoSpaces(es->str, es->indent * 2); str = es->str; } if (es->format == EXPLAIN_FORMAT_TEXT) { /* Append bloom filter num.*/ if (generate) { appendStringInfo(str, "%s: %s\n", "Generate Bloom Filter On Index", index_info.data); } else { appendStringInfo(str, "%s: %s\n", "Filter By Bloom Filter On Index", index_info.data); } } else { /* Append bloom filter num.*/ if (generate) { ExplainPropertyText("Generate Bloom Filter On Index", index_info.data, es); } else { ExplainPropertyText("Filter By Bloom Filter On Index", index_info.data, es); } } pfree_ext(index_info.data); } } /* * @Description: Show bloomfilter information, include filter var and filter index. * @in plan: Vechashjoin plan or Scan plan(include hdfs, hdfs foreign scan). * @in planstate: PlanState node. * @in ancestors: Ancestors list should already contain the immediate parent of these * SubPlanStates. * @in es: Explain state. */ template <bool generate> static void show_bloomfilter(Plan* plan, PlanState* planstate, List* ancestors, ExplainState* es) { if (plan->var_list) { if (generate) { show_expression((Node*)plan->var_list, "Generate Bloom Filter On Expr", planstate, ancestors, true, es); } else { show_expression((Node*)plan->var_list, "Filter By Bloom Filter On Expr", planstate, ancestors, true, es); } /* Show bloom filter numbers. */ show_bloomfilter_number<generate>(plan->filterIndexList, es); } } static void show_skew_optimization(const PlanState* planstate, ExplainState* es) { int skew_opt = SKEW_RES_NONE; char* skew_txt = NULL; switch (planstate->plan->type) { case T_NestLoop: case T_VecNestLoop: case T_HashJoin: case T_VecHashJoin: case T_MergeJoin: case T_VecMergeJoin: skew_opt = ((Join*)planstate->plan)->skewoptimize; skew_txt = "Skew Join Optimized"; break; case T_Agg: case T_VecAgg: skew_opt = ((Agg*)planstate->plan)->skew_optimize; skew_txt = "Skew Agg Optimized"; break; default: return; } if (skew_opt == SKEW_RES_NONE) return; /* Choose skew optimize source. */ StringInfoData str; initStringInfo(&str); appendStringInfo(&str, "%s by", skew_txt); if ((unsigned int)skew_opt & SKEW_RES_HINT) { if ((unsigned int)skew_opt & (SKEW_RES_HINT - 1)) appendStringInfo(&str, " %s,", "Hint"); else appendStringInfo(&str, " %s", "Hint"); } if ((unsigned int)skew_opt & SKEW_RES_RULE) { if ((unsigned int)skew_opt & (SKEW_RES_RULE - 1)) appendStringInfo(&str, " %s,", "Rule"); else appendStringInfo(&str, " %s", "Rule"); } if ((unsigned int)skew_opt & SKEW_RES_STAT) appendStringInfo(&str, " %s", "Statistic"); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { /* For skew agg, we add node info before print skew info in pretty mode. */ if (planstate->plan->type == T_Agg || planstate->plan->type == T_VecAgg) { StringInfo agg_node_des = makeStringInfo(); int rc = snprintf_s(agg_node_des->data, agg_node_des->maxlen, agg_node_des->maxlen - 1, "%3d --%s", planstate->plan->plan_node_id, es->planinfo->m_planInfo->m_pname.data); securec_check_ss(rc, "\0", "\0"); if (strstr(es->planinfo->m_detailInfo->info_str->data, agg_node_des->data) == NULL) appendStringInfo(es->planinfo->m_detailInfo->info_str, "%3d --%s\n", planstate->plan->plan_node_id, es->planinfo->m_planInfo->m_pname.data); } appendStringInfoSpaces(es->planinfo->m_detailInfo->info_str, 8); appendStringInfo(es->planinfo->m_detailInfo->info_str, "%s\n", str.data); } else { if (es->format == EXPLAIN_FORMAT_TEXT && !es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "%s\n", str.data); } } pfree_ext(str.data); } /** * @Description: Show pushdown quals in the flag identifier. */ static void show_pushdown_qual(PlanState* planstate, List* ancestors, ExplainState* es, const char* identifier) { Plan* plan = planstate->plan; switch (nodeTag(plan)) { case T_DfsScan: { DfsPrivateItem* item = (DfsPrivateItem*)((DefElem*)linitial(((DfsScan*)plan)->privateData))->arg; show_scan_qual(item->hdfsQual, identifier, planstate, ancestors, es); break; } case T_DfsIndexScan: { DfsScan* scan = ((DfsIndexScan*)plan)->dfsScan; if (!((DfsIndexScan*)plan)->indexonly) { DfsPrivateItem* item = (DfsPrivateItem*)((DefElem*)linitial(scan->privateData))->arg; show_scan_qual(item->hdfsQual, identifier, planstate, ancestors, es); } break; } case T_ForeignScan: case T_VecForeignScan: { /* * Only the HDFS foreign plan has pushdown predicate feature, * So show the pushdown predicate filter on HDFS foreign plan. */ if (((ForeignScanState*)planstate)->fdwroutine->GetFdwType != NULL && ((ForeignScanState*)planstate)->fdwroutine->GetFdwType() == HDFS_ORC) { DefElem* private_data = (DefElem*)linitial(((ForeignScan*)plan)->fdw_private); DfsPrivateItem* item = (DfsPrivateItem*)private_data->arg; show_scan_qual(item->hdfsQual, identifier, planstate, ancestors, es); } break; } case T_ExtensiblePlan: { ExtensiblePlanState* css = (ExtensiblePlanState*)planstate; show_scan_qual(plan->qual, "Filter", planstate, ancestors, es); if (plan->qual) { show_instrumentation_count("Rows Removed by Filter", 1, planstate, es); } if (css->methods->ExplainExtensiblePlan) { css->methods->ExplainExtensiblePlan(css, ancestors, es); } break; } default: { /* * Do nothing. */ break; } } } /* * Show a qualifier expression for an upper-level plan node */ static void show_upper_qual(List* qual, const char* qlabel, PlanState* planstate, List* ancestors, ExplainState* es) { bool useprefix = false; useprefix = (list_length(es->rtable) > 1 || es->verbose); show_qual(qual, qlabel, planstate, ancestors, useprefix, es); } /* * @Description: append the datanode name to str. * @in es: explain state. * @in node_name: datanode name * @in dop: query dop * @in j: current dop index * @out: return void */ static void append_datanode_name(ExplainState* es, char* node_name, int dop, int j) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); if (dop == 1) appendStringInfo(es->str, " %s ", node_name); else appendStringInfo(es->str, " %s[worker %d] ", node_name, j); } else { if (dop == 1) { ExplainPropertyText("DN Name", node_name, es); } else { ExplainPropertyText("DN Name", node_name, es); ExplainPropertyInteger("Worker", j, es); } } } /* * Show the group by keys for a Agg node. */ static void show_groupby_keys(AggState* aggstate, List* ancestors, ExplainState* es) { Agg* plan = (Agg*)aggstate->ss.ps.plan; if (plan->numCols > 0 || plan->groupingSets) { /* The key columns refer to the tlist of the child plan */ ancestors = lcons(aggstate, ancestors); if (plan->groupingSets) show_grouping_sets(outerPlanState(aggstate), plan, ancestors, es); else show_sort_group_keys(outerPlanState(aggstate), "Group By Key", plan->numCols, plan->grpColIdx, NULL, NULL, NULL, ancestors, es); ancestors = list_delete_first(ancestors); } } static void show_grouping_sets(PlanState* planstate, Agg* agg, List* ancestors, ExplainState* es) { List* context = NIL; bool useprefix = false; ListCell* lc = NULL; /* Set up deparsing context */ context = deparse_context_for_planstate((Node*)planstate, ancestors, es->rtable); useprefix = (list_length(es->rtable) > 1 || es->verbose); ExplainOpenGroup("Grouping Sets", "Grouping Sets", false, es); show_grouping_set_keys(planstate, agg, NULL, context, useprefix, ancestors, es); foreach (lc, agg->chain) { Agg* aggnode = (Agg*)lfirst(lc); Sort* sortnode = (Sort*)aggnode->plan.lefttree; show_grouping_set_keys(planstate, aggnode, sortnode, context, useprefix, ancestors, es); } ExplainCloseGroup("Grouping Sets", "Grouping Sets", false, es); } static void show_grouping_set_keys(PlanState* planstate, Agg* aggnode, Sort* sortnode, List* context, bool useprefix, List* ancestors, ExplainState* es) { Plan* plan = planstate->plan; char* exprstr = NULL; ListCell* lc = NULL; List* gsets = aggnode->groupingSets; AttrNumber* keycols = aggnode->grpColIdx; ExplainOpenGroup("Grouping Set", NULL, true, es); if (sortnode != NULL) { show_sort_group_keys(planstate, "Sort Key", sortnode->numCols, sortnode->sortColIdx, sortnode->sortOperators, sortnode->collations, sortnode->nullsFirst, ancestors, es); if (es->format == EXPLAIN_FORMAT_TEXT) es->indent++; } ExplainOpenGroup("Group Keys", "Group Keys", false, es); foreach (lc, gsets) { List* result = NIL; ListCell* lc2 = NULL; foreach (lc2, (List*)lfirst(lc)) { Index i = lfirst_int(lc2); AttrNumber keyresno = keycols[i]; TargetEntry* target = get_tle_by_resno(plan->targetlist, keyresno); if (target == NULL) ereport(ERROR, (errcode(ERRCODE_OPTIMIZER_INCONSISTENT_STATE), errmsg("no tlist entry for key %d", keyresno))); /* Deparse the expression, showing any top-level cast */ exprstr = deparse_expression((Node*)target->expr, context, useprefix, true); result = lappend(result, exprstr); } if (result == NIL && es->format == EXPLAIN_FORMAT_TEXT) ExplainPropertyText("Group By Key", "()", es); else ExplainPropertyListNested("Group By Key", result, es); } ExplainCloseGroup("Group Keys", "Group Keys", false, es); if (sortnode != NULL && es->format == EXPLAIN_FORMAT_TEXT) es->indent--; ExplainCloseGroup("Grouping Set", NULL, true, es); } /* * @Description:Show the grouping keys for a Group node. * @in gstate - group node state * @in ancestors - a list of parent PlanState nodes, most-closely-nested first. * These are needed in order to interpret PARAM_EXEC Params. * @in es - explain state. */ static void show_group_keys(GroupState* gstate, List* ancestors, ExplainState* es) { Group* plan = (Group*)gstate->ss.ps.plan; /* The key columns refer to the tlist of the child plan */ ancestors = lcons(gstate, ancestors); show_sort_group_keys( outerPlanState(gstate), "Group By Key", plan->numCols, plan->grpColIdx, NULL, NULL, NULL, ancestors, es); ancestors = list_delete_first(ancestors); } /* * Show the sort keys for a Sort node. */ static void show_sort_keys(SortState* sortstate, List* ancestors, ExplainState* es) { Sort* plan = (Sort*)sortstate->ss.ps.plan; show_sort_group_keys((PlanState*)sortstate, "Sort Key", plan->numCols, plan->sortColIdx, plan->sortOperators, plan->collations, plan->nullsFirst, ancestors, es); } /* * Likewise, for a MergeAppend node. */ static void show_merge_append_keys(MergeAppendState* mstate, List* ancestors, ExplainState* es) { MergeAppend* plan = (MergeAppend*)mstate->ps.plan; show_sort_group_keys((PlanState*)mstate, "Sort Key", plan->numCols, plan->sortColIdx, plan->sortOperators, plan->collations, plan->nullsFirst, ancestors, es); } /* * Likewise, for a merge sort info of RemoteQuery or Broadcast node. */ static void show_merge_sort_keys(PlanState* state, List* ancestors, ExplainState* es) { SimpleSort* sort = NULL; Plan* plan = state->plan; if (IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery)) sort = ((RemoteQuery*)plan)->sort; else if (IsA(plan, Stream) || IsA(plan, VecStream)) sort = ((Stream*)plan)->sort; /* No merge sort keys, just return */ if (sort == NULL) return; show_sort_group_keys((PlanState*)state, "Merge Sort Key", sort->numCols, sort->sortColIdx, sort->sortOperators, sort->sortCollations, sort->nullsFirst, ancestors, es); } static void show_detail_sortinfo(ExplainState* es, const char* sortMethod, const char* spaceType, long spaceUsed) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(es->str, "Sort Method: %s %s: %ldkB\n", sortMethod, spaceType, spaceUsed); } else { ExplainPropertyText("Sort Method", sortMethod, es); ExplainPropertyLong("Sort Space Used", spaceUsed, es); ExplainPropertyText("Sort Space Type", spaceType, es); } } /* * show min and max sort info */ static void show_detail_sortinfo_min_max( ExplainState* es, const char* sortMethod, const char* spaceType, long minspaceUsed, long maxspaceUsed) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo( es->str, "Sort Method: %s %s: %ldkB ~ %ldkB\n", sortMethod, spaceType, minspaceUsed, maxspaceUsed); } else { ExplainPropertyText("Sort Method", sortMethod, es); ExplainPropertyLong("Sort Space Min Used", minspaceUsed, es); ExplainPropertyLong("Sort Space Max Used", maxspaceUsed, es); ExplainPropertyText("Sort Space Type", spaceType, es); } } /* * @Description: show peak memory for each datanode and coordinator * @in es - the explain state info * @in plan_size - current plan size * @out - void */ static void show_peak_memory(ExplainState* es, int plan_size) { if (u_sess->instr_cxt.global_instr == NULL) { elog(ERROR, "u_sess->instr_cxt.global_instr is NULL"); } bool from_datanode = false; bool last_datanode = u_sess->instr_cxt.global_instr->isFromDataNode(1); for (int i = 1; i < plan_size; i++) { int dop = u_sess->instr_cxt.global_instr->getNodeDop(i + 1); from_datanode = u_sess->instr_cxt.global_instr->isFromDataNode(i + 1); if (!last_datanode && from_datanode) { int64 peak_memory = (int64)(unsigned)((uint)(t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->peakChunksQuery - t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->initMemInChunks) << (unsigned int)(chunkSizeInBits - BITS_IN_MB)); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Coordinator Query Peak Memory:\n"); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Query Peak Memory: %ldMB\n", peak_memory); Instrumentation* instr = NULL; int64 max_peak_memory = -1; int64 min_peak_memory = LONG_MAX; bool is_execute = false; if (es->detail) appendStringInfo(es->planinfo->m_staticInfo->info_str, "DataNode Query Peak Memory\n"); for (int j = 0; j < u_sess->instr_cxt.global_instr->getInstruNodeNum(); j++) { for (int k = 0; k < dop; k++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(j, i + 1, k); #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(j, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif if (instr != NULL) { if (!is_execute) is_execute = true; if (es->detail) { peak_memory = instr->memoryinfo.peakNodeMemory; es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Query Peak Memory: %ldMB\n", peak_memory); } else { max_peak_memory = rtl::max(max_peak_memory, instr->memoryinfo.peakNodeMemory); min_peak_memory = rtl::min(min_peak_memory, instr->memoryinfo.peakNodeMemory); } } } } if (is_execute && !es->detail) { appendStringInfo(es->planinfo->m_staticInfo->info_str, "Datanode:\n"); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Max Query Peak Memory: %ldMB\n", max_peak_memory); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Min Query Peak Memory: %ldMB\n", min_peak_memory); } } last_datanode = from_datanode; } } /* * @Description: show the min/max of datanode executor start/run/end time. * @in es - the explain state info * @in plan_node_id - current plan node id * @in stage - the stage of executor time * @out - void */ static void show_dn_executor_time(ExplainState* es, int plan_node_id, ExecutorTime stage) { Instrumentation* instr = NULL; double min_time = 0; double max_time = 0; int min_idx = 0; int max_idx = 0; bool fisrt_time = true; const char* symbol_time = "nostage"; int data_size = u_sess->instr_cxt.global_instr->getInstruNodeNum(); for (int i = 0; i < data_size; i++) { double exec_time; instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, plan_node_id + 1); if (instr != NULL) { switch (stage) { case DN_START_TIME: exec_time = instr->init_time * 1000.0; symbol_time = "start"; break; case DN_RUN_TIME: exec_time = instr->run_time * 1000.0; symbol_time = "run"; break; case DN_END_TIME: exec_time = instr->end_time * 1000.0; symbol_time = "end"; break; } if (fisrt_time) { min_time = exec_time; min_idx = i; max_time = exec_time; max_idx = i; fisrt_time = false; } else { if (exec_time > max_time) { max_time = exec_time; max_idx = i; } if (exec_time < min_time) { min_time = exec_time; min_idx = i; } } } } #ifdef ENABLE_MULTIPLE_NODES char* min_node_name = PGXCNodeGetNodeNameFromId(min_idx, PGXC_NODE_DATANODE); char* max_node_name = PGXCNodeGetNodeNameFromId(max_idx, PGXC_NODE_DATANODE); #else char* min_node_name = g_instance.exec_cxt.nodeName; char* max_node_name = g_instance.exec_cxt.nodeName; #endif appendStringInfo(es->planinfo->m_query_summary->info_str, "Datanode executor %s time [%s, %s]: [%.3f ms,%.3f ms]\n", symbol_time, min_node_name, max_node_name, min_time, max_time); } /* * If it's EXPLAIN ANALYZE, show tuplesort stats for a sort node */ static void show_sort_info(SortState* sortstate, ExplainState* es) { PlanState* planstate = NULL; planstate = (PlanState*)sortstate; AssertEreport(IsA(sortstate, SortState) || IsA(sortstate, VecSortState), MOD_EXECUTOR, "unexpect sortstate type"); if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; const char* sortMethod = NULL; const char* spaceType = NULL; long spaceUsed = 0; bool has_sort_info = false; long max_diskUsed = 0; long min_diskUsed = MIN_DISK_USED; long max_memoryUsed = 0; long min_memoryUsed = u_sess->attr.attr_memory.work_mem; int sortMethodId = 0; int spaceTypeId = 0; if (es->detail) { for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); /* * when this operator does not actual executed, we will not show sort info. */ if (instr == NULL || instr->sorthashinfo.sortMethodId < (int)HEAPSORT || instr->sorthashinfo.sortMethodId > (int)STILLINPROGRESS) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif sortMethodId = instr->sorthashinfo.sortMethodId; spaceTypeId = instr->sorthashinfo.spaceTypeId; sortMethod = sortmessage[sortMethodId].sortName; spaceUsed = instr->sorthashinfo.spaceUsed; if (spaceTypeId == SORT_IN_DISK) spaceType = "Disk"; else spaceType = "Memory"; if (es->planinfo != NULL && es->planinfo->m_runtimeinfo != NULL) { es->planinfo->m_runtimeinfo->put(i, 0, SORT_METHOD, PointerGetDatum(cstring_to_text(sortMethod))); es->planinfo->m_runtimeinfo->put(i, 0, SORT_TYPE, PointerGetDatum(cstring_to_text(spaceType))); es->planinfo->m_runtimeinfo->put(i, 0, SORT_SPACE, Int64GetDatum(spaceUsed)); if (es->planinfo->m_staticInfo != NULL) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Sort Method: %s %s: %ldkB\n", sortMethod, spaceType, spaceUsed); } continue; } if (has_sort_info == false) ExplainOpenGroup("Sort Detail", "Sort Detail", false, es); has_sort_info = true; ExplainOpenGroup("Plan", NULL, true, es); append_datanode_name(es, node_name, 1, 0); show_detail_sortinfo(es, sortMethod, spaceType, spaceUsed); ExplainCloseGroup("Plan", NULL, true, es); } if (has_sort_info) ExplainCloseGroup("Sort Detail", "Sort Detail", false, es); } else { for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL || instr->sorthashinfo.sortMethodId < (int)HEAPSORT || instr->sorthashinfo.sortMethodId > (int)STILLINPROGRESS) continue; sortMethodId = instr->sorthashinfo.sortMethodId; spaceTypeId = instr->sorthashinfo.spaceTypeId; sortMethod = sortmessage[sortMethodId].sortName; spaceUsed = instr->sorthashinfo.spaceUsed; if (spaceTypeId == SORT_IN_DISK) { spaceType = "Disk"; max_diskUsed = rtl::max(spaceUsed, max_diskUsed); min_diskUsed = rtl::min(spaceUsed, min_diskUsed); if (min_diskUsed == MIN_DISK_USED) min_diskUsed = spaceUsed; } else { spaceType = "Memory"; max_memoryUsed = rtl::max(spaceUsed, max_memoryUsed); min_memoryUsed = rtl::min(spaceUsed, min_memoryUsed); } } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL && es->planinfo->m_staticInfo != NULL) { if (max_memoryUsed != 0) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); } appendStringInfo(es->planinfo->m_staticInfo->info_str, "Sort Method: %s %s: %ldkB ~ %ldkB\n", sortMethod, "Memory", min_memoryUsed, max_memoryUsed); if (max_diskUsed != 0) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); } appendStringInfo(es->planinfo->m_staticInfo->info_str, "Sort Method: %s %s: %ldkB ~ %ldkB\n", sortMethod, "Disk", min_diskUsed, max_diskUsed); } else { if (max_memoryUsed != 0) { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoSpaces(es->str, es->indent * 2); show_detail_sortinfo_min_max(es, sortMethod, "Memory", min_memoryUsed, max_memoryUsed); } if (max_diskUsed != 0) { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoSpaces(es->str, es->indent * 2); show_detail_sortinfo_min_max(es, sortMethod, "Disk", min_diskUsed, max_diskUsed); } } } } else { char* sortMethod = NULL; char* spaceType = NULL; int spaceTypeId = 0; if (es->analyze && sortstate->sort_Done && sortstate->sortMethodId >= (int)HEAPSORT && sortstate->sortMethodId <= (int)STILLINPROGRESS && (sortstate->spaceTypeId == SORT_IN_DISK || sortstate->spaceTypeId == SORT_IN_MEMORY)) { sortMethod = sortmessage[sortstate->sortMethodId].sortName; spaceTypeId = sortstate->spaceTypeId; if (spaceTypeId == SORT_IN_DISK) spaceType = "Disk"; else spaceType = "Memory"; if (es->planinfo && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(-1, -1, SORT_METHOD, PointerGetDatum(cstring_to_text(sortMethod))); es->planinfo->m_runtimeinfo->put(-1, -1, SORT_TYPE, PointerGetDatum(cstring_to_text(spaceType))); es->planinfo->m_runtimeinfo->put(-1, -1, SORT_SPACE, Int64GetDatum(sortstate->spaceUsed)); } if (es->detail == false && t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Sort Method: %s %s: %ldkB\n", sortMethod, spaceType, sortstate->spaceUsed); } else { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoSpaces(es->str, es->indent * 2); show_detail_sortinfo(es, sortMethod, spaceType, sortstate->spaceUsed); } } } } template <bool is_detail> static void show_datanode_hash_info(ExplainState* es, int nbatch, int nbatch_original, int nbuckets, long spacePeakKb) { if (es->format != EXPLAIN_FORMAT_TEXT) { ExplainPropertyLong("Hash Buckets", nbuckets, es); ExplainPropertyLong("Hash Batches", nbatch, es); ExplainPropertyLong("Original Hash Batches", nbatch_original, es); ExplainPropertyLong("Peak Memory Usage", spacePeakKb, es); } else if (is_detail == false && t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_staticInfo) { if (nbatch_original != nbatch) { appendStringInfo(es->planinfo->m_staticInfo->info_str, " Buckets: %d Batches: %d (originally %d) Memory Usage: %ldkB\n", nbuckets, nbatch, nbatch_original, spacePeakKb); } else { appendStringInfo(es->planinfo->m_staticInfo->info_str, " Buckets: %d Batches: %d Memory Usage: %ldkB\n", nbuckets, nbatch, spacePeakKb); } } else { if (nbatch_original != nbatch) { appendStringInfo(es->str, " Buckets: %d Batches: %d (originally %d) Memory Usage: %ldkB\n", nbuckets, nbatch, nbatch_original, spacePeakKb); } else { appendStringInfo( es->str, " Buckets: %d Batches: %d Memory Usage: %ldkB\n", nbuckets, nbatch, spacePeakKb); } } } /* * Brief : Display LLVM info through explain performance syntax. * Description : Display LLVM info through explain performance syntax. * Input : fsstate, a ForeignScanState struct. * es, a ExplainState struct. * Output : none. * Return Value : none. * Notes : none. */ static void show_llvm_info(const PlanState* planstate, ExplainState* es) { if (!es->detail) return; AssertEreport(planstate != NULL && es != NULL, MOD_EXECUTOR, "unexpect null value"); if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->format == EXPLAIN_FORMAT_TEXT) { for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr != NULL && instr->isLlvmOpt) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(i, 0, LLVM_OPTIMIZATION, true); es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "%s ", node_name); appendStringInfoString(es->planinfo->m_datanodeInfo->info_str, "(LLVM Optimized)\n"); } else { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, " %s", node_name); appendStringInfo(es->str, " (LLVM Optimized)\n"); } } } } else { bool first = true; bool has_llvm = false; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) continue; if (instr->isLlvmOpt) { has_llvm = true; if (first) { ExplainOpenGroup("LLVM Detail", "LLVM Detail", false, es); } ExplainOpenGroup("Plan", NULL, true, es); #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif ExplainPropertyText("DN Name", node_name, es); ExplainPropertyText("LLVM", "LLVM Optimized", es); ExplainCloseGroup("Plan", NULL, true, es); first = false; } } if (has_llvm) ExplainCloseGroup("LLVM Detail", "LLVM Detail", false, es); } } } /* * @Description: show datanode filenum and respill info * @in es: current explainstate * @in file_num: file num to show * @in respill_time: respill times if any(>0) to show * @in expand_times: hashtable expand times * @return: void */ static void show_datanode_filenum_info( ExplainState* es, int file_num, int respill_time, int expand_times, StringInfo info_str) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (file_num > 0) { appendStringInfo(info_str, "Temp File Num: %d", file_num); if (respill_time > 0) { appendStringInfo(info_str, ", Spill Time: %d", respill_time); } if (expand_times > 0) appendStringInfo(info_str, ", Expand Times: %d", expand_times); } if (file_num == 0 && expand_times > 0) { appendStringInfo(info_str, "Expand Times: %d", expand_times); } appendStringInfoChar(info_str, '\n'); } else { ExplainPropertyLong("Temp File Num", file_num, es); ExplainPropertyLong("Spill Time", respill_time, es); ExplainPropertyLong("Expand Times", expand_times, es); } } /* * @Description: show detail filenum * @in es: current explainstate * @in planstate: planstate info * @in label_name: operator label name * @return: void */ static void show_detail_filenum_info(const PlanState* planstate, ExplainState* es, const char* label_name) { Instrumentation* instr = NULL; int max_file_num = 0; int min_file_num = MIN_FILE_NUM; bool is_execute = false; bool is_writefile = false; int datanode_size = 0; int i = 0; int j = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; int count_dn_writefile = 0; if (u_sess->instr_cxt.global_instr) datanode_size = u_sess->instr_cxt.global_instr->getInstruNodeNum(); if (es->detail) { ExplainOpenGroup(label_name, label_name, false, es); for (i = 0; i < datanode_size; i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { is_writefile = instr->sorthashinfo.hash_writefile; int expand_times = instr->sorthashinfo.hashtable_expand_times; if (is_writefile || expand_times > 0) { ExplainOpenGroup("Plan", NULL, true, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL && es->planinfo->m_runtimeinfo != NULL && es->planinfo->m_staticInfo != NULL) { es->planinfo->m_staticInfo->set_plan_name<false, true>(); es->planinfo->m_staticInfo->set_datanode_name(node_name, j, dop); if (is_writefile) { es->planinfo->m_runtimeinfo->put(i, j, HASH_FILENUM, instr->sorthashinfo.hash_FileNum); } show_datanode_filenum_info(es, instr->sorthashinfo.hash_FileNum, instr->sorthashinfo.hash_spillNum, expand_times, es->planinfo->m_staticInfo->info_str); } else { append_datanode_name(es, node_name, dop, j); show_datanode_filenum_info(es, instr->sorthashinfo.hash_FileNum, instr->sorthashinfo.hash_spillNum, expand_times, es->str); } ExplainCloseGroup("Plan", NULL, true, es); } } } } ExplainCloseGroup(label_name, label_name, false, es); } else { if (datanode_size > 0) { int file_num = 0; for (i = 0; i < datanode_size; i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; int count_dop_writefile = 0; for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { if (!is_execute) { is_execute = true; } is_writefile = instr->sorthashinfo.hash_writefile; if (is_writefile == true) { // in all dop,count_dn_writefile only add 1 // count_dop_writefile + 1 if writefile is true in current dop if (count_dop_writefile++ == 0) { count_dn_writefile++; } file_num = instr->sorthashinfo.hash_FileNum; max_file_num = rtl::max(max_file_num, file_num); min_file_num = rtl::min(min_file_num, file_num); if (min_file_num == MIN_FILE_NUM) { min_file_num = file_num; } } } } } if (count_dn_writefile < datanode_size) { min_file_num = 0; } if (is_execute && max_file_num > 0) { if (es->format != EXPLAIN_FORMAT_TEXT) { ExplainPropertyLong("Max File Num", max_file_num, es); ExplainPropertyLong("Min File Num", min_file_num, es); } else { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Max File Num: %d Min File Num: %d\n", max_file_num, min_file_num); if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_PRETTY && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Max File Num: %d Min File Num: %d\n", max_file_num, min_file_num); } } } } } } /* * Show information on hashed_setop. */ static void show_setop_info(SetOpState* setopstate, ExplainState* es) { PlanState* planstate = (PlanState*)setopstate; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && es->from_dn) { show_detail_filenum_info(planstate, es, "Hash Setop Detail"); } else if (es->analyze) { if (!es->from_dn) { int filenum = 0; int expand_times = 0; if (IsA(setopstate, VecSetOpState)) { setOpTbl* vechashSetopTbl = (setOpTbl*)((VecSetOpState*)setopstate)->vecSetOpInfo; if (vechashSetopTbl != NULL) filenum = vechashSetopTbl->getFileNum(); expand_times = setopstate->ps.instrument->sorthashinfo.hashtable_expand_times; } else { SetopWriteFileControl* TempFileControl = (SetopWriteFileControl*)setopstate->TempFileControl; if (TempFileControl != NULL) filenum = TempFileControl->filenum; } if (filenum > 0 || expand_times > 0) { if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) show_datanode_filenum_info(es, filenum, 0, expand_times, es->str); else { if (es->planinfo->m_runtimeinfo) es->planinfo->m_runtimeinfo->put(-1, -1, HASH_FILENUM, filenum); if (es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); show_datanode_filenum_info(es, filenum, 0, expand_times, es->planinfo->m_staticInfo->info_str); } } } } } } /* * @Description: Show hashagg build and probe time info * @in planstate: PlanState node.+ * @in es: Explain state. */ static void show_detail_execute_info(const PlanState* planstate, ExplainState* es) { Instrumentation* instr = NULL; int datanode_size = 0; int i = 0; int j = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (u_sess->instr_cxt.global_instr) datanode_size = u_sess->instr_cxt.global_instr->getInstruNodeNum(); if (!es->detail) return; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_runtimeinfo) { for (i = 0; i < datanode_size; i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { double build_time = instr->sorthashinfo.hashbuild_time; double agg_time = instr->sorthashinfo.hashagg_time; if (build_time > 0.0 || agg_time > 0.0) { es->planinfo->m_staticInfo->set_plan_name<false, true>(); es->planinfo->m_staticInfo->set_datanode_name(node_name, j, dop); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Hashagg Build time: %.3f, Aggregation time: %.3f\n", build_time * 1000.0, agg_time * 1000.0); } } } } } } /* * Show information on hash agg. */ static void show_hashAgg_info(AggState* hashaggstate, ExplainState* es) { PlanState* planstate = (PlanState*)hashaggstate; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && es->from_dn) { show_detail_filenum_info(planstate, es, "Hash Aggregate Detail"); show_detail_execute_info(planstate, es); } else if (es->analyze) { if (!es->from_dn) { int filenum = 0; int expand_times = 0; double hashagg_build_time = 0.0; double hashagg_agg_time = 0.0; if (IsA(hashaggstate, VecAggState)) { VecAgg* plan = (VecAgg*)(hashaggstate->ss.ps.plan); if (plan->is_sonichash) { SonicHashAgg* vechashAggTbl = (SonicHashAgg*)((VecAggState*)hashaggstate)->aggRun; if (vechashAggTbl != NULL) filenum = vechashAggTbl->getFileNum(); } else { HashAggRunner* vechashAggTbl = (HashAggRunner*)((VecAggState*)hashaggstate)->aggRun; if (vechashAggTbl != NULL) filenum = vechashAggTbl->getFileNum(); } expand_times = hashaggstate->ss.ps.instrument->sorthashinfo.hashtable_expand_times; hashagg_build_time = hashaggstate->ss.ps.instrument->sorthashinfo.hashbuild_time; hashagg_agg_time = hashaggstate->ss.ps.instrument->sorthashinfo.hashagg_time; } else { AggWriteFileControl* TempFileControl = (AggWriteFileControl*)hashaggstate->aggTempFileControl; if (TempFileControl != NULL) filenum = TempFileControl->filenum; } if (filenum > 0 || expand_times > 0) { if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) { show_datanode_filenum_info(es, filenum, planstate->instrument->sorthashinfo.hash_spillNum, planstate->instrument->sorthashinfo.hashtable_expand_times, es->str); } else { if (es->planinfo->m_runtimeinfo != NULL) es->planinfo->m_runtimeinfo->put(-1, -1, HASH_FILENUM, filenum); if (es->planinfo->m_staticInfo != NULL) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); show_datanode_filenum_info(es, filenum, planstate->instrument->sorthashinfo.hash_spillNum, planstate->instrument->sorthashinfo.hashtable_expand_times, es->planinfo->m_staticInfo->info_str); } } } if (hashagg_build_time > 0.0 || hashagg_agg_time > 0.0) { /* Here must be pretty format */ if (es->planinfo && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Hashagg Build time: %.3f, Aggregation time: %.3f\n", hashagg_build_time * 1000.0, hashagg_agg_time * 1000.0); } } } } } /* * Show information on hash buckets/batches. */ static void show_hash_info(HashState* hashstate, ExplainState* es) { HashJoinTable hashtable; PlanState* planstate = NULL; planstate = (PlanState*)hashstate; int nbatch; int nbatch_original; int nbuckets; long spacePeakKb = 0; int max_nbatch = -1; int min_nbatch = INT_MAX; int max_nbatch_original = -1; int min_nbatch_original = INT_MAX; int max_nbuckets = -1; int min_nbuckets = INT_MAX; long max_spacePeakKb = -1; long min_spacePeakKb = LONG_MAX; bool is_execute = false; AssertEreport(IsA(hashstate, HashState), MOD_EXECUTOR, "unexpect hashstate type"); hashtable = hashstate->hashtable; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->detail) { ExplainOpenGroup("Hash Detail", "Hash Detail", false, es); for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif append_datanode_name(es, node_name, 1, 0); spacePeakKb = (instr->sorthashinfo.spacePeak + 1023) / 1024; nbatch = instr->sorthashinfo.nbatch; nbatch_original = instr->sorthashinfo.nbatch_original; nbuckets = instr->sorthashinfo.nbuckets; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo && es->planinfo->m_staticInfo && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(i, 0, HASH_BATCH, nbatch); es->planinfo->m_runtimeinfo->put(i, 0, HASH_BATCH_ORIGNAL, nbatch_original); es->planinfo->m_runtimeinfo->put(i, 0, HASH_BUCKET, nbuckets); es->planinfo->m_runtimeinfo->put(i, 0, HASH_SPACE, spacePeakKb); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); show_datanode_hash_info<false>(es, nbatch, nbatch_original, nbuckets, spacePeakKb); } show_datanode_hash_info<true>(es, nbatch, nbatch_original, nbuckets, spacePeakKb); ExplainCloseGroup("Plan", NULL, true, es); } ExplainCloseGroup("Hash Detail", "Hash Detail", false, es); } else { if (u_sess->instr_cxt.global_instr->getInstruNodeNum() > 0) { SortHashInfo* psi = NULL; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr != NULL) { if (!is_execute) is_execute = true; psi = &instr->sorthashinfo; spacePeakKb = (instr->sorthashinfo.spacePeak + 1023) / 1024; max_nbatch = rtl::max(max_nbatch, psi->nbatch); min_nbatch = rtl::min(min_nbatch, psi->nbatch); max_nbatch_original = rtl::max(max_nbatch_original, psi->nbatch_original); min_nbatch_original = rtl::min(min_nbatch_original, psi->nbatch_original); max_nbuckets = rtl::max(max_nbuckets, psi->nbuckets); min_nbuckets = rtl::min(min_nbuckets, psi->nbuckets); max_spacePeakKb = rtl::max(max_spacePeakKb, spacePeakKb); min_spacePeakKb = rtl::min(min_spacePeakKb, spacePeakKb); } } if (is_execute) { AssertEreport(max_nbatch != -1 && min_nbatch != INT_MAX && max_nbatch_original != -1 && min_nbatch_original != INT_MAX && max_nbuckets != -1 && min_nbuckets != INT_MAX && max_spacePeakKb != -1 && min_spacePeakKb != LONG_MAX, MOD_EXECUTOR, "unexpect min/max value"); if (es->format != EXPLAIN_FORMAT_TEXT) { ExplainPropertyLong("Max Hash Buckets", max_nbuckets, es); ExplainPropertyLong("Min Hash Buckets", min_nbuckets, es); ExplainPropertyLong("Max Hash Batches", max_nbatch, es); ExplainPropertyLong("Min Hash Batches", min_nbatch, es); ExplainPropertyLong("Max Original Hash Batches", max_nbatch_original, es); ExplainPropertyLong("Min Original Hash Batches", min_nbatch_original, es); ExplainPropertyLong("Max Peak Memory Usage", max_spacePeakKb, es); ExplainPropertyLong("min Peak Memory Usage", min_spacePeakKb, es); } else if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) { if (max_nbatch_original != max_nbatch) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Max Buckets: %d Max Batches: %d (max originally %d) Max Memory Usage: %ldkB\n", max_nbuckets, max_nbatch, max_nbatch_original, max_spacePeakKb); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Min Buckets: %d Min Batches: %d (min originally %d) Min Memory Usage: %ldkB\n", min_nbuckets, min_nbatch, min_nbatch_original, min_spacePeakKb); } else { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Max Buckets: %d Max Batches: %d Max Memory Usage: %ldkB\n", max_nbuckets, max_nbatch, max_spacePeakKb); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Min Buckets: %d Min Batches: %d Min Memory Usage: %ldkB\n", min_nbuckets, min_nbatch, min_spacePeakKb); } } else if (es->planinfo->m_staticInfo) { if (max_nbatch_original != max_nbatch) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Max Buckets: %d Max Batches: %d (max originally %d) Max Memory Usage: %ldkB\n", max_nbuckets, max_nbatch, max_nbatch_original, max_spacePeakKb); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Min Buckets: %d Min Batches: %d (min originally %d) Min Memory Usage: %ldkB\n", min_nbuckets, min_nbatch, min_nbatch_original, min_spacePeakKb); } else { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Max Buckets: %d Max Batches: %d Max Memory Usage: %ldkB\n", max_nbuckets, max_nbatch, max_spacePeakKb); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Min Buckets: %d Min Batches: %d Min Memory Usage: %ldkB\n", min_nbuckets, min_nbatch, min_spacePeakKb); } } } } } } else if (hashstate->ps.instrument) { SortHashInfo hashinfo = hashstate->ps.instrument->sorthashinfo; spacePeakKb = (hashinfo.spacePeak + 1023) / 1024; nbatch = hashinfo.nbatch; nbatch_original = hashinfo.nbatch_original; nbuckets = hashinfo.nbuckets; /* wlm_statistics_plan_max_digit: this variable is used to judge, isn't it a active sql */ if (es->wlm_statistics_plan_max_digit == NULL) { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoSpaces(es->str, es->indent * 2); show_datanode_hash_info<false>(es, nbatch, nbatch_original, nbuckets, spacePeakKb); } } } inline static void show_buffers_info( StringInfo infostr, bool has_shared, bool has_local, bool has_temp, const BufferUsage* usage) { appendStringInfoString(infostr, "(Buffers:"); if (has_shared) { appendStringInfoString(infostr, " shared"); if (usage->shared_blks_hit > 0) appendStringInfo(infostr, " hit=%ld", usage->shared_blks_hit); if (usage->shared_blks_read > 0) appendStringInfo(infostr, " read=%ld", usage->shared_blks_read); if (usage->shared_blks_dirtied > 0) appendStringInfo(infostr, " dirtied=%ld", usage->shared_blks_dirtied); if (usage->shared_blks_written > 0) appendStringInfo(infostr, " written=%ld", usage->shared_blks_written); } if (has_local) { appendStringInfoString(infostr, " local"); if (usage->local_blks_hit > 0) appendStringInfo(infostr, " hit=%ld", usage->local_blks_hit); if (usage->local_blks_read > 0) appendStringInfo(infostr, " read=%ld", usage->local_blks_read); if (usage->local_blks_dirtied > 0) appendStringInfo(infostr, " dirtied=%ld", usage->local_blks_dirtied); if (usage->local_blks_written > 0) appendStringInfo(infostr, " written=%ld", usage->local_blks_written); if (has_temp) appendStringInfoChar(infostr, ','); } if (has_temp) { appendStringInfoString(infostr, " temp"); if (usage->temp_blks_read > 0) appendStringInfo(infostr, " read=%ld", usage->temp_blks_read); if (usage->temp_blks_written > 0) appendStringInfo(infostr, " written=%ld", usage->temp_blks_written); } appendStringInfoString(infostr, ")\n"); } static void put_buffers(ExplainState* es, const BufferUsage* usage, int nodeIdx, int smpIdx) { bool has_timing = false; es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, SHARED_BLK_HIT, Int64GetDatum(usage->shared_blks_hit)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, SHARED_BLK_READ, Int64GetDatum(usage->shared_blks_read)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, SHARED_BLK_DIRTIED, Int64GetDatum(usage->shared_blks_dirtied)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, SHARED_BLK_WRITTEN, Int64GetDatum(usage->shared_blks_written)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, LOCAL_BLK_HIT, Int64GetDatum(usage->local_blks_hit)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, LOCAL_BLK_READ, Int64GetDatum(usage->local_blks_read)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, LOCAL_BLK_DIRTIED, Int64GetDatum(usage->local_blks_dirtied)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, LOCAL_BLK_WRITTEN, Int64GetDatum(usage->local_blks_written)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, TEMP_BLK_READ, Int64GetDatum(usage->temp_blks_read)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, TEMP_BLK_WRITTEN, Int64GetDatum(usage->temp_blks_written)); has_timing = (!INSTR_TIME_IS_ZERO(usage->blk_read_time) || !INSTR_TIME_IS_ZERO(usage->blk_write_time)); if (has_timing) { double blk_time; if (!INSTR_TIME_IS_ZERO(usage->blk_read_time)) { blk_time = INSTR_TIME_GET_MILLISEC(usage->blk_read_time); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, BLK_READ_TIME, Float8GetDatum(blk_time)); } if (!INSTR_TIME_IS_ZERO(usage->blk_write_time)) { blk_time = INSTR_TIME_GET_MILLISEC(usage->blk_write_time); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, BLK_WRITE_TIME, Float8GetDatum(blk_time)); } } } static void show_datanode_vecjoin_info( ExplainState* es, StringInfo instr, int64 file_number, int spillNum, long spillSize, long space, bool is_writefile) { if (is_writefile == false) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(instr, "Memory Used : %ldkB\n", space); } else { ExplainPropertyLong("Memory Used", space, es); } } else { if (es->format == EXPLAIN_FORMAT_TEXT) { if (spillNum > 0) appendStringInfo(instr, "Temp File Num: %ld, Spill Time: %d, Total Written Disk IO: %ldKB\n", file_number, spillNum, spillSize); else appendStringInfo(instr, "Temp File Num: %ld, Total Written Disk IO: %ldKB\n", file_number, spillSize); } else { ExplainPropertyLong("Temp File Num", file_number, es); ExplainPropertyLong("Spill Time", spillNum, es); ExplainPropertyLong("Total Written Disk IO", spillSize, es); } } } static void show_datanode_sonicjoin_info( ExplainState* es, StringInfo instr, int partNum, int spillNum, long space, bool is_writefile) { if (is_writefile == false) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(instr, "Memory Used : %ldkB\n", space); } else { ExplainPropertyLong("Memory Used", space, es); } } else { if (es->format == EXPLAIN_FORMAT_TEXT) { if (spillNum > 0) appendStringInfo(instr, "Partition Num: %d, Spill Times: %d\n", partNum, spillNum); else appendStringInfo(instr, "Partition Num: %d\n", partNum); } else { ExplainPropertyLong("Partition Num", partNum, es); ExplainPropertyLong("Spill Times", spillNum, es); } } } static void show_datanode_sonicjoin_detail_info(ExplainState* es, StringInfo instr, bool buildside, int partNum, int fileNum, long spillSize, long spillSizeMin, long spillSizeMax) { const char* side = buildside ? "Inner Partition" : "Outer Partition"; if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(instr, "%s Spill Num: %d, " "Temp File Num: %d, " "Written Disk IO: %ldKB [%ldKB %ldKB]\n", side, partNum, fileNum, spillSize, spillSizeMin, spillSizeMax); } else { ExplainOpenGroup(side, side, false, es); ExplainPropertyLong("Spill Num", partNum, es); ExplainPropertyLong("Temp File Num", fileNum, es); ExplainPropertyLong("Total Written Disk IO", spillSize, es); ExplainPropertyLong("Min Partition Written Disk IO", spillSizeMin, es); ExplainPropertyLong("Max Partition Written Disk IO", spillSizeMax, es); ExplainCloseGroup(side, side, false, es); } } static void show_vechash_info(VecHashJoinState* hashstate, ExplainState* es) { PlanState* planstate = (PlanState*)hashstate; int64 max_file_num = 0; int min_file_num = MIN_FILE_NUM; bool is_execute = false; long spaceUsed, spillSize; int64 file_num; long max_spaceused = 0; long min_spaceused = u_sess->attr.attr_memory.work_mem; bool is_writefile = false; int spillNum; int partNum, innerPartNum, outerPartNum; int innerFileNum, outerFileNum; long spillInnerSize, spillInnerSizeMax, spillInnerSizeMin; long spillOuterSize, spillOuterSizeMax, spillOuterSizeMin; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->detail) { ExplainOpenGroup("VecHashJoin Detail", "VecHashJoin Detail", false, es); for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) continue; is_writefile = instr->sorthashinfo.hash_writefile; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif spaceUsed = (instr->sorthashinfo.spaceUsed + 1023) / 1024; spillSize = (instr->sorthashinfo.spill_size + 1023) / 1024; file_num = instr->sorthashinfo.hash_FileNum; spillNum = instr->sorthashinfo.hash_spillNum; partNum = instr->sorthashinfo.hash_partNum; innerPartNum = instr->sorthashinfo.spill_innerPartNum; outerPartNum = instr->sorthashinfo.spill_outerPartNum; innerFileNum = instr->sorthashinfo.hash_innerFileNum; outerFileNum = instr->sorthashinfo.hash_outerFileNum; spillInnerSize = (instr->sorthashinfo.spill_innerSize + 1023) / 1024; spillInnerSizeMax = (instr->sorthashinfo.spill_innerSizePartMax + 1023) / 1024; spillInnerSizeMin = (instr->sorthashinfo.spill_innerSizePartMin + 1023) / 1024; spillOuterSize = (instr->sorthashinfo.spill_outerSize + 1023) / 1024; spillOuterSizeMax = (instr->sorthashinfo.spill_outerSizePartMax + 1023) / 1024; spillOuterSizeMin = (instr->sorthashinfo.spill_outerSizePartMin + 1023) / 1024; double build_time = instr->sorthashinfo.hashbuild_time; double probe_time = instr->sorthashinfo.hashagg_time; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL && es->planinfo->m_staticInfo != NULL) { if (is_writefile) es->planinfo->m_runtimeinfo->put(i, 0, HASH_FILENUM, file_num); else es->planinfo->m_runtimeinfo->put(i, 0, HASH_SPACE, spaceUsed); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); if (((HashJoin*)planstate->plan)->isSonicHash) { show_datanode_sonicjoin_info( es, es->planinfo->m_staticInfo->info_str, partNum, spillNum, spaceUsed, is_writefile); if (is_writefile) { es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); show_datanode_sonicjoin_detail_info(es, es->planinfo->m_staticInfo->info_str, true, innerPartNum, innerFileNum, spillInnerSize, spillInnerSizeMin, spillInnerSizeMax); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s ", node_name); show_datanode_sonicjoin_detail_info(es, es->planinfo->m_staticInfo->info_str, false, outerPartNum, outerFileNum, spillOuterSize, spillOuterSizeMin, spillOuterSizeMax); } } else show_datanode_vecjoin_info(es, es->planinfo->m_staticInfo->info_str, file_num, spillNum, spillSize, spaceUsed, is_writefile); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "%s", node_name); appendStringInfo(es->planinfo->m_staticInfo->info_str, " Hashjoin Build time: %.3f, Probe time: %.3f\n", build_time * 1000.0, probe_time * 1000.0); } else { append_datanode_name(es, node_name, 1, 0); if (((HashJoin*)planstate->plan)->isSonicHash) { show_datanode_sonicjoin_info(es, es->str, partNum, spillNum, spaceUsed, is_writefile); if (is_writefile) { append_datanode_name(es, node_name, 1, 0); show_datanode_sonicjoin_detail_info(es, es->str, true, innerPartNum, innerFileNum, spillInnerSize, spillInnerSizeMin, spillInnerSizeMax); append_datanode_name(es, node_name, 1, 0); show_datanode_sonicjoin_detail_info(es, es->str, false, outerPartNum, outerFileNum, spillOuterSize, spillOuterSizeMin, spillOuterSizeMax); } } else { show_datanode_vecjoin_info(es, es->str, file_num, spillNum, spillSize, spaceUsed, is_writefile); } } ExplainCloseGroup("Plan", NULL, true, es); } ExplainCloseGroup("VecHashJoin Detail", "VecHashJoin Detail", false, es); } else { if (u_sess->instr_cxt.global_instr->getInstruNodeNum() > 0) { file_num = 0; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr != NULL) { if (!is_execute) is_execute = true; file_num = instr->sorthashinfo.hash_FileNum; spaceUsed = (instr->sorthashinfo.spaceUsed + 1023) / 1024; max_file_num = rtl::max(max_file_num, file_num); min_file_num = rtl::min((int64)min_file_num, file_num); if (min_file_num == MIN_FILE_NUM) min_file_num = file_num; max_spaceused = rtl::max(max_spaceused, spaceUsed); min_spaceused = rtl::min(min_spaceused, spaceUsed); } } if (is_execute) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) { /* * Here, we adjust output information and here our output will be used * major showing whether writing to disk occurs or not. * 1, min_file_num and max_file_num are both equal to 0. * It means All DNs' work mem can hold themselves hash table in memory, * then we only print out memory usage related information. * 2, min_spaceused and max_spaceused are both equal to 0. * It means all the DNs have written out the hash table content to disk, * then we only print out min and max file num information. * 3, If file num and spaceused are not both equal to 0. * It means some DNs' work mem are not enough to hold themselves hash table in memory, * here we print out only file num related informaiton to show the writing out operation * occurs. 4, All above four variables equal to 0, this situation could occur when the hash * table is empty. */ if (min_file_num != 0 || max_file_num != 0) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Max File Num: %ld\n", max_file_num); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Min File Num: %d\n", min_file_num); } else { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Max Memory Used : %ldkB\n", max_spaceused); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Min Memory Used : %ldkB\n", min_spaceused); } } else if (es->planinfo->m_staticInfo) { if (min_file_num != 0 || max_file_num != 0) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Max File Num: %ld\n", max_file_num); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Min File Num: %d\n", min_file_num); } else { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Max Memory Used : %ldkB\n", max_spaceused); es->planinfo->m_staticInfo->set_plan_name<false, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "Min Memory Used : %ldkB\n", min_spaceused); } } } else { ExplainPropertyLong("Min Memory Used", min_spaceused, es); ExplainPropertyLong("Max Memory Used", max_spaceused, es); ExplainPropertyLong("Min File Num", min_file_num, es); ExplainPropertyLong("Max File Num", max_file_num, es); } } } } } } static void show_recursive_info(RecursiveUnionState* rustate, ExplainState* es) { PlanState* planstate = (PlanState*)rustate; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->detail && t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL) { ExplainOpenGroup("RecursiveUnion Detail", "RecursiveUnion Detail", false, es); /* Find iteration number */ int niters = 0; bool has_reach_limit = false; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) { continue; } niters = Max(niters, instr->recursiveInfo.niters); if (instr->recursiveInfo.has_reach_limit) has_reach_limit = true; } if (niters == 0) { ExplainCloseGroup("RecursiveUnion Detail", "RecursiveUnion Detail", false, es); return; } appendStringInfo( es->planinfo->m_recursiveInfo->info_str, "%3d --Recursive Union\n", planstate->plan->plan_node_id); appendStringInfoSpaces(es->planinfo->m_recursiveInfo->info_str, 8); appendStringInfo(es->planinfo->m_recursiveInfo->info_str, "Iteration times: %d\n", niters - 1); /* report non-recursive part */ appendStringInfoSpaces(es->planinfo->m_recursiveInfo->info_str, 8); appendStringInfo(es->planinfo->m_recursiveInfo->info_str, "Iteration[0] (Step 0 None-Recursive)\n"); for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) { continue; } appendStringInfoSpaces(es->planinfo->m_recursiveInfo->info_str, 16); appendStringInfo(es->planinfo->m_recursiveInfo->info_str, "%s return tuples: %lu\n", node_name, instr->recursiveInfo.iter_ntuples[0]); } /* report recursive part */ for (int iteridx = 1; iteridx < niters; iteridx++) { appendStringInfoSpaces(es->planinfo->m_recursiveInfo->info_str, 8); appendStringInfo(es->planinfo->m_recursiveInfo->info_str, "Iteration[%d] (Step %d Recursive[%d])%s\n", iteridx, iteridx, iteridx, (iteridx == niters - 1 && !has_reach_limit) ? " --- finish" : ""); for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) { continue; } #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif appendStringInfoSpaces(es->planinfo->m_recursiveInfo->info_str, 16); appendStringInfo(es->planinfo->m_recursiveInfo->info_str, "%s return tuples: %lu\n", node_name, instr->recursiveInfo.iter_ntuples[iteridx]); } } ExplainCloseGroup("RecursiveUnion Detail", "RecursiveUnion Detail", false, es); } } } static void show_datanode_buffers(ExplainState* es, PlanState* planstate) { Instrumentation* instr = NULL; int nodeNum = u_sess->instr_cxt.global_instr->getInstruNodeNum(); int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; int i = 0; int j = 0; if (es->detail) { ExplainOpenGroup("Buffers In Detail", "Buffers In Detail", false, es); for (i = 0; i < nodeNum; i++) { for (j = 0; j < dop; j++) { ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr == NULL) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif append_datanode_name(es, node_name, dop, j); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); es->planinfo->m_datanodeInfo->set_datanode_name(node_name, j, dop); } show_buffers(es, es->str, instr, true, i, j, node_name); ExplainCloseGroup("Plan", NULL, true, es); } } ExplainCloseGroup("Buffers In Detail", "Buffers In Detail", false, es); } else { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_IOInfo) show_analyze_buffers(es, planstate, es->planinfo->m_IOInfo->info_str, nodeNum); else show_analyze_buffers(es, planstate, es->str, nodeNum); } } static void show_analyze_buffers(ExplainState* es, const PlanState* planstate, StringInfo infostr, int nodeNum) { bool has_shared = false; bool has_local = false; bool has_temp = false; bool has_timing = false; long shared_blks_hit_max = -1; long shared_blks_hit_min = LONG_MAX; long shared_blks_read_max = -1; long shared_blks_read_min = LONG_MAX; long shared_blks_dirtied_max = -1; long shared_blks_dirtied_min = LONG_MAX; long shared_blks_written_max = -1; long shared_blks_written_min = LONG_MAX; long local_blks_hit_max = -1; long local_blks_hit_min = LONG_MAX; long local_blks_read_max = -1; long local_blks_read_min = LONG_MAX; long local_blks_dirtied_max = -1; long local_blks_dirtied_min = LONG_MAX; long local_blks_written_max = -1; long local_blks_written_min = LONG_MAX; long temp_blks_read_max = -1; long temp_blks_read_min = LONG_MAX; long temp_blks_written_max = -1; long temp_blks_written_min = LONG_MAX; instr_time blk_read_time_max, blk_read_time_min; instr_time blk_write_time_max, blk_write_time_min; bool is_execute = false; Instrumentation* instr = NULL; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; INSTR_TIME_SET_ZERO(blk_read_time_max); INSTR_TIME_SET_ZERO(blk_write_time_max); INSTR_TIME_INITIAL_MIN(blk_read_time_min); INSTR_TIME_INITIAL_MIN(blk_write_time_min); if (nodeNum > 0) { for (int i = 0; i < nodeNum; i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; for (int j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { BufferUsage* pbu = &instr->bufusage; if (!is_execute) { is_execute = true; } if (!has_shared) has_shared = (pbu->shared_blks_hit > 0 || pbu->shared_blks_read > 0 || pbu->shared_blks_dirtied > 0 || pbu->shared_blks_written > 0); shared_blks_read_max = rtl::max(shared_blks_read_max, pbu->shared_blks_read); shared_blks_read_min = rtl::min(shared_blks_read_min, pbu->shared_blks_read); shared_blks_hit_max = rtl::max(shared_blks_hit_max, pbu->shared_blks_hit); shared_blks_hit_min = rtl::min(shared_blks_hit_min, pbu->shared_blks_hit); shared_blks_dirtied_max = rtl::max(shared_blks_dirtied_max, pbu->shared_blks_dirtied); shared_blks_dirtied_min = rtl::min(shared_blks_dirtied_min, pbu->shared_blks_dirtied); shared_blks_written_max = rtl::max(shared_blks_written_max, pbu->shared_blks_written); shared_blks_written_min = rtl::min(shared_blks_written_min, pbu->shared_blks_written); if (!has_local) has_local = (pbu->local_blks_hit > 0 || pbu->local_blks_read > 0 || pbu->local_blks_dirtied > 0 || pbu->local_blks_written > 0); local_blks_read_max = rtl::max(local_blks_read_max, pbu->local_blks_read); local_blks_read_min = rtl::min(local_blks_read_min, pbu->local_blks_read); local_blks_hit_max = rtl::max(local_blks_hit_max, pbu->local_blks_hit); local_blks_hit_min = rtl::min(local_blks_hit_min, pbu->local_blks_hit); local_blks_dirtied_max = rtl::max(local_blks_dirtied_max, pbu->local_blks_dirtied); local_blks_dirtied_min = rtl::min(local_blks_dirtied_min, pbu->local_blks_dirtied); local_blks_written_max = rtl::max(local_blks_written_max, pbu->local_blks_written); local_blks_written_min = rtl::min(local_blks_written_min, pbu->local_blks_written); if (!has_temp) has_temp = (pbu->temp_blks_read > 0 || pbu->temp_blks_written > 0); temp_blks_read_max = rtl::max(temp_blks_read_max, pbu->temp_blks_read); temp_blks_read_min = rtl::min(temp_blks_read_min, pbu->temp_blks_read); temp_blks_written_max = rtl::max(temp_blks_written_max, pbu->temp_blks_written); temp_blks_written_min = rtl::min(temp_blks_written_min, pbu->temp_blks_written); if (!has_timing) has_timing = (!INSTR_TIME_IS_ZERO(pbu->blk_read_time) || !INSTR_TIME_IS_ZERO(pbu->blk_write_time)); if (!INSTR_TIME_IS_BIGGER(blk_read_time_max, pbu->blk_read_time)) blk_read_time_max = pbu->blk_read_time; if (INSTR_TIME_IS_BIGGER(blk_read_time_min, pbu->blk_read_time)) blk_read_time_min = pbu->blk_read_time; if (!INSTR_TIME_IS_BIGGER(blk_write_time_max, pbu->blk_write_time)) blk_write_time_max = pbu->blk_write_time; if (INSTR_TIME_IS_BIGGER(blk_write_time_min, pbu->blk_write_time)) blk_write_time_min = pbu->blk_write_time; } } } if (is_execute) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (has_shared || has_local || has_temp) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_IOInfo) { es->planinfo->m_IOInfo->set_plan_name<true, true>(); appendStringInfoString(es->planinfo->m_IOInfo->info_str, "Buffers:"); } else { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoString(es->str, "Buffers:"); } if (has_shared) { appendStringInfoString(infostr, " shared"); if (shared_blks_hit_max > 0) appendStringInfo(infostr, " max hit=%ld", shared_blks_hit_max); if (shared_blks_hit_min > 0 && shared_blks_hit_min < LONG_MAX) appendStringInfo(infostr, " min hit=%ld", shared_blks_hit_min); if (shared_blks_read_max > 0) appendStringInfo(infostr, " max read=%ld", shared_blks_read_max); if (shared_blks_read_min > 0 && shared_blks_read_min < LONG_MAX) appendStringInfo(infostr, " min read=%ld", shared_blks_read_min); if (shared_blks_dirtied_max > 0) appendStringInfo(infostr, " max dirtied=%ld", shared_blks_dirtied_max); if (shared_blks_dirtied_min > 0 && shared_blks_dirtied_min < LONG_MAX) appendStringInfo(infostr, " min dirtied=%ld", shared_blks_dirtied_min); if (shared_blks_written_max > 0) appendStringInfo(infostr, " max written=%ld", shared_blks_written_max); if (shared_blks_written_min > 0 && shared_blks_written_min < LONG_MAX) appendStringInfo(infostr, " min written=%ld", shared_blks_written_min); if (has_local || has_temp) appendStringInfoChar(infostr, ','); } if (has_local) { appendStringInfoString(infostr, " local"); if (local_blks_hit_max > 0) appendStringInfo(infostr, " max hit=%ld", local_blks_hit_max); if (local_blks_hit_min > 0 && local_blks_hit_min < LONG_MAX) appendStringInfo(infostr, " min hit=%ld", local_blks_hit_min); if (local_blks_read_max > 0) appendStringInfo(infostr, " max read=%ld", local_blks_read_max); if (local_blks_read_min > 0 && local_blks_read_min < LONG_MAX) appendStringInfo(infostr, " min read=%ld", local_blks_read_min); if (local_blks_dirtied_max > 0) appendStringInfo(infostr, " max dirtied=%ld", local_blks_dirtied_max); if (local_blks_dirtied_min > 0 && local_blks_dirtied_min < LONG_MAX) appendStringInfo(infostr, " min dirtied=%ld", local_blks_dirtied_min); if (local_blks_written_max > 0) appendStringInfo(infostr, " max written=%ld", local_blks_written_max); if (local_blks_written_min > 0 && local_blks_written_min < LONG_MAX) appendStringInfo(infostr, " min written=%ld", local_blks_written_min); if (has_temp) appendStringInfoChar(infostr, ','); } if (has_temp) { appendStringInfoString(infostr, " temp"); if (temp_blks_read_max > 0) appendStringInfo(infostr, " max read=%ld", temp_blks_read_max); if (temp_blks_read_min > 0 && temp_blks_read_min < LONG_MAX) appendStringInfo(infostr, " min read=%ld", temp_blks_read_min); if (temp_blks_written_max > 0) appendStringInfo(infostr, " max written=%ld", temp_blks_written_max); if (temp_blks_written_min > 0 && temp_blks_written_min < LONG_MAX) appendStringInfo(infostr, " min written=%ld", temp_blks_written_min); } appendStringInfoChar(infostr, '\n'); } /* As above, show only positive counter values. */ if (has_timing) { appendStringInfoSpaces(infostr, es->indent * 2); appendStringInfoString(infostr, "I/O Timings:"); if (!INSTR_TIME_IS_ZERO(blk_read_time_max)) appendStringInfo(infostr, " max read=%.3f", INSTR_TIME_GET_MILLISEC(blk_read_time_max)); if (!INSTR_TIME_IS_ZERO(blk_read_time_min) && !INSTR_TIME_IS_INTMAX(blk_read_time_min)) appendStringInfo(infostr, " min read=%.3f", INSTR_TIME_GET_MILLISEC(blk_read_time_min)); if (!INSTR_TIME_IS_ZERO(blk_write_time_max)) appendStringInfo(infostr, " max write=%.3f", INSTR_TIME_GET_MILLISEC(blk_write_time_max)); if (!INSTR_TIME_IS_ZERO(blk_write_time_min) && !INSTR_TIME_IS_INTMAX(blk_write_time_min)) appendStringInfo(infostr, " min write=%.3f", INSTR_TIME_GET_MILLISEC(blk_write_time_min)); appendStringInfoChar(infostr, '\n'); } } else { ExplainPropertyLong("Max Shared Hit Blocks", shared_blks_hit_max, es); ExplainPropertyLong("Min Shared Hit Blocks", shared_blks_hit_min, es); ExplainPropertyLong("Max Shared Read Blocks", shared_blks_read_max, es); ExplainPropertyLong("Min Shared Read Blocks", shared_blks_read_min, es); ExplainPropertyLong("Max Shared Dirtied Blocks", shared_blks_dirtied_max, es); ExplainPropertyLong("Min Shared Dirtied Blocks", shared_blks_dirtied_min, es); ExplainPropertyLong("Max Shared Written Blocks", shared_blks_written_max, es); ExplainPropertyLong("Max Shared Written Blocks", shared_blks_written_min, es); ExplainPropertyLong("Max Local Hit Blocks", local_blks_hit_max, es); ExplainPropertyLong("Min Local Hit Blocks", local_blks_hit_min, es); ExplainPropertyLong("Max Local Read Blocks", local_blks_read_max, es); ExplainPropertyLong("Min Local Read Blocks", local_blks_read_min, es); ExplainPropertyLong("Max Local Dirtied Blocks", local_blks_dirtied_max, es); ExplainPropertyLong("Min Local Dirtied Blocks", local_blks_dirtied_min, es); ExplainPropertyLong("Max Local Written Blocks", local_blks_written_max, es); ExplainPropertyLong("Min Local Written Blocks", local_blks_written_min, es); ExplainPropertyLong("Max Temp Read Blocks", temp_blks_read_max, es); ExplainPropertyLong("Min Temp Read Blocks", temp_blks_read_min, es); ExplainPropertyLong("Max Temp Written Blocks", temp_blks_written_max, es); ExplainPropertyLong("Min Temp Written Blocks", temp_blks_written_min, es); ExplainPropertyFloat("Max IO Read Time", INSTR_TIME_GET_MILLISEC(blk_read_time_max), 3, es); ExplainPropertyFloat("Min IO Read Time", INSTR_TIME_GET_MILLISEC(blk_read_time_min), 3, es); ExplainPropertyFloat("Max IO Write Time", INSTR_TIME_GET_MILLISEC(blk_write_time_max), 3, es); ExplainPropertyFloat("Min IO Write Time", INSTR_TIME_GET_MILLISEC(blk_write_time_min), 3, es); } } } } static void show_buffers(ExplainState* es, StringInfo infostr, const Instrumentation* instrument, bool is_datanode, int nodeIdx, int smpIdx, const char* node_name) { const BufferUsage* usage = &instrument->bufusage; if (es->format == EXPLAIN_FORMAT_TEXT) { bool has_shared = (usage->shared_blks_hit > 0 || usage->shared_blks_read > 0 || usage->shared_blks_dirtied > 0 || usage->shared_blks_written > 0); bool has_local = (usage->local_blks_hit > 0 || usage->local_blks_read > 0 || usage->local_blks_dirtied > 0 || usage->local_blks_written > 0); bool has_temp = (usage->temp_blks_read > 0 || usage->temp_blks_written > 0); bool has_timing = (!INSTR_TIME_IS_ZERO(usage->blk_read_time) || !INSTR_TIME_IS_ZERO(usage->blk_write_time)); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->detail) { put_buffers(es, usage, nodeIdx, smpIdx); if (node_name == NULL) appendStringInfoSpaces(es->planinfo->m_datanodeInfo->info_str, 8); if (has_shared || has_temp) { show_buffers_info(es->planinfo->m_datanodeInfo->info_str, has_shared, has_local, has_temp, usage); } else { appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "(Buffers: 0)\n"); } return; } /* Show only positive counter values. */ if (has_shared || has_local || has_temp) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_IOInfo) { es->planinfo->m_IOInfo->set_plan_name<true, true>(); appendStringInfoString(es->planinfo->m_IOInfo->info_str, "Buffers:"); } if (!is_datanode) appendStringInfoSpaces(es->str, es->indent * 2); show_buffers_info(infostr, has_shared, has_local, has_temp, usage); } else if (is_datanode) { appendStringInfo(infostr, get_execute_mode(es, nodeIdx) ? "(Buffers: 0)\n" : "(Buffers: unknown)\n"); } /* As above, show only positive counter values. */ if (has_timing) { appendStringInfoSpaces(infostr, es->indent * 2); appendStringInfoString(infostr, "I/O Timings:"); if (!INSTR_TIME_IS_ZERO(usage->blk_read_time)) appendStringInfo(infostr, " read=%.3f", INSTR_TIME_GET_MILLISEC(usage->blk_read_time)); if (!INSTR_TIME_IS_ZERO(usage->blk_write_time)) appendStringInfo(infostr, " write=%.3f", INSTR_TIME_GET_MILLISEC(usage->blk_write_time)); appendStringInfoChar(infostr, '\n'); } } else { ExplainPropertyLong("Shared Hit Blocks", usage->shared_blks_hit, es); ExplainPropertyLong("Shared Read Blocks", usage->shared_blks_read, es); ExplainPropertyLong("Shared Dirtied Blocks", usage->shared_blks_dirtied, es); ExplainPropertyLong("Shared Written Blocks", usage->shared_blks_written, es); ExplainPropertyLong("Local Hit Blocks", usage->local_blks_hit, es); ExplainPropertyLong("Local Read Blocks", usage->local_blks_read, es); ExplainPropertyLong("Local Dirtied Blocks", usage->local_blks_dirtied, es); ExplainPropertyLong("Local Written Blocks", usage->local_blks_written, es); ExplainPropertyLong("Temp Read Blocks", usage->temp_blks_read, es); ExplainPropertyLong("Temp Written Blocks", usage->temp_blks_written, es); ExplainPropertyFloat("IO Read Time", INSTR_TIME_GET_MILLISEC(usage->blk_read_time), 3, es); ExplainPropertyFloat("IO Write Time", INSTR_TIME_GET_MILLISEC(usage->blk_write_time), 3, es); } } /* * Calculate the child plan's exclusive cpu cycles/inclusive cpu cycles/ * left child processed rows/right child processedrows. */ template <bool datanode> static void show_child_cpu_cycles_and_rows(PlanState* planstate, int idx, int smpIdx, double* outerCycles, double* innerCycles, uint64* outterRows, uint64* innerRows) { PlanState* outerChild = NULL; PlanState* innerChild = NULL; Instrumentation* tmp_instr = NULL; Plan* plan = planstate->plan; int outer_smp_idx = 0; int inner_smp_idx = 0; switch (nodeTag(plan)) { case T_ModifyTable: case T_VecModifyTable: CalCPUMemberNode<datanode>(((ModifyTable*)plan)->plans, ((ModifyTableState*)planstate)->mt_plans, idx, smpIdx, outerCycles, outterRows); break; case T_VecAppend: case T_Append: CalCPUMemberNode<datanode>(((Append*)plan)->appendplans, ((AppendState*)planstate)->appendplans, idx, smpIdx, outerCycles, outterRows); break; case T_MergeAppend: CalCPUMemberNode<datanode>(((MergeAppend*)plan)->mergeplans, ((MergeAppendState*)planstate)->mergeplans, idx, smpIdx, outerCycles, outterRows); break; case T_BitmapAnd: CalCPUMemberNode<datanode>(((BitmapAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, idx, smpIdx, outerCycles, outterRows); break; case T_BitmapOr: CalCPUMemberNode<datanode>(((BitmapOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, idx, smpIdx, outerCycles, outterRows); break; case T_CStoreIndexAnd: CalCPUMemberNode<datanode>(((CStoreIndexAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, idx, smpIdx, outerCycles, outterRows); break; case T_CStoreIndexOr: CalCPUMemberNode<datanode>(((CStoreIndexOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, idx, smpIdx, outerCycles, outterRows); break; case T_SubqueryScan: case T_VecSubqueryScan: /* Left Tree Only */ outerChild = ((SubqueryScanState*)planstate)->subplan; if (outerChild != NULL) { if (datanode) { outer_smp_idx = outerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, outerChild->plan->plan_node_id, outer_smp_idx); } else tmp_instr = planstate->instrument; if (tmp_instr != NULL) { *outerCycles = tmp_instr->cpuusage.m_cycles; *outterRows = tmp_instr->ntuples; } } break; case T_RemoteQuery: case T_VecRemoteQuery: case T_Stream: case T_VecStream: /* Treat them as scan nodes, because their left trees are in different thread. */ break; default: /* Left Tree */ outerChild = outerPlanState(planstate); if (outerChild != NULL) { if (datanode) { outer_smp_idx = outerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, outerChild->plan->plan_node_id, outer_smp_idx); } else tmp_instr = outerChild->instrument; if (tmp_instr != NULL) { *outerCycles = tmp_instr->cpuusage.m_cycles; *outterRows = tmp_instr->ntuples; } } /* Right Tree */ innerChild = innerPlanState(planstate); if (innerChild != NULL) { if (datanode) { inner_smp_idx = innerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, innerChild->plan->plan_node_id, inner_smp_idx); } else tmp_instr = innerChild->instrument; if (tmp_instr != NULL) { *innerCycles = tmp_instr->cpuusage.m_cycles; *innerRows = tmp_instr->ntuples; } } break; } } /* * Calculate the cpu cycles of a ModifyTable, Append, MergeAppend, * BitmapAnd, or BitmapOr node. * * The ancestors list should already contain the total cpu cycles * of the operator. */ template <bool datanode> static void CalCPUMemberNode(const List* plans, PlanState** planstates, int idx, int smpIdx, double* Cycles, uint64* proRows) { int nplans = list_length(plans); int k; Instrumentation* tmp_instr = NULL; for (k = 0; k < nplans; k++) { if (datanode) { int child_smp_idx = planstates[k]->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot(idx, planstates[k]->plan->plan_node_id, child_smp_idx); } else { tmp_instr = planstates[k]->instrument; } if (tmp_instr != NULL) { *Cycles += tmp_instr->cpuusage.m_cycles; *proRows += tmp_instr->ntuples; } } } template <bool datanode> static void CalOperTimeMemberNode(const List* plans, PlanState** planstates, int idx, int smpIdx, double* oper_time) { int nplans = list_length(plans); int k; Instrumentation* tmp_instr = NULL; for (k = 0; k < nplans; k++) { if (datanode) { int child_smp_idx = planstates[k]->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot(idx, planstates[k]->plan->plan_node_id, child_smp_idx); } else { tmp_instr = planstates[k]->instrument; } if (tmp_instr != NULL && tmp_instr->nloops > 0) { *oper_time += 1000.0 * tmp_instr->total; } } } /* * Calculate the child node's run time */ template <bool datanode> static void show_child_time( PlanState* planstate, int idx, int smpIdx, double* inner_time, double* outer_time, ExplainState* es) { PlanState* outerChild = NULL; PlanState* innerChild = NULL; Instrumentation* tmp_instr = NULL; Plan* plan = planstate->plan; int outer_smp_idx = 0; int inner_smp_idx = 0; switch (nodeTag(plan)) { case T_ModifyTable: case T_VecModifyTable: CalOperTimeMemberNode<datanode>( ((ModifyTable*)plan)->plans, ((ModifyTableState*)planstate)->mt_plans, idx, smpIdx, outer_time); break; case T_VecAppend: case T_Append: CalOperTimeMemberNode<datanode>( ((Append*)plan)->appendplans, ((AppendState*)planstate)->appendplans, idx, smpIdx, outer_time); break; case T_MergeAppend: CalOperTimeMemberNode<datanode>( ((MergeAppend*)plan)->mergeplans, ((MergeAppendState*)planstate)->mergeplans, idx, smpIdx, outer_time); break; case T_BitmapAnd: CalOperTimeMemberNode<datanode>( ((BitmapAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, idx, smpIdx, outer_time); break; case T_BitmapOr: CalOperTimeMemberNode<datanode>( ((BitmapOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, idx, smpIdx, outer_time); break; case T_CStoreIndexAnd: CalOperTimeMemberNode<datanode>(((CStoreIndexAnd*)plan)->bitmapplans, ((BitmapAndState*)planstate)->bitmapplans, idx, smpIdx, outer_time); break; case T_CStoreIndexOr: CalOperTimeMemberNode<datanode>( ((CStoreIndexOr*)plan)->bitmapplans, ((BitmapOrState*)planstate)->bitmapplans, idx, smpIdx, outer_time); break; case T_SubqueryScan: case T_VecSubqueryScan: /* Left Tree Only */ outerChild = ((SubqueryScanState*)planstate)->subplan; if (outerChild != NULL) { if (datanode) { outer_smp_idx = outerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, outerChild->plan->plan_node_id, outer_smp_idx); } else tmp_instr = planstate->instrument; if (tmp_instr != NULL && tmp_instr->nloops > 0) *outer_time = 1000.0 * tmp_instr->total; } break; case T_RemoteQuery: case T_VecRemoteQuery: // remove poll time *outer_time = planstate->instrument->network_perfdata.total_poll_time; if (es->planinfo->m_query_summary) { double deserialze_time = planstate->instrument->network_perfdata.total_deserialize_time; appendStringInfo( es->planinfo->m_query_summary->info_str, "Remote query poll time: %.3f ms", *outer_time); appendStringInfo( es->planinfo->m_query_summary->info_str, ", Deserialze time: %.3f ms\n", deserialze_time); } break; case T_Stream: case T_VecStream: /* remove poll time */ if (datanode) { tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot(idx, planstate->plan->plan_node_id, smpIdx); if (tmp_instr != NULL) *outer_time = tmp_instr->network_perfdata.total_poll_time; } break; default: /* Left Tree */ outerChild = outerPlanState(planstate); if (outerChild != NULL) { if (datanode) { outer_smp_idx = outerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, outerChild->plan->plan_node_id, outer_smp_idx); } else { InstrEndLoop(outerChild->instrument); tmp_instr = outerChild->instrument; } if (tmp_instr != NULL && tmp_instr->nloops > 0) { *outer_time = 1000.0 * tmp_instr->total; } } /* Right Tree */ innerChild = innerPlanState(planstate); if (innerChild != NULL) { if (datanode) { inner_smp_idx = innerChild->plan->parallel_enabled ? smpIdx : 0; tmp_instr = u_sess->instr_cxt.global_instr->getInstrSlot( idx, innerChild->plan->plan_node_id, inner_smp_idx); } else { InstrEndLoop(innerChild->instrument); tmp_instr = innerChild->instrument; } if (tmp_instr != NULL && tmp_instr->nloops > 0) { *inner_time = 1000.0 * tmp_instr->total; } } break; } } inline static void show_cpu_info(StringInfo infostr, double incCycles, double exCycles, uint64 proRows) { appendStringInfoString(infostr, "(CPU:"); appendStringInfo(infostr, " ex c/r=%.0f,", proRows != 0 ? (long)(exCycles / proRows) : 0.0); appendStringInfo(infostr, " ex row=%lu,", proRows); appendStringInfo(infostr, " ex cyc=%.0f,", exCycles); appendStringInfo(infostr, " inc cyc=%.0f)", incCycles); appendStringInfoChar(infostr, '\n'); } static void show_detail_cpu(ExplainState* es, PlanState* planstate) { Instrumentation* instr = NULL; uint64 proRows = 0; double incCycles = 0.0; double exCycles = 0.0; double incCycles_max = -1; double outerCycles = 0.0; double innerCycles = 0.0; uint64 outterRows = 0; uint64 innerRows = 0; double incCycles_min = HUGE_VAL - 1; double exCycles_max = -1; double exCycles_min = HUGE_VAL - 1; double proRows_max = -1; double proRows_min = HUGE_VAL - 1; bool is_null = false; int i = 0; int j = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (u_sess->instr_cxt.global_instr->getInstruNodeNum() > 0) { for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); outerCycles = 0.0; innerCycles = 0.0; if (instr != NULL && instr->nloops > 0) { if (!is_null) is_null = true; show_child_cpu_cycles_and_rows<true>( planstate, i, j, &outerCycles, &innerCycles, &outterRows, &innerRows); incCycles = instr->cpuusage.m_cycles; exCycles = incCycles - outerCycles - innerCycles; proRows = (long)(instr->ntuples / instr->nloops); proRows = (proRows != 0 ? (long)(exCycles / proRows) : 0.0); incCycles_max = rtl::max(incCycles_max, incCycles); incCycles_min = rtl::min(incCycles_min, incCycles); exCycles_max = rtl::max(exCycles_max, exCycles); exCycles_min = rtl::min(exCycles_min, exCycles); proRows_max = rtl::max((uint64)proRows_max, proRows); proRows_min = rtl::min((uint64)proRows_min, proRows); } } } } if (is_null) { AssertEreport( (incCycles_max != -1 || exCycles_max != -1 || proRows_max != -1) && (incCycles_min != HUGE_VAL - 1 || exCycles_min != HUGE_VAL - 1 || proRows_min != HUGE_VAL - 1), MOD_EXECUTOR, "unexpect min/max value"); if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoString(es->str, "CPU:"); appendStringInfo(es->str, " max_ex c/r=%.0f,", proRows_max); appendStringInfo(es->str, " max_ex cyc=%.0f,", exCycles_max); appendStringInfo(es->str, " max_inc cyc=%.0f", incCycles_max); appendStringInfoChar(es->str, '\n'); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoString(es->str, " "); appendStringInfo(es->str, " min_ex c/r=%.0f,", proRows_min); appendStringInfo(es->str, " min_ex cyc=%.0f,", exCycles_min); appendStringInfo(es->str, " min_inc cyc=%.0f", incCycles_min); appendStringInfoChar(es->str, '\n'); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_IOInfo) { es->planinfo->m_IOInfo->set_plan_name<true, true>(); appendStringInfoString(es->planinfo->m_IOInfo->info_str, "CPU:"); appendStringInfo(es->planinfo->m_IOInfo->info_str, " max_ex c/r=%.0f,", proRows_max); appendStringInfo(es->planinfo->m_IOInfo->info_str, " max_ex cyc=%.0f,", exCycles_max); appendStringInfo(es->planinfo->m_IOInfo->info_str, " max_inc cyc=%.0f", incCycles_max); appendStringInfoChar(es->planinfo->m_IOInfo->info_str, '\n'); appendStringInfoSpaces(es->planinfo->m_IOInfo->info_str, 11); appendStringInfo(es->planinfo->m_IOInfo->info_str, " min_ex c/r=%.0f,", proRows_min); appendStringInfo(es->planinfo->m_IOInfo->info_str, " min_ex cyc=%.0f,", exCycles_min); appendStringInfo(es->planinfo->m_IOInfo->info_str, " min_inc cyc=%.0f", incCycles_min); appendStringInfoChar(es->planinfo->m_IOInfo->info_str, '\n'); } } else { ExplainPropertyLong("Exclusive Max Cycles Per Row", (long)proRows_max, es); ExplainPropertyLong("Exclusive Max Cycles", (long)exCycles_max, es); ExplainPropertyLong("Inclusive Max Cycles", (long)incCycles_max, es); ExplainPropertyLong("Exclusive Min Cycles Per Row", (long)proRows_min, es); ExplainPropertyLong("Exclusive Min Cycles", (long)exCycles_min, es); ExplainPropertyLong("Inclusive Min Cycles", (long)incCycles_min, es); } } else if (es->analyze) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(es->str, "(CPU: never executed)"); appendStringInfoChar(es->str, '\n'); } else { ExplainPropertyFloat("Actual Exclusive Per Row", 0.0, 0, es); ExplainPropertyFloat("Actual Exclusive Cycles", 0.0, 0, es); ExplainPropertyFloat("Actual Inclusive Cycles", 0.0, 0, es); } } } // To determine whether the current operator is actually executed. static bool get_execute_mode(const ExplainState* es, int idx) { int id; if (!es->from_dn || !es->sql_execute) return true; id = idx < 0 ? 0 : idx; if (u_sess->instr_cxt.global_instr) { ThreadInstrumentation* threadinstr = #ifdef ENABLE_MULTIPLE_NODES u_sess->instr_cxt.global_instr->getThreadInstrumentationCN(id); #else u_sess->instr_cxt.global_instr->getThreadInstrumentationDN(1, 0); #endif if (threadinstr == NULL) return true; bool execute = threadinstr->m_instrArray[0].instr.isExecute; if (!execute) { if (es->datanodeinfo.all_datanodes) return false; for (int i = 0; i < es->datanodeinfo.len_nodelist; i++) { if (id == es->datanodeinfo.node_index[i]) return false; } } } return true; } static void show_cpu(ExplainState* es, const Instrumentation* instrument, double innerCycles, double outerCycles, int nodeIdx, int smpIdx, uint64 proRows) { if (instrument != NULL && instrument->nloops > 0) { double incCycles = 0.0; double exCycles = 0.0; int64 ex_cyc_rows; incCycles = instrument->cpuusage.m_cycles; exCycles = incCycles - outerCycles - innerCycles; ex_cyc_rows = proRows != 0 ? (long)(exCycles / proRows) : 0; if (es->planinfo && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, EX_CYC, Int64GetDatum(exCycles)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, INC_CYC, Int64GetDatum(incCycles)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, EX_CYC_PER_ROWS, Int64GetDatum(ex_cyc_rows)); show_cpu_info(es->planinfo->m_datanodeInfo->info_str, incCycles, exCycles, proRows); return; } if (es->format == EXPLAIN_FORMAT_TEXT) { show_cpu_info(es->str, incCycles, exCycles, proRows); } else { ExplainPropertyLong("Exclusive Cycles Per Row", proRows != 0 ? (long)(exCycles / proRows) : 0, es); ExplainPropertyLong("Exclusive Cycles", (long)exCycles, es); ExplainPropertyLong("Inclusive Cycles", (long)incCycles, es); } } else if (es->analyze) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (get_execute_mode(es, nodeIdx)) appendStringInfo(es->str, "(CPU: never executed)"); else appendStringInfo(es->str, "(CPU: unknown)"); appendStringInfoChar(es->str, '\n'); } else { ExplainPropertyFloat("Actual Exclusive Cycles Per Row", 0.0, 0, es); ExplainPropertyFloat("Actual Exclusive Cycles", 0.0, 0, es); ExplainPropertyFloat("Actual Inclusive Cycles", 0.0, 0, es); } } } /* * @Description: show memory info about each plan node in pretty mode * @in es - the explain state info * @in node_name - datanode name * @in instrument - instrument info * @in smpIdx - current smp idx * @in dop - query dop * @out - void */ static void show_pretty_memory(ExplainState* es, char* node_name, const Instrumentation* instrument, int smpIdx, int dop) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); if (node_name != NULL) { es->planinfo->m_staticInfo->set_datanode_name(node_name, smpIdx, dop); } if (instrument->memoryinfo.peakOpMemory <= 1024) appendStringInfo( es->planinfo->m_staticInfo->info_str, "Peak Memory: %ldBYTE", instrument->memoryinfo.peakOpMemory); else appendStringInfo( es->planinfo->m_staticInfo->info_str, "Peak Memory: %ldKB", instrument->memoryinfo.peakOpMemory / 1024); if (instrument->memoryinfo.peakControlMemory > 0) { if (instrument->memoryinfo.peakControlMemory <= 1024) appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Control Memory: %ldBYTE", instrument->memoryinfo.peakControlMemory); else appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Control Memory: %ldKB", instrument->memoryinfo.peakControlMemory / 1024); } /* show operator memory information */ if (instrument->memoryinfo.operatorMemory > 0) { if (instrument->memoryinfo.operatorMemory <= 1024) appendStringInfo( es->planinfo->m_staticInfo->info_str, ", Estimate Memory: %dKB", instrument->memoryinfo.operatorMemory); else appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Estimate Memory: %dMB", instrument->memoryinfo.operatorMemory / 1024); } if (instrument->spreadNum > 0) { appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Auto spread times: %d", instrument->spreadNum); } if (instrument->sysBusy) { appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Early spilled"); } if (instrument->width > 0) { appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Width: %d", instrument->width); } appendStringInfo(es->planinfo->m_staticInfo->info_str, "\n"); } static void show_pretty_time( ExplainState* es, Instrumentation* instrument, char* node_name, int nodeIdx, int smpIdx, int dop, bool executed) { if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double startup_sec = 1000.0 * instrument->startup; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; if (es->format == EXPLAIN_FORMAT_TEXT) { char str[100] = "\0"; int rc = sprintf_s(str, sizeof(str), "%.3f", total_sec); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_ROWS, Float8GetDatum(rows)); if (es->timing) { es->planinfo->m_planInfo->put(ACTUAL_TIME, PointerGetDatum(cstring_to_text(str))); } char memoryPeakSize[100] = "\0"; if (instrument->memoryinfo.peakOpMemory <= 1024) rc = sprintf_s(memoryPeakSize, sizeof(memoryPeakSize), "%ldBYTE", instrument->memoryinfo.peakOpMemory); else rc = sprintf_s( memoryPeakSize, sizeof(memoryPeakSize), "%ldKB", instrument->memoryinfo.peakOpMemory / 1024); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_WIDTH, PointerGetDatum(cstring_to_text(""))); es->planinfo->m_planInfo->put(ACTUAL_MEMORY, PointerGetDatum(cstring_to_text(memoryPeakSize))); if (es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, START_TIME, Float8GetDatum(startup_sec)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, TOTAL_TIME, Float8GetDatum(total_sec)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, PLAN_ROWS, rows); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, PLAN_LOOPS, nloops); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, PEAK_OP_MEMORY, instrument->memoryinfo.peakOpMemory); if (node_name != NULL) es->planinfo->m_runtimeinfo->put( nodeIdx, smpIdx, NODE_NAME, PointerGetDatum(cstring_to_text(node_name))); else es->planinfo->m_runtimeinfo->put( nodeIdx, smpIdx, NODE_NAME, PointerGetDatum(cstring_to_text("coordinator"))); } if (es->detail) { es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); if (node_name != NULL) { es->planinfo->m_datanodeInfo->set_datanode_name(node_name, smpIdx, dop); } if (instrument->need_timer) appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "(actual time=%.3f..%.3f rows=%.0f loops=%.0f)\n", startup_sec, total_sec, rows, nloops); else appendStringInfo( es->planinfo->m_datanodeInfo->info_str, "(actual rows=%.0f loops=%.0f)\n", rows, nloops); show_pretty_memory(es, node_name, instrument, smpIdx, dop); } } } else if (es->planinfo->m_runtimeinfo) { if (node_name != NULL) { if (executed) es->planinfo->m_runtimeinfo->put( nodeIdx, smpIdx, NODE_NAME, PointerGetDatum(cstring_to_text(node_name))); } else es->planinfo->m_runtimeinfo->put( nodeIdx, smpIdx, NODE_NAME, PointerGetDatum(cstring_to_text("coordinator"))); } } template <bool isdetail> static StreamTime* get_instrument( int j, int smpid, Track* trackpoint, int plan_node_id, StringInfo str, bool* first_time) { StreamTime* instrument = NULL; int dop = u_sess->instr_cxt.global_instr->getNodeDop(plan_node_id); #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(j, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif instrument = &trackpoint->track_time; if (*first_time) { if (trackpoint->node_id > 0) appendStringInfo(str, "Plan Node id: %d Track name: %s\n", trackpoint->node_id, trackdesc[trackpoint->registerTrackId].trackName); /* nodeid == -1 means generaltrack */ if (trackpoint->node_id == -1) appendStringInfo(str, "Segment Id: %d Track name: %s\n", plan_node_id, trackdesc[trackpoint->registerTrackId].trackName); *first_time = false; } if (isdetail) { appendStringInfoSpaces(str, 6); if (dop == 1) appendStringInfo(str, " %s", node_name); else appendStringInfo(str, "%s[worker %d]", node_name, smpid); } StreamEndLoop(instrument); return instrument; } /* show general track info which is not related to plannodeid */ static void show_track_time_without_plannodeid(ExplainState* es) { StringInfo str; StreamTime* instrument = NULL; int i = 0; int j = 0; bool has_perf = CPUMon::m_has_perf; AccumCounters accumcount; const char* track_name = NULL; bool first_time = true; int track_Id; if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) str = es->str; else str = es->planinfo->m_profileInfo->info_str; int m_num_streams = u_sess->instr_cxt.global_instr->getInstruThreadNum(); int m_query_dop = u_sess->instr_cxt.global_instr->get_query_dop(); int threadlen = u_sess->instr_cxt.global_instr->get_threadInstrArrayLen(); int m_gather_count = u_sess->instr_cxt.global_instr->get_gather_num(); ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(0); int generaltracknum = threadinstr->get_generaltracknum(); // show generaltrack info for (i = 0; i < generaltracknum; i++) { track_Id = i; track_name = trackdesc[track_Id].trackName; ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(0); Track* generaltrack = &threadinstr_tmp->m_generalTrackArray[i]; int segmentid = threadinstr_tmp->getSegmentId(); if (segmentid > 0 && generaltrack->registerTrackId == track_Id && IS_NULL(generaltrack->active)) { instrument = &generaltrack->track_time; StreamEndLoop(instrument); if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; appendStringInfo(str, "Segment Id: %d Track name: %s\n", segmentid, track_name); #ifdef ENABLE_MULTIPLE_NODES char* nodename = PGXCNodeGetNodeNameFromId(0, PGXC_NODE_COORDINATOR); #else char* nodename = g_instance.exec_cxt.nodeName; #endif appendStringInfoSpaces(str, 6); appendStringInfo(str, " %s:", nodename); if (instrument->need_timer) { if (!has_perf) { appendStringInfo(str, " (time=%.3f total_calls=%.0f loops=%.0f)", total_sec, rows, nloops); } else { accumcount = generaltrack->accumCounters; appendStringInfo(str, " (time=%.3f Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", total_sec, accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } else { if (!has_perf) { appendStringInfo(str, " (total_calls=%.0f loops=%.0f)", rows, nloops); } else { accumcount = generaltrack->accumCounters; appendStringInfo(str, " (Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } appendStringInfoChar(str, '\n'); } } for (j = 1; j < threadlen; j++) { ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(j); if (threadinstr_tmp != NULL) { Track* generaltrack_tmp = &threadinstr_tmp->m_generalTrackArray[i]; int segmentid_tmp = threadinstr_tmp->getSegmentId(); if (segmentid_tmp > 0 && generaltrack_tmp->registerTrackId == track_Id && IS_NULL(generaltrack_tmp->active)) { int nodeidx = (j - 1) / ((m_gather_count + m_num_streams) * m_query_dop); int smpid = (j - 1) % m_query_dop; instrument = get_instrument<true>(nodeidx, smpid, generaltrack_tmp, segmentid_tmp, str, &first_time); if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; if (instrument->need_timer) { if (!has_perf) { appendStringInfo( str, " (time=%.3f total_calls=%.0f loops=%.0f)", total_sec, rows, nloops); } else { accumcount = generaltrack_tmp->accumCounters; appendStringInfo(str, " (time=%.3f Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", total_sec, accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } else { if (!has_perf) { appendStringInfo(str, " (total_calls=%.0f loops=%.0f)", rows, nloops); } else { accumcount = generaltrack_tmp->accumCounters; appendStringInfo(str, " (Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } appendStringInfoChar(str, '\n'); } } } } } } /* show all track info */ static void show_track_time_info(ExplainState* es) { StreamTime* instrument = NULL; Track* trackArray = NULL; bool first_time = true; int i = 0; int j = 0; StringInfo str; int plan_node_id; AccumCounters accumcount; const char* track_name = NULL; bool has_perf = CPUMon::m_has_perf; int track_Id; if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) { str = es->str; appendStringInfo(str, "*********User Define Profiling*********\n"); } else str = es->planinfo->m_profileInfo->info_str; int m_num_streams = u_sess->instr_cxt.global_instr->getInstruThreadNum(); int m_query_dop = u_sess->instr_cxt.global_instr->get_query_dop(); int plannodes_num = u_sess->instr_cxt.global_instr->getInstruPlanSize() + 1; int m_gather_count = u_sess->instr_cxt.global_instr->get_gather_num(); ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(0); int tracknum = threadinstr->get_tracknum(); int generaltracknum = threadinstr->get_generaltracknum(); int dn_start_node_id = u_sess->instr_cxt.global_instr->get_startnodeid(); if (es->detail) { /* show generaltrackinfo */ show_track_time_without_plannodeid(es); /* show nodetrack info */ for (i = 0; i < tracknum; i++) { track_Id = i + generaltracknum; track_name = trackdesc[track_Id].trackName; /* print the track info on coordinator */ ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(0); int trackArrayLen = threadinstr_tmp->get_instrArrayLen(); for (j = 0; j < trackArrayLen; j++) { trackArray = threadinstr_tmp->m_instrArray[j].tracks; Track* trackpoint = &trackArray[i]; plan_node_id = trackpoint->node_id; if (plan_node_id > 0 && trackpoint->registerTrackId == track_Id && IS_NULL(trackpoint->active)) { instrument = &trackpoint->track_time; StreamEndLoop(instrument); if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; appendStringInfo(str, "Plan Node id: %d Track name: %s\n", plan_node_id, track_name); #ifdef ENABLE_MULTIPLE_NODES char* nodename = PGXCNodeGetNodeNameFromId(0, PGXC_NODE_COORDINATOR); #else char* nodename = g_instance.exec_cxt.nodeName; #endif appendStringInfoSpaces(str, 6); appendStringInfo(str, " %s:", nodename); if (instrument->need_timer) { if (!has_perf) { appendStringInfo( str, " (time=%.3f total_calls=%.0f loops=%.0f)", total_sec, rows, nloops); } else { accumcount = trackpoint->accumCounters; appendStringInfo(str, " (time=%.3f Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", total_sec, accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } else { if (!has_perf) { appendStringInfo(str, " (total_calls=%.0f loops=%.0f)", rows, nloops); } else { accumcount = trackpoint->accumCounters; appendStringInfo(str, " (Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } appendStringInfoChar(str, '\n'); } } } } /* print DN track info */ for (j = dn_start_node_id; j < plannodes_num; j++) { for (i = 0; i < tracknum; i++) { first_time = true; track_Id = i + generaltracknum; for (int k = 0; k < u_sess->instr_cxt.global_instr->getInstruNodeNum(); k++) { for (int m = 0; m < u_sess->instr_cxt.global_instr->getNodeDop(j); m++) { ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->getThreadInstrumentation(k, j, m); if (threadinstr_tmp != NULL) { trackArray = threadinstr_tmp->get_tracks(j); /* when m_instrArrayMap is initialized but nodeinstr is not executed, it should return. */ if (trackArray == NULL) continue; Track* trackpoint = &trackArray[i]; plan_node_id = trackpoint->node_id; if (plan_node_id > 0 && trackpoint->registerTrackId == track_Id && IS_NULL(trackpoint->active)) { instrument = get_instrument<true>(k, m, trackpoint, plan_node_id, str, &first_time); if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; if (instrument->need_timer) { if (!has_perf) appendStringInfo(str, " (time=%.3f total_calls=%.0f loops=%.0f)", total_sec, rows, nloops); else { accumcount = trackpoint->accumCounters; appendStringInfo(str, " (time=%.3f Instructions=%ld cpu cycles=%ld total_calls=%.0f " "loops=%.0f)", total_sec, accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } else { if (!has_perf) appendStringInfo(str, " (total_calls=%.0f loops=%.0f)", rows, nloops); else { accumcount = trackpoint->accumCounters; appendStringInfo(str, " (Instructions=%ld cpu cycles=%ld total_calls=%.0f loops=%.0f)", accumcount.accumCounters[1], accumcount.accumCounters[0], rows, nloops); } } appendStringInfoChar(str, '\n'); } } } } } } } } else { /* show generaltrack */ for (i = 0; i < generaltracknum; i++) { double total_sec_max = -1; double total_sec_min = HUGE_VAL - 1; bool need_timer = false; double max_calls = -1; double min_calls = HUGE_VAL - 1; double total_sec; double calls = 0; int64 max_stru = -1; int64 min_stru = LONG_MAX; int64 max_cpu_cycle = -1; int64 min_cpu_cycle = LONG_MAX; /* generaltrack */ track_Id = i; first_time = true; for (j = 0; j < u_sess->instr_cxt.global_instr->get_threadInstrArrayLen(); j++) { ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->get_cnthreadinstrumentation(j); if (threadinstr_tmp != NULL) { Track* trackpoint = &threadinstr_tmp->m_generalTrackArray[i]; int segmentid = threadinstr_tmp->getSegmentId(); if (segmentid > 0 && trackpoint->registerTrackId == track_Id && IS_NULL(trackpoint->active)) { int nodeidx = (j == 0 ? 0 : (j - 1) / ((m_gather_count + m_num_streams) * m_query_dop)); int smpid = (j == 0 ? 0 : (j - 1) % m_query_dop); instrument = get_instrument<false>(nodeidx, smpid, trackpoint, segmentid, str, &first_time); if (instrument != NULL && instrument->nloops > 0) { if (!need_timer) need_timer = instrument->need_timer; calls = instrument->ntuples; max_calls = rtl::max(max_calls, calls); min_calls = rtl::min(min_calls, calls); total_sec = 1000.0 * instrument->total; total_sec_max = rtl::max(total_sec_max, total_sec); total_sec_min = rtl::min(total_sec_min, total_sec); } if (has_perf) { accumcount = trackpoint->accumCounters; max_stru = rtl::max(max_stru, accumcount.accumCounters[1]); min_stru = rtl::min(min_stru, accumcount.accumCounters[1]); max_cpu_cycle = rtl::max(max_cpu_cycle, accumcount.accumCounters[0]); min_cpu_cycle = rtl::min(min_cpu_cycle, accumcount.accumCounters[0]); } } } } if (need_timer && es->format == EXPLAIN_FORMAT_TEXT) { AssertEreport( total_sec_max != -1 && total_sec_min != HUGE_VAL - 1, MOD_EXECUTOR, "unexpect min/max value"); if (es->format == EXPLAIN_FORMAT_TEXT) { if (!has_perf) appendStringInfo(str, " (actual time=[%.3f, %.3f], calls=[%.0f, %.0f])\n", total_sec_min, total_sec_max, min_calls, max_calls); else appendStringInfo(str, " (actual time=[%.3f, %.3f], Instructions=[%ld, %ld], cpu cycles=[%ld, %ld], calls=[%.0f, " "%.0f])\n", total_sec_min, total_sec_max, min_stru, max_stru, min_cpu_cycle, max_cpu_cycle, min_calls, max_calls); } } } /* show nodetrack for every plannodeid */ for (j = 1; j < plannodes_num; j++) { for (i = 0; i < tracknum; i++) { double total_sec_max = -1; double total_sec_min = HUGE_VAL - 1; bool need_timer = false; double max_calls = -1; double min_calls = HUGE_VAL - 1; double total_sec; double calls = 0; int64 max_stru = -1; int64 min_stru = LONG_MAX; int64 max_cpu_cycle = -1; int64 min_cpu_cycle = LONG_MAX; first_time = true; track_Id = i + generaltracknum; for (int k = 0; k < u_sess->instr_cxt.global_instr->getInstruNodeNum(); k++) { for (int m = 0; m < u_sess->instr_cxt.global_instr->getNodeDop(j); m++) { ThreadInstrumentation* threadinstr_tmp = u_sess->instr_cxt.global_instr->getThreadInstrumentation(k, j, m); if (threadinstr_tmp != NULL) { Track* trackArray_tmp = threadinstr_tmp->get_tracks(j); /* when m_instrArrayMap is initialized but nodeinstr is not executed, it should return. */ if (trackArray_tmp == NULL) continue; Track* trackpoint = &trackArray_tmp[i]; plan_node_id = trackpoint->node_id; if (plan_node_id > 0 && trackpoint->registerTrackId == track_Id && IS_NULL(trackpoint->active)) { instrument = get_instrument<false>(k, m, trackpoint, plan_node_id, str, &first_time); if (instrument != NULL && instrument->nloops > 0) { if (!need_timer) need_timer = instrument->need_timer; calls = instrument->ntuples; max_calls = rtl::max(max_calls, calls); min_calls = rtl::min(min_calls, calls); total_sec = 1000.0 * instrument->total; total_sec_max = rtl::max(total_sec_max, total_sec); total_sec_min = rtl::min(total_sec_min, total_sec); } if (has_perf) { accumcount = trackpoint->accumCounters; max_stru = rtl::max(max_stru, accumcount.accumCounters[1]); min_stru = rtl::min(min_stru, accumcount.accumCounters[1]); max_cpu_cycle = rtl::max(max_cpu_cycle, accumcount.accumCounters[0]); min_cpu_cycle = rtl::min(min_cpu_cycle, accumcount.accumCounters[0]); } } } } } if (need_timer && es->format == EXPLAIN_FORMAT_TEXT) { AssertEreport( total_sec_max != -1 && total_sec_min != HUGE_VAL - 1, MOD_EXECUTOR, "unexpect min/max value"); if (es->format == EXPLAIN_FORMAT_TEXT) { if (!has_perf) appendStringInfo(str, " (actual time=[%.3f, %.3f], calls=[%.0f, %.0f])\n", total_sec_min, total_sec_max, min_calls, max_calls); else appendStringInfo(str, " (actual time=[%.3f, %.3f], Instructions=[%ld, %ld], cpu cycles=[%ld, %ld], " "calls=[%.0f, %.0f])\n", total_sec_min, total_sec_max, min_stru, max_stru, min_cpu_cycle, max_cpu_cycle, min_calls, max_calls); } } } } } } int get_track_time(ExplainState* es, PlanState* planstate, bool show_track, bool show_buffer, bool show_dummygroup, bool show_indexinfo, bool show_storageinfo) { if (show_track) show_track_time_info(es); if (show_buffer) { append_datanode_name(es, "datanode1", 2, 1); show_analyze_buffers(es, planstate, es->str, 1); show_buffers(es, es->str, u_sess->instr_cxt.global_instr->getInstrSlot(0, 1), false, 0, 0, NULL); } if (show_dummygroup) { ExplainDummyGroup("ut", "test", es); ExplainDummyGroup("ut", NULL, es); } if (show_indexinfo) { ExplainIndexScanDetails(0, BackwardScanDirection, es); ExplainIndexScanDetails(0, NoMovementScanDirection, es); ExplainIndexScanDetails(0, ForwardScanDirection, es); } if (show_storageinfo) { append_datanode_name(es, "datanode1", 2, 1); show_detail_storage_info_json(u_sess->instr_cxt.global_instr->getInstrSlot(0, 1), es->str, es); } return 0; } template <bool is_detail> static void show_time(ExplainState* es, const Instrumentation* instrument, int idx) { if (instrument != NULL && instrument->nloops > 0) { double nloops = instrument->nloops; const double startup_sec = 1000.0 * instrument->startup; const double total_sec = 1000.0 * instrument->total; double rows = instrument->ntuples; if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_detail == false) appendStringInfoSpaces(es->str, 1); if (instrument->need_timer) appendStringInfo( es->str, "(actual time=%.3f..%.3f rows=%.0f loops=%.0f)", startup_sec, total_sec, rows, nloops); else appendStringInfo(es->str, "(actual rows=%.0f loops=%.0f)", rows, nloops); } else { if (instrument->need_timer) { ExplainPropertyFloat("Actual Startup Time", startup_sec, 3, es); ExplainPropertyFloat("Actual Total Time", total_sec, 3, es); } ExplainPropertyFloat("Actual Rows", rows, 0, es); ExplainPropertyFloat("Actual Loops", nloops, 0, es); } } else if (es->analyze) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (is_detail == false) appendStringInfoSpaces(es->str, 1); if (get_execute_mode(es, idx)) appendStringInfo(es->str, "(Actual time: never executed)"); else appendStringInfo(es->str, "(Actual time: unknown)"); } else if (instrument != NULL && instrument->need_timer) { ExplainPropertyFloat("Actual Startup Time", 0.0, 3, es); ExplainPropertyFloat("Actual Total Time", 0.0, 3, es); } else { ExplainPropertyFloat("Actual Rows", 0.0, 0, es); ExplainPropertyFloat("Actual Loops", 0.0, 0, es); } } /* in text format, first line ends here */ if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoChar(es->str, '\n'); } /* * @Description: get max plan id from a plannedstmt * @in value -a integer * @out int - digit of value */ static int get_digit(int value) { AssertEreport(value >= 0, MOD_EXECUTOR, "unexpect input value"); int result = 0; while (value > 0) { result++; value /= 10; } if (result == 0) { return 1; } return result; } template <bool datanode> static void get_oper_time(ExplainState* es, PlanState* planstate, const Instrumentation* instr, int nodeIdx, int smpIdx) { double outer_total_time = 0.0; double inner_total_time = 0.0; double oper_time; show_child_time<datanode>(planstate, nodeIdx, smpIdx, &inner_total_time, &outer_total_time, es); if (instr != NULL && instr->nloops > 0) { oper_time = 1000.0 * instr->total; oper_time = oper_time - outer_total_time - inner_total_time; es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, OPER_TIME, Float8GetDatum(oper_time)); } } /* * @Description: show time info about stream send data to other thread * @in es - the explain state info * @in planstate - current planstate * @out - void */ static void show_stream_send_time(ExplainState* es, const PlanState* planstate) { bool isSend = false; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; /* stream send time will print only es->detail is true and t_thrd.explain_cxt.explain_perf_mode is not normal */ if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL || es->detail == false) return; /* is current plan node is the top node */ isSend = u_sess->instr_cxt.global_instr->IsSend(0, planstate->plan->plan_node_id, 0); if (isSend == false) { return; } for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (int j = 0; j < dop; j++) { Instrumentation* instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->stream_senddata.loops == true) { double send_time = instr->stream_senddata.total_send_time; double wait_quota_time = instr->stream_senddata.total_wait_quota_time; double os_send_time = instr->stream_senddata.total_os_send_time; double serialize_time = instr->stream_senddata.total_serialize_time; double copy_time = instr->stream_senddata.total_copy_time; es->planinfo->m_staticInfo->set_plan_name<false, true>(); es->planinfo->m_staticInfo->set_datanode_name(node_name, j, dop); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Stream Send time: %.3f", send_time); /* Only SCTP mode can collect quota and os send info. */ if (wait_quota_time > 0.0) appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Wait Quota time: %.3f", wait_quota_time); if (os_send_time > 0.0) appendStringInfo(es->planinfo->m_staticInfo->info_str, ", OS Kernel Send time: %.3f", os_send_time); /* Local Stream use data copy instead of serialize. */ if (copy_time > 0.0) appendStringInfo(es->planinfo->m_staticInfo->info_str, ", Data Copy time: %.3f", copy_time); else appendStringInfo( es->planinfo->m_staticInfo->info_str, "; Data Serialize time: %.3f", serialize_time); appendStringInfoChar(es->planinfo->m_staticInfo->info_str, '\n'); } } } } static void show_datanode_time(ExplainState* es, PlanState* planstate) { Instrumentation* instr = NULL; double total_sec_max = -1; double total_sec_min = HUGE_VAL - 1; double start_sec_max = -1; double start_sec_min = HUGE_VAL - 1; bool need_timer = false; double rows = 0; double total_sec; double start_sec; int64 peak_memory_min = (int64)(0x6FFFFFFFFFFFFFFF); int64 peak_memory_max = 0; int width_min = (int)(0x6FFFFFFF); int width_max = 0; bool executed = true; int i = 0; int j = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (es->detail) { if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoChar(es->str, '\n'); ExplainOpenGroup("Actual In Detail", "Actual In Detail", false, es); for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentationCN(i); #else char* node_name = g_instance.exec_cxt.nodeName; ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentationDN(1, 0); #endif if (threadinstr == NULL) continue; executed = threadinstr->m_instrArray[0].instr.isExecute; for (j = 0; j < dop; j++) { ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr == NULL) continue; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { show_pretty_time(es, instr, node_name, i, j, dop, executed); get_oper_time<true>(es, planstate, instr, i, j); if (instr->needRCInfo) { es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); es->planinfo->m_datanodeInfo->set_datanode_name(node_name, j, dop); ShowRoughCheckInfo(es, instr, i, j); } if (instr != NULL && instr->nloops > 0) { if (!need_timer) need_timer = instr->need_timer; rows += instr->ntuples; total_sec = 1000.0 * instr->total; start_sec = 1000.0 * instr->startup; total_sec_max = rtl::max(total_sec_max, total_sec); total_sec_min = rtl::min(total_sec_min, total_sec); start_sec_max = rtl::max(start_sec_max, start_sec); start_sec_min = rtl::min(start_sec_min, start_sec); peak_memory_min = rtl::min(peak_memory_min, instr->memoryinfo.peakOpMemory); peak_memory_max = rtl::max(peak_memory_max, instr->memoryinfo.peakOpMemory); width_min = rtl::min(width_min, instr->width); width_max = rtl::max(width_max, instr->width); } } else { append_datanode_name(es, node_name, dop, j); show_time<true>(es, instr, i); ShowRoughCheckInfo(es, instr, i, j); } ExplainCloseGroup("Plan", NULL, true, es); } } ExplainCloseGroup("Actual In Detail", "Actual In Detail", false, es); if (es->format == EXPLAIN_FORMAT_TEXT) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->analyze) { char str[100] = "\0"; int rc = 0; if (need_timer) rc = sprintf_s(str, sizeof(str), "[%.3f,%.3f]", total_sec_min, total_sec_max); else rc = sprintf_s(str, sizeof(str), "[0,0]"); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_ROWS, Float8GetDatum(rows)); if (es->timing) { es->planinfo->m_planInfo->put(ACTUAL_TIME, PointerGetDatum(cstring_to_text(str))); } char width[50] = "\0"; if (width_max > 0) { rc = sprintf_s(width, sizeof(width), "[%d,%d]", width_min, width_max); securec_check_ss(rc, "\0", "\0"); } es->planinfo->m_planInfo->put(ACTUAL_WIDTH, PointerGetDatum(cstring_to_text(width))); if (es->planinfo->m_planInfo->m_query_mem_mode) { char opmem[50] = "\0"; if (planstate->plan->operatorMemKB[0] > 0) { if (planstate->plan->operatorMemKB[0] < 1024) rc = sprintf_s(opmem, sizeof(opmem), "%dKB", (int)planstate->plan->operatorMemKB[0]); else { if (planstate->plan->operatorMemKB[0] > MIN_OP_MEM && planstate->plan->operatorMaxMem > planstate->plan->operatorMemKB[0]) rc = sprintf_s(opmem, sizeof(opmem), "%dMB(%dMB)", (int)planstate->plan->operatorMemKB[0] / 1024, (int)planstate->plan->operatorMaxMem / 1024); else rc = sprintf_s( opmem, sizeof(opmem), "%dMB", (int)planstate->plan->operatorMemKB[0] / 1024); } securec_check_ss(rc, "\0", "\0"); } es->planinfo->m_planInfo->put(ESTIMATE_MEMORY, PointerGetDatum(cstring_to_text(opmem))); } char memoryPeakMinSize[100] = "\0"; if (peak_memory_min < 1024) rc = sprintf_s(memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldBYTE", peak_memory_min); else if (peak_memory_min < 1024 * 1024) rc = sprintf_s(memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldKB", peak_memory_min / 1024); else rc = sprintf_s( memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldMB", peak_memory_min / (1024 * 1024)); securec_check_ss(rc, "\0", "\0"); char memoryPeakMaxSize[100] = "\0"; if (peak_memory_max < 1024) rc = sprintf_s(memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldBYTE", peak_memory_max); else if (peak_memory_max < 1024 * 1024) rc = sprintf_s(memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldKB", peak_memory_max / 1024); else rc = sprintf_s( memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldMB", peak_memory_max / (1024 * 1024)); securec_check_ss(rc, "\0", "\0"); char memoryStr[256] = "\0"; if (need_timer) rc = sprintf_s(memoryStr, sizeof(memoryStr), "[%s, %s]", memoryPeakMinSize, memoryPeakMaxSize); else rc = sprintf_s(memoryStr, sizeof(memoryStr), "[0, 0]"); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_MEMORY, PointerGetDatum(cstring_to_text(memoryStr))); } } } else { if (u_sess->instr_cxt.global_instr->getInstruNodeNum() > 0) { for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { if (!need_timer) need_timer = true; rows += instr->ntuples; total_sec = 1000.0 * instr->total; start_sec = 1000.0 * instr->startup; total_sec_max = rtl::max(total_sec_max, total_sec); total_sec_min = rtl::min(total_sec_min, total_sec); start_sec_max = rtl::max(start_sec_max, start_sec); start_sec_min = rtl::min(start_sec_min, start_sec); peak_memory_min = rtl::min(peak_memory_min, instr->memoryinfo.peakOpMemory); peak_memory_max = rtl::max(peak_memory_max, instr->memoryinfo.peakOpMemory); width_min = rtl::min(width_min, instr->width); width_max = rtl::max(width_max, instr->width); } } } } if (need_timer) { AssertEreport((total_sec_max != -1 || start_sec_max != -1) && (total_sec_min != HUGE_VAL - 1 || start_sec_min != HUGE_VAL - 1), MOD_EXECUTOR, "unexpect min/max value"); if (es->format == EXPLAIN_FORMAT_TEXT) { if (es->timing) appendStringInfo(es->str, " (actual time=[%.3f,%.3f]..[%.3f,%.3f], rows=%.0f)", start_sec_min, total_sec_min, start_sec_max, total_sec_max, rows); else appendStringInfo(es->str, " (actual rows=%.0f)", rows); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->analyze) { char str[100] = "\0"; int rc = sprintf_s(str, sizeof(str), "[%.3f,%.3f]", total_sec_min, total_sec_max); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_ROWS, Float8GetDatum(rows)); if (es->timing) { es->planinfo->m_planInfo->put(ACTUAL_TIME, PointerGetDatum(cstring_to_text(str))); } char width[50] = "\0"; if (width_max > 0) { rc = sprintf_s(width, sizeof(width), "[%d,%d]", width_min, width_max); securec_check_ss(rc, "\0", "\0"); } es->planinfo->m_planInfo->put(ACTUAL_WIDTH, PointerGetDatum(cstring_to_text(width))); if (es->planinfo->m_planInfo->m_query_mem_mode) { char opmem[50] = "\0"; if (planstate->plan->operatorMemKB[0] > 0) { if (planstate->plan->operatorMemKB[0] < 1024) rc = sprintf_s(opmem, sizeof(opmem), "%dKB", (int)planstate->plan->operatorMemKB[0]); else { if (planstate->plan->operatorMemKB[0] > MIN_OP_MEM && planstate->plan->operatorMaxMem > planstate->plan->operatorMemKB[0]) rc = sprintf_s(opmem, sizeof(opmem), "%dMB(%dMB)", (int)planstate->plan->operatorMemKB[0] / 1024, (int)planstate->plan->operatorMaxMem / 1024); else rc = sprintf_s( opmem, sizeof(opmem), "%dMB", (int)planstate->plan->operatorMemKB[0] / 1024); } securec_check_ss(rc, "\0", "\0"); } es->planinfo->m_planInfo->put(ESTIMATE_MEMORY, PointerGetDatum(cstring_to_text(opmem))); } char memoryPeakMinSize[100] = "\0"; if (peak_memory_min < 1024) rc = sprintf_s(memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldBYTE", peak_memory_min); else if (peak_memory_min < 1024 * 1024) rc = sprintf_s(memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldKB", peak_memory_min / 1024); else rc = sprintf_s( memoryPeakMinSize, sizeof(memoryPeakMinSize), "%ldMB", peak_memory_min / (1024 * 1024)); securec_check_ss(rc, "\0", "\0"); char memoryPeakMaxSize[100] = "\0"; if (peak_memory_max < 1024) rc = sprintf_s(memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldBYTE", peak_memory_max); else if (peak_memory_max < 1024 * 1024) rc = sprintf_s(memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldKB", peak_memory_max / 1024); else rc = sprintf_s( memoryPeakMaxSize, sizeof(memoryPeakMaxSize), "%ldMB", peak_memory_max / (1024 * 1024)); securec_check_ss(rc, "\0", "\0"); char memoryStr[256] = "\0"; rc = sprintf_s(memoryStr, sizeof(memoryStr), "[%s,%s]", memoryPeakMinSize, memoryPeakMaxSize); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_MEMORY, PointerGetDatum(cstring_to_text(memoryStr))); } } else { /* Do not show time information when timing is off */ if (es->timing) { ExplainPropertyFloat("Actual Min Startup Time", start_sec_min, 3, es); ExplainPropertyFloat("Actual Max Startup Time", start_sec_max, 3, es); ExplainPropertyFloat("Actual Min Total Time", total_sec_min, 3, es); ExplainPropertyFloat("Actual Max Total Time", total_sec_max, 3, es); } ExplainPropertyFloat("Actual Total Rows", rows, 0, es); } } else if (es->analyze) { if (es->format == EXPLAIN_FORMAT_TEXT) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { char str[100] = "\0"; int rc = sprintf_s(str, sizeof(str), "[0,0]"); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_ROWS, Float8GetDatum(rows)); if (es->timing) { es->planinfo->m_planInfo->put(ACTUAL_TIME, PointerGetDatum(cstring_to_text(str))); } char memoryStr[100] = "\0"; rc = sprintf_s(memoryStr, sizeof(memoryStr), "[0, 0]"); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_planInfo->put(ACTUAL_MEMORY, PointerGetDatum(cstring_to_text(memoryStr))); } else appendStringInfo(es->str, " (Actual time: never executed)"); } else { ExplainPropertyFloat("Actual Startup Time", 0.0, 3, es); ExplainPropertyFloat("Actual Total Time", 0.0, 3, es); } } /* in text format, first line ends here */ if (es->format == EXPLAIN_FORMAT_TEXT) appendStringInfoChar(es->str, '\n'); } return; } /* * If it's EXPLAIN ANALYZE, show instrumentation information for a plan node * * "which" identifies which instrumentation counter to print */ static void show_instrumentation_count(const char* qlabel, int which, const PlanState* planstate, ExplainState* es) { double nfiltered = 0.0; Instrumentation* instr = NULL; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (!es->analyze || !planstate->instrument) return; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ThreadInstrumentation* threadinstr = u_sess->instr_cxt.global_instr->getThreadInstrumentation(i, planstate->plan->plan_node_id, 0); if (threadinstr == NULL) continue; for (int j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL && instr->nloops > 0) { if (which == 1) nfiltered += instr->nfiltered1; else if (which == 2) nfiltered += instr->nfiltered2; } } } } else { if (which == 1) nfiltered = planstate->instrument->nfiltered1; else if (which == 2) nfiltered = planstate->instrument->nfiltered2; } if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL && (nfiltered > 0 || es->format != EXPLAIN_FORMAT_TEXT)) { ExplainPropertyFloat(qlabel, nfiltered, 0, es); } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_detailInfo) { if (nfiltered > 0 && es->format == EXPLAIN_FORMAT_TEXT) { char buf[512]; int rc = 0; rc = snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%.*f", 0, nfiltered); securec_check_ss(rc, "\0", "\0"); es->planinfo->m_detailInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_detailInfo->info_str, "%s: %s\n", qlabel, buf); } } } /* * Show removed rows by filters. */ static void show_removed_rows(int which, const PlanState* planstate, int idx, int smpIdx, int* removeRows) { Instrumentation* instr = NULL; if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(idx, planstate->plan->plan_node_id, smpIdx); if (instr != NULL && instr->nloops > 0) { if (which == 1) *removeRows = instr->nfiltered1; else if (which == 2) *removeRows = instr->nfiltered2; } } else { if (which == 1) *removeRows = planstate->instrument->nfiltered1; else if (which == 2) *removeRows = planstate->instrument->nfiltered2; } } /* * Show extra information for a ForeignScan node. */ static void show_foreignscan_info(ForeignScanState* fsstate, ExplainState* es) { FdwRoutine* fdwroutine = fsstate->fdwroutine; /* Let the FDW emit whatever fields it wants */ if (NULL != fdwroutine && NULL != fdwroutine->ExplainForeignScan) fdwroutine->ExplainForeignScan(fsstate, es); } /* * @Description: check whether Instrumentation object has * bloomfilter info to display about storage. * @IN instr: Instrumentation object * @Return: true if needed to display bloomfilter info; otherwise false. * @See also: */ static inline bool storage_has_bloomfilter_info(const Instrumentation* instr) { return (instr->bloomFilterRows > 0); } /* * @Description: check whether Instrumentation object has * min/max info to display about storage. * @IN instr: Instrumentation object * @Return: true if needed to display minmax filter info; otherwise false. * @See also: */ static inline bool storage_has_minmax_filter(const Instrumentation* instr) { return (instr->minmaxFilterFiles > 0 || instr->minmaxFilterStripe > 0 || instr->minmaxFilterStride > 0 || instr->minmaxFilterRows > 0); } /* * @Description: check whether Instrumentation object has * pruned-partition info to display about storage. * @IN instr: Instrumentation object * @Return: true if needed to display pruned-partition info; otherwise false. * @See also: */ static inline bool storage_has_pruned_info(const Instrumentation* instr) { return (instr->dynamicPrunFiles > 0 || instr->staticPruneFiles > 0); } /* * @Description: check whether Instrumentation object has * orc data cache info to display about storage. * @IN instr: Instrumentation object * @Return: true if needed to display orc data cache info; otherwise false. * @See also: */ static inline bool storage_has_cached_info(const Instrumentation* instr) { return (instr->orcMetaCacheBlockCount > 0 || instr->orcMetaLoadBlockCount > 0 || instr->orcDataCacheBlockCount > 0 || instr->orcDataLoadBlockCount > 0); } /* * @Description: append dfs block info to str * @in planstate - current plan state info * @in es - explain state info * @return - void */ static void append_dfs_block_info( ExplainState* es, double localRatio, double metaCacheRatio, double dataCacheRatio, Instrumentation* instr) { if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(es->str, "(local read ratio: %.1f%s, local: %.0f, remote: %.0f)", localRatio * 100, "%", instr->localBlock, instr->remoteBlock); appendStringInfo( es->str, " (nn intersection count: %lu, dn intersection count: %lu)", instr->nnCalls, instr->dnCalls); appendStringInfo(es->str, " (meta cache: hit ratio %.1f%s, hit[count %lu, size %lu], read[count %lu, size %lu]", metaCacheRatio * 100, "%", instr->orcMetaCacheBlockCount, instr->orcMetaCacheBlockSize, instr->orcMetaLoadBlockCount, instr->orcMetaLoadBlockSize); appendStringInfo(es->str, " data cache: hit ratio %.1f%s, hit[count %lu, size %lu], read[count %lu, size %lu])", dataCacheRatio * 100, "%", instr->orcDataCacheBlockCount, instr->orcDataCacheBlockSize, instr->orcDataLoadBlockCount, instr->orcDataLoadBlockSize); appendStringInfo(es->str, "\n"); } else { ExplainPropertyFloat("local read ratio", localRatio * 100, 1, es); ExplainPropertyFloat("local block", instr->localBlock, 0, es); ExplainPropertyFloat("remote block", instr->remoteBlock, 0, es); ExplainPropertyLong("nn intersection count", instr->nnCalls, es); ExplainPropertyLong("dn intersection count", instr->dnCalls, es); ExplainPropertyFloat("meta cache hit ratio", metaCacheRatio * 100, 1, es); ExplainPropertyLong("meta cache hit count", instr->orcMetaCacheBlockCount, es); ExplainPropertyLong("meta cache hit size", instr->orcMetaCacheBlockSize, es); ExplainPropertyLong("meta cache read count", instr->orcMetaLoadBlockCount, es); ExplainPropertyLong("meta cache read size", instr->orcMetaLoadBlockSize, es); ExplainPropertyFloat("data cache hit ratio", dataCacheRatio * 100, 1, es); ExplainPropertyLong("data cache hit count", instr->orcDataCacheBlockCount, es); ExplainPropertyLong("data cache hit size", instr->orcDataCacheBlockSize, es); ExplainPropertyLong("data cache read count", instr->orcDataLoadBlockCount, es); ExplainPropertyLong("data cache read size", instr->orcDataLoadBlockSize, es); } } /* * @Description: print dfs info in detail=off * @in planstate - current plan state info * @in es - explain state info * @return - void */ static void show_analyze_dfs_info(const PlanState* planstate, ExplainState* es) { Instrumentation* instr = NULL; int i = 0; int j = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; double total_local_block = 0.0; double total_remote_block = 0.0; double total_datacache_block_count = 0.0; double total_metacache_block_count = 0.0; double total_metaload_block_count = 0.0; double total_dataload_block_count = 0.0; for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL) { total_local_block += instr->localBlock; total_remote_block += instr->remoteBlock; total_datacache_block_count += instr->orcDataCacheBlockCount; total_metacache_block_count += instr->orcMetaCacheBlockCount; total_dataload_block_count += instr->orcDataLoadBlockCount; total_metaload_block_count += instr->orcMetaLoadBlockCount; } } } if (total_local_block > 0 || total_remote_block > 0 || total_datacache_block_count > 0 || total_metacache_block_count > 0 || total_metaload_block_count || total_dataload_block_count) { double localRatio = (total_local_block + total_remote_block == 0) ? 0 : (total_local_block / (total_local_block + total_remote_block)); double metaCacheRatio = (total_metacache_block_count + total_metaload_block_count == 0) ? 0 : (double)total_metacache_block_count / (total_metacache_block_count + total_metaload_block_count); double dataCacheRatio = (total_datacache_block_count + total_dataload_block_count == 0) ? 0 : (double)total_datacache_block_count / (total_dataload_block_count + total_datacache_block_count); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "(local read ratio: %.1f%s,", localRatio * 100, "%"); appendStringInfo( es->planinfo->m_staticInfo->info_str, " meta cache hit ratio: %.1f%s,", metaCacheRatio * 100, "%"); appendStringInfo( es->planinfo->m_staticInfo->info_str, " data cache hit ratio %.1f%s)\n", dataCacheRatio * 100, "%"); } if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "(local read ratio: %.1f%s,", localRatio * 100, "%"); appendStringInfo(es->str, " meta cache hit ratio: %.1f%s,", metaCacheRatio * 100, "%"); appendStringInfo(es->str, " data cache hit ratio: %.1f%s)\n", dataCacheRatio * 100, "%"); } else { ExplainPropertyFloat("local read ratio", localRatio, 1, es); ExplainPropertyFloat("meta cache hit ratio", metaCacheRatio, 1, es); ExplainPropertyFloat("data cache hit ratio", dataCacheRatio, 1, es); } } } static void show_dfs_block_info(PlanState* planstate, ExplainState* es) { AssertEreport(planstate != NULL && es != NULL, MOD_EXECUTOR, "unexpect null value"); if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; int i = 0; int j = 0; bool has_info = false; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (es->detail) { for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr == NULL) continue; if (instr->localBlock > 0 || instr->remoteBlock > 0 || storage_has_cached_info(instr)) { if (has_info == false) ExplainOpenGroup("Dfs Block Detail", "Dfs Block Detail", false, es); has_info = true; ExplainOpenGroup("Plan", NULL, true, es); double localRatio = instr->localBlock / (instr->localBlock + instr->remoteBlock); double metaCacheRatio = (instr->orcMetaCacheBlockCount + instr->orcMetaLoadBlockCount == 0) ? 0 : (double)instr->orcMetaCacheBlockCount / (instr->orcMetaCacheBlockCount + instr->orcMetaLoadBlockCount); double dataCacheRatio = (instr->orcDataCacheBlockCount + instr->orcDataLoadBlockCount == 0) ? 0 : (double)instr->orcDataCacheBlockCount / (instr->orcDataCacheBlockCount + instr->orcDataLoadBlockCount); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(i, 0, DFS_BLOCK_INFO, BoolGetDatum(true)); es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); es->planinfo->m_datanodeInfo->set_datanode_name(node_name, j, dop); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "(local read ratio: %.1f%s, local: %.0f, remote: %.0f)", localRatio * 100, "%", instr->localBlock, instr->remoteBlock); /* as for the obs foreign table, we do not have the datanode and namenode. */ if (instr->nnCalls != 0 && instr->dnCalls != 0) { appendStringInfo(es->planinfo->m_datanodeInfo->info_str, " (nn intersection count: %lu, dn intersection count: %lu)", instr->nnCalls, instr->dnCalls); } appendStringInfo(es->planinfo->m_datanodeInfo->info_str, " (meta cache: hit ratio %.1f%s, hit[count %lu, size %lu], read[count %lu, size %lu]", metaCacheRatio * 100, "%", instr->orcMetaCacheBlockCount, instr->orcMetaCacheBlockSize, instr->orcMetaLoadBlockCount, instr->orcMetaLoadBlockSize); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, " data cache: hit ratio %.1f%s, hit[count %lu, size %lu], read[count %lu, size %lu])", dataCacheRatio * 100, "%", instr->orcDataCacheBlockCount, instr->orcDataCacheBlockSize, instr->orcDataLoadBlockCount, instr->orcDataLoadBlockSize); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "\n"); continue; } append_datanode_name(es, node_name, dop, j); append_dfs_block_info(es, localRatio, metaCacheRatio, dataCacheRatio, instr); ExplainCloseGroup("Plan", NULL, true, es); } } } if (has_info) ExplainCloseGroup("Dfs Block Detail", "Dfs Block Detail", false, es); } else show_analyze_dfs_info(planstate, es); } } /* * @Description: print filter info in detail in storage level * @in instr - instrument info * @in instr_info - the string to be append * @return - void */ static void show_detail_storage_info_json_of_dfs(Instrumentation* instr, StringInfo instr_info, ExplainState* es) { if (storage_has_bloomfilter_info(instr)) { ExplainPropertyLong("rows skipped by bloom filter", instr->bloomFilterRows, es); if (instr->bloomFilterBlocks > 0) { ExplainPropertyLong("include strides) ", instr->bloomFilterBlocks, es); } } if (storage_has_minmax_filter(instr)) { if (instr->minmaxFilterRows > 0) { ExplainPropertyLong("min max skip rows", instr->minmaxFilterRows, es); } if (instr->minmaxFilterStride > 0) { ExplainPropertyLong("min max filter strides", instr->minmaxFilterStride, es); ExplainPropertyLong("min max check strides", instr->minmaxCheckStride, es); } if (instr->minmaxFilterStripe > 0) { ExplainPropertyLong("min max filter stripes", instr->minmaxFilterStripe, es); ExplainPropertyLong("min max check stripes", instr->minmaxCheckStripe, es); } if (instr->minmaxFilterFiles > 0) { ExplainPropertyLong("min max filter files", instr->minmaxFilterFiles, es); ExplainPropertyLong("min max check files", instr->minmaxCheckFiles, es); } } if (storage_has_pruned_info(instr)) { if (instr->staticPruneFiles > 0) { ExplainPropertyLong("pruned files static", instr->staticPruneFiles, es); } if (instr->dynamicPrunFiles > 0) { ExplainPropertyLong("pruned files dynamic", instr->dynamicPrunFiles, es); } } } static void show_detail_storage_info_json_of_logft(const Instrumentation* instr, StringInfo instr_info, ExplainState* es) { if (instr->minmaxFilterStripe > 0) { ExplainPropertyText("refuted by hostname", "true", es); } if (instr->minmaxCheckStride > 0) { ExplainPropertyLong("dirname total", instr->minmaxCheckStride, es); if (instr->minmaxFilterStride > 0) { ExplainPropertyLong("dirname refuted", instr->minmaxFilterStride, es); ExplainPropertyLong("dirname scan", (instr->minmaxCheckStride - instr->minmaxFilterStride), es); } } if (instr->minmaxCheckFiles > 0) { ExplainPropertyLong("filename total", instr->minmaxCheckFiles, es); if (instr->minmaxFilterFiles > 0) { ExplainPropertyLong("filename refuted", instr->minmaxFilterFiles, es); ExplainPropertyLong("filename scan", (instr->minmaxCheckFiles - instr->minmaxFilterFiles), es); } if (instr->staticPruneFiles > 0) { ExplainPropertyLong("filename incompleted", instr->staticPruneFiles, es); } if (instr->dynamicPrunFiles) { ExplainPropertyLong("filename latest files", instr->dynamicPrunFiles, es); } } } static void show_detail_storage_info_json(Instrumentation* instr, StringInfo instr_info, ExplainState* es) { if (instr->dfsType == TYPE_LOG_FT) { show_detail_storage_info_json_of_logft(instr, instr_info, es); } else { show_detail_storage_info_json_of_dfs(instr, instr_info, es); } } static void show_detail_storage_info_text_of_dfs(Instrumentation* instr, StringInfo instr_info) { if (storage_has_bloomfilter_info(instr)) { appendStringInfo(instr_info, "(skip %lu rows by bloom filter", instr->bloomFilterRows); if (instr->bloomFilterBlocks > 0) { appendStringInfo(instr_info, " include %lu strides) ", instr->bloomFilterBlocks); } else { appendStringInfo(instr_info, ") "); } } if (storage_has_minmax_filter(instr)) { appendStringInfo(instr_info, "(min max skip:"); if (instr->minmaxFilterRows > 0) { appendStringInfo(instr_info, " rows %lu", instr->minmaxFilterRows); } if (instr->minmaxFilterStride > 0) { appendStringInfo(instr_info, " strides %lu/%lu", instr->minmaxFilterStride, instr->minmaxCheckStride); } if (instr->minmaxFilterStripe > 0) { appendStringInfo(instr_info, " stripes %lu/%lu", instr->minmaxFilterStripe, instr->minmaxCheckStripe); } if (instr->minmaxFilterFiles > 0) { appendStringInfo(instr_info, " files %lu/%lu", instr->minmaxFilterFiles, instr->minmaxCheckFiles); } appendStringInfo(instr_info, ")"); } if (storage_has_pruned_info(instr)) { appendStringInfo(instr_info, "(pruned files:"); if (instr->staticPruneFiles > 0) { appendStringInfo(instr_info, " static %lu", instr->staticPruneFiles); } if (instr->dynamicPrunFiles > 0) { appendStringInfo(instr_info, " dynamic %lu", instr->dynamicPrunFiles); } appendStringInfo(instr_info, ")"); } appendStringInfo(instr_info, "\n"); } static void show_detail_storage_info_text_of_logft(const Instrumentation* instr, StringInfo instr_info) { if (instr->minmaxFilterStripe > 0) { appendStringInfo(instr_info, "(refuted by hostname)"); } if (instr->minmaxCheckStride > 0) { appendStringInfo(instr_info, "(dirname: total %lu", instr->minmaxCheckStride); if (instr->minmaxFilterStride > 0) { appendStringInfo(instr_info, ", refuted %lu, scan %lu", instr->minmaxFilterStride, (instr->minmaxCheckStride - instr->minmaxFilterStride)); } appendStringInfo(instr_info, ")"); } if (instr->minmaxCheckFiles > 0) { appendStringInfo(instr_info, "(filename: total %lu", instr->minmaxCheckFiles); if (instr->minmaxFilterFiles > 0) { appendStringInfo(instr_info, ", refuted %lu, scan %lu", instr->minmaxFilterFiles, (instr->minmaxCheckFiles - instr->minmaxFilterFiles)); } if (instr->staticPruneFiles > 0) { appendStringInfo(instr_info, ", incompleted %lu", instr->staticPruneFiles); } if (instr->dynamicPrunFiles) { appendStringInfo(instr_info, ", latest files %lu", instr->dynamicPrunFiles); } appendStringInfo(instr_info, ")"); } appendStringInfo(instr_info, "\n"); } static void show_detail_storage_info_text(Instrumentation* instr, StringInfo instr_info) { if (instr->dfsType == TYPE_LOG_FT) { show_detail_storage_info_text_of_logft(instr, instr_info); } else { /* DFS type */ show_detail_storage_info_text_of_dfs(instr, instr_info); } } /* * @Description: print storage info in detail=off * @in planstate - current plan state info * @in es - explain state info * @return - void */ static void show_analyze_storage_info_of_dfs(const PlanState* planstate, ExplainState* es) { int i = 0; int j = 0; uint64 total_bloomfilter_rows = 0; uint64 total_dynamicfiles = 0; uint64 total_staticFiles = 0; Instrumentation* instr = NULL; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr != NULL) { total_bloomfilter_rows += instr->bloomFilterRows; total_dynamicfiles += instr->dynamicPrunFiles; total_staticFiles += instr->staticPruneFiles; } } } if (total_bloomfilter_rows > 0 || total_dynamicfiles > 0 || total_staticFiles > 0) { if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo( es->planinfo->m_staticInfo->info_str, "(skip %lu rows by bloom filter,", total_bloomfilter_rows); appendStringInfo(es->planinfo->m_staticInfo->info_str, " pruned files: static %lu, dynamic %lu)\n", total_dynamicfiles, total_staticFiles); } if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "(skip %lu rows by bloom filter,", total_bloomfilter_rows); appendStringInfo( es->str, " pruned files: static %lu, dynamic %lu)\n", total_dynamicfiles, total_staticFiles); } else { ExplainPropertyLong("rows skipped by bloom filter", total_bloomfilter_rows, es); ExplainPropertyLong("pruned files static", total_dynamicfiles, es); ExplainPropertyLong("pruned files dynamic", total_staticFiles, es); } } } static void show_analyze_storage_info_of_logft(const PlanState* planstate, ExplainState* es) { uint64 total_hostname = 0; uint64 total_refuted_by_hostname = 0; uint64 total_dirname = 0; uint64 total_refuted_by_dirname = 0; uint64 total_filename = 0; uint64 total_refuted_by_filename = 0; uint64 total_incompleted = 0; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; Instrumentation* instr = NULL; int node_idx = 0; int dop_idx = 0; for (node_idx = 0; node_idx < u_sess->instr_cxt.global_instr->getInstruNodeNum(); node_idx++) { for (dop_idx = 0; dop_idx < dop; dop_idx++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(node_idx, planstate->plan->plan_node_id, dop_idx); if (instr != NULL) { total_hostname += instr->minmaxCheckStripe; total_refuted_by_hostname += instr->minmaxFilterStripe; total_dirname += instr->minmaxCheckStride; total_refuted_by_dirname += instr->minmaxFilterStride; total_filename += instr->minmaxCheckFiles; total_refuted_by_filename += instr->minmaxFilterFiles; total_incompleted += instr->staticPruneFiles; } } } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_staticInfo) { es->planinfo->m_staticInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_staticInfo->info_str, "(nodes refuted %lu, total %lu)", total_refuted_by_hostname, total_hostname); appendStringInfo(es->planinfo->m_staticInfo->info_str, "(dirname refuted %lu, total %lu)", total_refuted_by_dirname, total_dirname); appendStringInfo(es->planinfo->m_staticInfo->info_str, "(filename refuted %lu, total %lu, incompleted %lu)\n", total_refuted_by_filename, total_filename, total_incompleted); } if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "(nodes refuted %lu, total %lu)", total_refuted_by_hostname, total_hostname); appendStringInfo(es->str, "(dirname refuted %lu, total %lu)", total_refuted_by_dirname, total_dirname); appendStringInfo(es->str, "(filename refuted %lu, total %lu, incompleted %lu)\n", total_refuted_by_filename, total_filename, total_incompleted); } else { ExplainPropertyLong("nodes refuted", total_refuted_by_hostname, es); ExplainPropertyLong("nodes total", total_hostname, es); ExplainPropertyLong("dirname refuted", total_refuted_by_dirname, es); ExplainPropertyLong("dirname total", total_dirname, es); ExplainPropertyLong("filename refuted", total_refuted_by_filename, es); ExplainPropertyLong("filename total", total_filename, es); ExplainPropertyLong("filename incompleted", total_incompleted, es); } } static void show_analyze_storage_info(PlanState* planstate, ExplainState* es) { if (u_sess->instr_cxt.global_instr->getInstruNodeNum() > 0) { Instrumentation* instr = u_sess->instr_cxt.global_instr->getInstrSlot(0, planstate->plan->plan_node_id, 0); if (instr && instr->dfsType == TYPE_LOG_FT) { show_analyze_storage_info_of_logft(planstate, es); } else { show_analyze_storage_info_of_dfs(planstate, es); } } } static void show_storage_filter_info(PlanState* planstate, ExplainState* es) { AssertEreport(planstate != NULL && es != NULL, MOD_EXECUTOR, "unexpect null value"); if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; int i = 0; int j = 0; bool has_info = false; int dop = planstate->plan->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; if (es->detail) { for (i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id, j); if (instr == NULL) continue; if (storage_has_bloomfilter_info(instr) || storage_has_minmax_filter(instr) || storage_has_pruned_info(instr)) { if (has_info == false) ExplainOpenGroup("Storage Detail", "Storage Detail", false, es); has_info = true; ExplainOpenGroup("Plan", NULL, true, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(i, 0, BLOOM_FILTER_INFO, true); es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); es->planinfo->m_datanodeInfo->set_datanode_name(node_name, j, dop); show_detail_storage_info_text(instr, es->planinfo->m_datanodeInfo->info_str); continue; } append_datanode_name(es, node_name, dop, j); if (es->format == EXPLAIN_FORMAT_TEXT) show_detail_storage_info_text(instr, es->str); else show_detail_storage_info_json(instr, es->str, es); ExplainCloseGroup("Plan", NULL, true, es); } } } if (has_info) ExplainCloseGroup("Storage Detail", "Storage Detail", false, es); } else show_analyze_storage_info(planstate, es); } } static void show_wlm_explain_name(ExplainState* es, const char* plan_name, const char* pname, int plan_node_id) { if (plan_name != NULL) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); appendStringInfo(es->str, "%s\n", plan_name); es->indent++; } int digit = get_digit(plan_node_id); appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit - digit); appendStringInfo(es->str, "%d | ", plan_node_id); if (es->indent) { appendStringInfoSpaces(es->str, es->indent); appendStringInfoString(es->str, "-> "); } appendStringInfoString(es->str, pname); es->indent++; } /* * Show extra information of MERGE for a ModifyTable node */ static void show_modifytable_merge_info(const PlanState* planstate, ExplainState* es) { if (planstate->plan->plan_node_id > 0 && u_sess->instr_cxt.global_instr && u_sess->instr_cxt.global_instr->isFromDataNode(planstate->plan->plan_node_id)) { Instrumentation* instr = NULL; if (es->detail) { ExplainOpenGroup("Merge Detail", "Merge Detail", false, es); for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { ExplainOpenGroup("Plan", NULL, true, es); instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, planstate->plan->plan_node_id); if (instr == NULL) continue; #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif append_datanode_name(es, node_name, 1, 0); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(i, 0, MERGE_INSERTED, instr->nfiltered1); es->planinfo->m_runtimeinfo->put(i, 0, MERGE_UPDATED, instr->nfiltered2); es->planinfo->m_datanodeInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "%s ", node_name); appendStringInfo( es->planinfo->m_datanodeInfo->info_str, "(Merge: inserted %.0f, ", instr->nfiltered1); appendStringInfo(es->planinfo->m_datanodeInfo->info_str, "updated %.0f)\n", instr->nfiltered2); continue; } if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(es->str, "(Merge: inserted %.0f, ", instr->nfiltered1); appendStringInfo(es->str, "updated %.0f)\n", instr->nfiltered2); } else { ExplainPropertyFloat("Merge Inserted", instr->nfiltered1, 0, es); ExplainPropertyFloat("Merge Updated", instr->nfiltered2, 0, es); } ExplainCloseGroup("Plan", NULL, true, es); } ExplainCloseGroup("Merge Detail", "Merge Detail", false, es); } } } static void ShowRoughCheckInfo(ExplainState* es, struct Instrumentation* instrument, int nodeIdx, int smpIdx) { RCInfo* rcPtr = &instrument->rcInfo; if (instrument->needRCInfo) { if (es->planinfo && es->planinfo->m_runtimeinfo) { es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, CU_NONE, Int64GetDatum(rcPtr->m_CUNone)); es->planinfo->m_runtimeinfo->put(nodeIdx, smpIdx, CU_SOME, Int64GetDatum(rcPtr->m_CUSome)); appendStringInfoString(es->planinfo->m_datanodeInfo->info_str, "(RoughCheck CU: "); appendStringInfo( es->planinfo->m_datanodeInfo->info_str, "CUNone: %lu, CUSome: %lu", rcPtr->m_CUNone, rcPtr->m_CUSome); appendStringInfoString(es->planinfo->m_datanodeInfo->info_str, ")\n"); } if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoString(es->str, " (RoughCheck CU: "); appendStringInfo(es->str, "CUNone: %lu, CUSome: %lu", rcPtr->m_CUNone, rcPtr->m_CUSome); appendStringInfoString(es->str, ")\n"); } else { ExplainPropertyLong("RoughCheck CUNone", rcPtr->m_CUNone, es); ExplainPropertyLong("RoughCheck CUSome", rcPtr->m_CUSome, es); } } } /* * Fetch the name of an index in an EXPLAIN * * We allow plugins to get control here so that plans involving hypothetical * indexes can be explained. */ static const char* explain_get_index_name(Oid indexId) { const char* result = NULL; if (explain_get_index_name_hook) { result = (*explain_get_index_name_hook) (indexId); if(result) return result; } /* default behavior: look in the catalogs and quote it */ result = get_rel_name(indexId); if (result == NULL) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for index %u", indexId))); result = quote_identifier(result); return result; } /* * Add some additional details about an IndexScan or IndexOnlyScan */ static void ExplainIndexScanDetails(Oid indexid, ScanDirection indexorderdir, ExplainState* es) { const char* indexname = explain_get_index_name(indexid); if (es->format == EXPLAIN_FORMAT_TEXT) { if (ScanDirectionIsBackward(indexorderdir)) appendStringInfoString(es->str, " Backward"); appendStringInfo(es->str, " using %s", indexname); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) { StringInfo tmpName = &es->planinfo->m_planInfo->m_pname; if (ScanDirectionIsBackward(indexorderdir)) appendStringInfoString(tmpName, " Backward"); appendStringInfo(tmpName, " using %s", indexname); } } else { const char* scandir = NULL; switch (indexorderdir) { case BackwardScanDirection: scandir = "Backward"; break; case NoMovementScanDirection: scandir = "NoMovement"; break; case ForwardScanDirection: scandir = "Forward"; break; default: scandir = "?\?\?"; break; } ExplainPropertyText("Scan Direction", scandir, es); ExplainPropertyText("Index Name", indexname, es); } } /* * Show the target of a Scan node */ static void ExplainScanTarget(Scan* plan, ExplainState* es) { ExplainTargetRel((Plan*)plan, plan->scanrelid, es); } /* * Show the target of a ModifyTable node */ static void ExplainModifyTarget(ModifyTable* plan, ExplainState* es) { Index rti; /* * We show the name of the first target relation. In multi-target-table * cases this should always be the parent of the inheritance tree. */ AssertEreport(plan->resultRelations != NIL, MOD_EXECUTOR, "unexpect empty list"); rti = linitial_int(plan->resultRelations); ExplainTargetRel((Plan*)plan, rti, es); } /* * Show the target relation of a scan or modify node */ static void ExplainTargetRel(Plan* plan, Index rti, ExplainState* es) { char* objectname = NULL; char* namespc = NULL; const char* objecttag = NULL; char* object_type = NULL; /* for plan_table column "object_type" */ RangeTblEntry* rte = NULL; if (IsA(plan, RemoteQuery) || IsA(plan, VecRemoteQuery)) { RemoteQuery* rq = (RemoteQuery*)plan; /* skip Streaming(Gather) since there is no corresponding RangeTblEntry */ if (rq->is_simple) return; } rte = rt_fetch(rti, es->rtable); if (rte == NULL) { ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("Unable to get relation."))); } /* Set object_type from rte->rtekind or rte->relkind for 'plan_table'. */ if (es->plan && rte) { es->planinfo->m_planTableData->set_object_type(rte, &object_type); } switch (nodeTag(plan)) { case T_SeqScan: case T_CStoreScan: #ifdef ENABLE_MULTIPLE_NODES case T_TsStoreScan: #endif /* ENABLE_MULTIPLE_NODES */ case T_DfsScan: case T_DfsIndexScan: case T_IndexScan: case T_IndexOnlyScan: case T_BitmapHeapScan: case T_CStoreIndexScan: case T_CStoreIndexCtidScan: case T_CStoreIndexHeapScan: case T_TidScan: case T_ForeignScan: case T_ExtensiblePlan: case T_VecForeignScan: case T_ModifyTable: case T_VecModifyTable: { /* Assert it's on a real relation */ Assert(rte != NULL); Assert(rte->rtekind == RTE_RELATION); objectname = get_rel_name(rte->relid); if (es->verbose || es->plan) namespc = get_namespace_name(get_rel_namespace(rte->relid)); objecttag = "Relation Name"; } break; case T_FunctionScan: { Node* funcexpr = NULL; /* Assert it's on a RangeFunction */ Assert(rte != NULL && rte->rtekind == RTE_FUNCTION); /* * If the expression is still a function call, we can get the * real name of the function. Otherwise, punt (this can * happen if the optimizer simplified away the function call, * for example). */ funcexpr = ((FunctionScan*)plan)->funcexpr; if (funcexpr && IsA(funcexpr, FuncExpr)) { Oid funcid = ((FuncExpr*)funcexpr)->funcid; objectname = get_func_name(funcid); if (es->verbose || es->plan) namespc = get_namespace_name(get_func_namespace(funcid)); } objecttag = "Function Name"; } break; case T_ValuesScan: { Assert(rte != NULL); Assert(rte->rtekind == RTE_VALUES); } break; case T_CteScan: { /* Assert it's on a non-self-reference CTE */ Assert(rte != NULL && rte->rtekind == RTE_CTE && !rte->self_reference); objectname = rte->ctename; objecttag = "CTE Name"; } break; case T_WorkTableScan: { /* Assert it's on a self-reference CTE */ Assert(rte != NULL && rte->rtekind == RTE_CTE && rte->self_reference); objectname = rte->ctename; objecttag = "CTE Name"; } break; case T_RemoteQuery: { /* get the object name from RTE itself */ RemoteQuery* rq = (RemoteQuery*)plan; if (rq->is_simple == false && rte) { Assert(rte->rtekind == RTE_REMOTE_DUMMY); objectname = rte->relname; objecttag = "RemoteQuery name"; } } break; default: break; } if (es->format == EXPLAIN_FORMAT_TEXT) { StringInfo tmpName; if (t_thrd.explain_cxt.explain_perf_mode == EXPLAIN_NORMAL) tmpName = es->str; else tmpName = &es->planinfo->m_planInfo->m_pname; appendStringInfoString(tmpName, " on"); if (namespc != NULL && objectname != NULL) { appendStringInfo(tmpName, " %s.%s", quote_identifier(namespc), quote_identifier(objectname)); } else if (objectname != NULL) { appendStringInfo(tmpName, " %s", quote_identifier(objectname)); } if (rte && rte->eref && (objectname == NULL || strcmp(rte->eref->aliasname, objectname) != 0)) { appendStringInfo(tmpName, " %s", quote_identifier(rte->eref->aliasname)); } /* Show if use column table min/max optimization. */ if (IsA(plan, CStoreScan) && ((CStoreScan*)plan)->minMaxInfo != NULL) { appendStringInfo(tmpName, " %s", "(min-max optimization)"); } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL) es->planinfo->m_planInfo->put(PLAN, PointerGetDatum(cstring_to_text(tmpName->data))); } else { if (objecttag != NULL && objectname != NULL) ExplainPropertyText(objecttag, objectname, es); if (namespc != NULL) ExplainPropertyText("Schema", namespc, es); if (rte != NULL && rte->eref != NULL) { ExplainPropertyText("Alias", rte->eref->aliasname, es); } } /* Set object_name, object_type, object_owner for 'plan_table'. */ if (es->plan) { /* If rte are subquery and values, then rte name will be null. And we get their name from alias. */ if (objectname == NULL && rte != NULL && rte->eref != NULL) objectname = rte->eref->aliasname; /* CTE\SUBQUERY\VALUES\JOIN\REMOTEQUERY do not have object owner. */ if (objectname != NULL) es->planinfo->m_planTableData->set_plan_table_objs(plan->plan_node_id, objectname, object_type, namespc); } } /* * Show extra information for upsert info */ static void show_on_duplicate_info(ModifyTableState* mtstate, ExplainState* es) { ResultRelInfo* resultRelInfo = mtstate->resultRelInfo; IndexInfo* indexInfo = NULL; List* idxNames = NIL; /* Gather names of ON CONFLICT Arbiter indexes */ for (int i = 0; i < resultRelInfo->ri_NumIndices; ++i) { indexInfo = resultRelInfo->ri_IndexRelationInfo[i]; if (!indexInfo->ii_Unique && !indexInfo->ii_ExclusionOps) { continue; } Relation indexRelation = resultRelInfo->ri_IndexRelationDescs[i]; char* indexName = RelationGetRelationName(indexRelation); idxNames = lappend(idxNames, indexName); } ExplainPropertyText("Conflict Resolution", mtstate->mt_upsert->us_action == UPSERT_NOTHING ? "NOTHING" : "UPDATE", es); /* * Don't display arbiter indexes at all when DO NOTHING variant * implicitly ignores all conflicts */ if (idxNames != NIL) { ExplainPropertyList("Conflict Arbiter Indexes", idxNames, es); } } #ifndef PGXC /* * Show extra information for a ModifyTable node */ static void show_modifytable_info(ModifyTableState* mtstate, ExplainState* es) { FdwRoutine* fdwroutine = mtstate->resultRelInfo->ri_FdwRoutine; /* * If the first target relation is a foreign table, call its FDW to * display whatever additional fields it wants to. For now, we ignore the * possibility of other targets being foreign tables, although the API for * ExplainForeignModify is designed to allow them to be processed. */ if (fdwroutine != NULL && fdwroutine->ExplainForeignModify != NULL) { ModifyTable* node = (ModifyTable*)mtstate->ps.plan; List* fdw_private = (List*)linitial(node->fdwPrivLists); fdwroutine->ExplainForeignModify(mtstate, mtstate->resultRelInfo, fdw_private, 0, es); } } #endif /* PGXC */ /* * Explain the constituent plans of a ModifyTable, Append, MergeAppend, * BitmapAnd, or BitmapOr node. * * The ancestors list should already contain the immediate parent of these * plans. * * Note: we don't actually need to examine the Plan list members, but * we need the list in order to determine the length of the PlanState array. */ static void ExplainMemberNodes(const List* plans, PlanState** planstates, List* ancestors, ExplainState* es) { int nplans = list_length(plans); int j; bool old_flag = es->from_dn; for (j = 0; j < nplans; j++) { es->from_dn = old_flag; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL) ExplainNode<true>(planstates[j], ancestors, "Member", NULL, es); else ExplainNode<false>(planstates[j], ancestors, "Member", NULL, es); } es->from_dn = old_flag; } /* * Explain a list of SubPlans (or initPlans, which also use SubPlan nodes). * * The ancestors list should already contain the immediate parent of these * SubPlanStates. */ static void ExplainSubPlans(List* plans, List* ancestors, const char* relationship, ExplainState* es) { ListCell* lst = NULL; bool old_flag = es->from_dn; foreach (lst, plans) { SubPlanState* sps = (SubPlanState*)lfirst(lst); SubPlan* sp = (SubPlan*)sps->xprstate.expr; es->from_dn = old_flag; if (sps->planstate == NULL) continue; if (sps->planstate->plan->exec_type == EXEC_ON_DATANODES) es->from_dn = true; /* * For stream planning of RecursiveUnion, we already print the RecursiveUnion * plan node in normal position, so in subplan list, we skip this part * * e.g. * * id | operation * ----+--------------------------------------------------------------------------------- * 1 | -> Streaming (type: GATHER) * 2 | -> Sort * 3 | -> CTE Scan on rq * 4 | -> Recursive Union * 5 | -> Seq Scan on chinamap * 6 | -> Hash Join (7,9) * 7 | -> Streaming(type: REDISTRIBUTE) stream_level:1 * 8 | -> Seq Scan on chinamap origin <<ruid:[4] ctlid:[4] (SYNC)>> * 9 | -> Hash * 10 | -> Streaming(type: REDISTRIBUTE) stream_level:1 * 11 | -> WorkTable Scan on rq <<ruid:[4] ctlid:[4]>> */ if (STREAM_RECURSIVECTE_SUPPORTED && sp->subLinkType == CTE_SUBLINK) { continue; } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo != NULL) ExplainNode<true>(sps->planstate, ancestors, relationship, sp->plan_name, es); else ExplainNode<false>(sps->planstate, ancestors, relationship, sp->plan_name, es); } es->from_dn = old_flag; } static void ExplainPrettyList(List* data, ExplainState* es) { ListCell* lc = NULL; bool first = true; foreach (lc, data) { if (!first) { appendStringInfoString(es->planinfo->m_verboseInfo->info_str, ", "); } appendStringInfoString(es->planinfo->m_verboseInfo->info_str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->planinfo->m_verboseInfo->info_str, '\n'); } /* * Explain a property, such as sort keys or targets, that takes the form of * a list of unlabeled items. "data" is a list of C strings. */ void ExplainPropertyList(const char* qlabel, List* data, ExplainState* es) { ListCell* lc = NULL; bool first = true; switch (es->format) { case EXPLAIN_FORMAT_TEXT: if (es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); } else { appendStringInfoSpaces(es->str, es->indent * 2); } appendStringInfo(es->str, "%s: ", qlabel); foreach (lc, data) { if (!first) appendStringInfoString(es->str, ", "); appendStringInfoString(es->str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->str, '\n'); break; case EXPLAIN_FORMAT_XML: ExplainXMLTag(qlabel, X_OPENING, es); foreach (lc, data) { char* str = NULL; appendStringInfoSpaces(es->str, es->indent * 2 + 2); appendStringInfoString(es->str, "<Item>"); str = escape_xml((const char*)lfirst(lc)); appendStringInfoString(es->str, str); pfree_ext(str); appendStringInfoString(es->str, "</Item>\n"); } ExplainXMLTag(qlabel, X_CLOSING, es); break; case EXPLAIN_FORMAT_JSON: ExplainJSONLineEnding(es); appendStringInfoSpaces(es->str, es->indent * 2); escape_json(es->str, qlabel); appendStringInfoString(es->str, ": ["); foreach (lc, data) { if (!first) appendStringInfoString(es->str, ", "); escape_json(es->str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->str, ']'); break; case EXPLAIN_FORMAT_YAML: ExplainYAMLLineStarting(es); appendStringInfo(es->str, "%s: ", qlabel); foreach (lc, data) { appendStringInfoChar(es->str, '\n'); appendStringInfoSpaces(es->str, es->indent * 2 + 2); appendStringInfoString(es->str, "- "); escape_yaml(es->str, (const char*)lfirst(lc)); } break; default: break; } } /* * Explain a property that takes the form of a list of unlabeled items within * another list. "data" is a list of C strings. */ void ExplainPropertyListNested(const char* qlabel, List* data, ExplainState* es) { ListCell* lc = NULL; bool first = true; switch (es->format) { case EXPLAIN_FORMAT_TEXT: case EXPLAIN_FORMAT_XML: ExplainPropertyList(qlabel, data, es); return; case EXPLAIN_FORMAT_JSON: ExplainJSONLineEnding(es); appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfoChar(es->str, '['); foreach (lc, data) { if (!first) appendStringInfoString(es->str, ", "); escape_json(es->str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->str, ']'); break; case EXPLAIN_FORMAT_YAML: ExplainYAMLLineStarting(es); appendStringInfoString(es->str, "- ["); foreach (lc, data) { if (!first) appendStringInfoString(es->str, ", "); escape_yaml(es->str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->str, ']'); break; default: break; } } /* * Explain a simple property. * * If "numeric" is true, the value is a number (or other value that * doesn't need quoting in JSON). * * This usually should not be invoked directly, but via one of the datatype * specific routines ExplainPropertyText, ExplainPropertyInteger, etc. */ static void ExplainProperty(const char* qlabel, const char* value, bool numeric, ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: if (es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, *es->wlm_statistics_plan_max_digit); appendStringInfoString(es->str, " | "); appendStringInfoSpaces(es->str, es->indent); } else { appendStringInfoSpaces(es->str, es->indent * 2); } appendStringInfo(es->str, "%s: %s\n", qlabel, value); break; case EXPLAIN_FORMAT_XML: { char* str = NULL; appendStringInfoSpaces(es->str, es->indent * 2); ExplainXMLTag(qlabel, X_OPENING | X_NOWHITESPACE, es); str = escape_xml(value); appendStringInfoString(es->str, str); pfree_ext(str); ExplainXMLTag(qlabel, X_CLOSING | X_NOWHITESPACE, es); appendStringInfoChar(es->str, '\n'); } break; case EXPLAIN_FORMAT_JSON: ExplainJSONLineEnding(es); appendStringInfoSpaces(es->str, es->indent * 2); escape_json(es->str, qlabel); appendStringInfoString(es->str, ": "); if (numeric) appendStringInfoString(es->str, value); else escape_json(es->str, value); break; case EXPLAIN_FORMAT_YAML: ExplainYAMLLineStarting(es); appendStringInfo(es->str, "%s: ", qlabel); if (numeric) appendStringInfoString(es->str, value); else escape_yaml(es->str, value); break; default: break; } } /* * Explain a string-valued property. */ void ExplainPropertyText(const char* qlabel, const char* value, ExplainState* es) { ExplainProperty(qlabel, value, false, es); } /* * Explain an integer-valued property. */ void ExplainPropertyInteger(const char* qlabel, int value, ExplainState* es) { char buf[32]; errno_t rc = snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%d", value); securec_check_ss(rc, "\0", "\0"); ExplainProperty(qlabel, buf, true, es); } /* * Explain a long-integer-valued property. */ void ExplainPropertyLong(const char* qlabel, long value, ExplainState* es) { char buf[32]; errno_t rc = snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%ld", value); securec_check_ss(rc, "\0", "\0"); ExplainProperty(qlabel, buf, true, es); } /* * Explain a float-valued property, using the specified number of * fractional digits. */ void ExplainPropertyFloat(const char* qlabel, double value, int ndigits, ExplainState* es) { char buf[256]; errno_t rc = snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%.*f", ndigits, value); securec_check_ss(rc, "\0", "\0"); ExplainProperty(qlabel, buf, true, es); } /* * Open a group of related objects. * * objtype is the type of the group object, labelname is its label within * a containing object (if any). * * If labeled is true, the group members will be labeled properties, * while if it's false, they'll be unlabeled objects. */ static void ExplainOpenGroup(const char* objtype, const char* labelname, bool labeled, ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* nothing to do */ break; case EXPLAIN_FORMAT_XML: ExplainXMLTag(objtype, X_OPENING, es); es->indent++; break; case EXPLAIN_FORMAT_JSON: ExplainJSONLineEnding(es); appendStringInfoSpaces(es->str, 2 * es->indent); if (labelname != NULL) { escape_json(es->str, labelname); appendStringInfoString(es->str, ": "); } appendStringInfoChar(es->str, labeled ? '{' : '['); /* * In JSON format, the grouping_stack is an integer list. 0 means * we've emitted nothing at this grouping level, 1 means we've * emitted something (and so the next item needs a comma). See * ExplainJSONLineEnding(). */ es->grouping_stack = lcons_int(0, es->grouping_stack); es->indent++; break; case EXPLAIN_FORMAT_YAML: /* * In YAML format, the grouping stack is an integer list. 0 means * we've emitted nothing at this grouping level AND this grouping * level is unlabelled and must be marked with "- ". See * ExplainYAMLLineStarting(). */ ExplainYAMLLineStarting(es); if (labelname != NULL) { appendStringInfo(es->str, "%s: ", labelname); es->grouping_stack = lcons_int(1, es->grouping_stack); } else { appendStringInfoString(es->str, "- "); es->grouping_stack = lcons_int(0, es->grouping_stack); } es->indent++; break; default: break; } } /* * Close a group of related objects. * Parameters must match the corresponding ExplainOpenGroup call. */ static void ExplainCloseGroup(const char* objtype, const char* labelname, bool labeled, ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* nothing to do */ break; case EXPLAIN_FORMAT_XML: es->indent--; ExplainXMLTag(objtype, X_CLOSING, es); break; case EXPLAIN_FORMAT_JSON: es->indent--; appendStringInfoChar(es->str, '\n'); appendStringInfoSpaces(es->str, 2 * es->indent); appendStringInfoChar(es->str, labeled ? '}' : ']'); es->grouping_stack = list_delete_first(es->grouping_stack); break; case EXPLAIN_FORMAT_YAML: es->indent--; es->grouping_stack = list_delete_first(es->grouping_stack); break; default: break; } } /* * Emit a "dummy" group that never has any members. * * objtype is the type of the group object, labelname is its label within * a containing object (if any). */ static void ExplainDummyGroup(const char* objtype, const char* labelname, ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* nothing to do */ break; case EXPLAIN_FORMAT_XML: ExplainXMLTag(objtype, X_CLOSE_IMMEDIATE, es); break; case EXPLAIN_FORMAT_JSON: ExplainJSONLineEnding(es); appendStringInfoSpaces(es->str, 2 * es->indent); if (labelname != NULL) { escape_json(es->str, labelname); appendStringInfoString(es->str, ": "); } escape_json(es->str, objtype); break; case EXPLAIN_FORMAT_YAML: ExplainYAMLLineStarting(es); if (labelname != NULL) { escape_yaml(es->str, labelname); appendStringInfoString(es->str, ": "); } else { appendStringInfoString(es->str, "- "); } escape_yaml(es->str, objtype); break; default: break; } } /* * Emit the start-of-output boilerplate. * * This is just enough different from processing a subgroup that we need * a separate pair of subroutines. */ void ExplainBeginOutput(ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* nothing to do */ break; case EXPLAIN_FORMAT_XML: appendStringInfoString(es->str, "<explain xmlns=\"http://www.postgresql.org/2009/explain\">\n"); es->indent++; break; case EXPLAIN_FORMAT_JSON: /* top-level structure is an array of plans */ appendStringInfoChar(es->str, '['); es->grouping_stack = lcons_int(0, es->grouping_stack); es->indent++; break; case EXPLAIN_FORMAT_YAML: es->grouping_stack = lcons_int(0, es->grouping_stack); break; default: break; } } /* * Emit the end-of-output boilerplate. */ void ExplainEndOutput(ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* nothing to do */ break; case EXPLAIN_FORMAT_XML: es->indent--; appendStringInfoString(es->str, "</explain>"); break; case EXPLAIN_FORMAT_JSON: es->indent--; appendStringInfoString(es->str, "\n]"); es->grouping_stack = list_delete_first(es->grouping_stack); break; case EXPLAIN_FORMAT_YAML: es->grouping_stack = list_delete_first(es->grouping_stack); break; default: break; } } /* * Put an appropriate separator between multiple plans */ void ExplainSeparatePlans(ExplainState* es) { switch (es->format) { case EXPLAIN_FORMAT_TEXT: /* add a blank line */ appendStringInfoChar(es->str, '\n'); break; case EXPLAIN_FORMAT_XML: case EXPLAIN_FORMAT_JSON: case EXPLAIN_FORMAT_YAML: /* nothing to do */ break; default: break; } } #ifdef PGXC /* * Emit execution node list number. */ static void ExplainExecNodes(const ExecNodes* en, ExplainState* es) { int primary_node_count = en ? list_length(en->primarynodelist) : 0; int node_count = en ? list_length(en->nodeList) : 0; if (!es->num_nodes) return; if (es->format == EXPLAIN_FORMAT_TEXT) { appendStringInfo(es->str, " (primary node count=%d, node count=%d)", primary_node_count, node_count); } else { ExplainPropertyInteger("Primary node count", primary_node_count, es); ExplainPropertyInteger("Node count", node_count, es); } } static void showStreamnetwork(Stream* stream, ExplainState* es) { Instrumentation* instr = NULL; Plan* plan = (Plan*)stream; long spacePeakKb = 0; double toltal_time = 0; double deserialize_time = 0; double copy_time = 0; if (u_sess->instr_cxt.global_instr && es->planinfo->m_runtimeinfo) { int dop = ((Plan*)stream)->parallel_enabled ? u_sess->opt_cxt.query_dop : 1; for (int i = 0; i < u_sess->instr_cxt.global_instr->getInstruNodeNum(); i++) { #ifdef ENABLE_MULTIPLE_NODES char* node_name = PGXCNodeGetNodeNameFromId(i, PGXC_NODE_DATANODE); #else char* node_name = g_instance.exec_cxt.nodeName; #endif for (int j = 0; j < dop; j++) { instr = u_sess->instr_cxt.global_instr->getInstrSlot(i, plan->plan_node_id, j); if (instr == NULL) continue; spacePeakKb = (instr->network_perfdata.network_size + 1023) / 1024; toltal_time = instr->network_perfdata.total_poll_time; deserialize_time = instr->network_perfdata.total_deserialize_time; copy_time = instr->network_perfdata.total_copy_time; es->planinfo->m_runtimeinfo->put(i, j, QUERY_NETWORK, spacePeakKb); es->planinfo->m_runtimeinfo->put(i, j, NETWORK_POLL_TIME, Float8GetDatum(toltal_time)); es->planinfo->m_query_summary->m_size += instr->network_perfdata.network_size; es->planinfo->m_staticInfo->set_plan_name<false, true>(); es->planinfo->m_staticInfo->set_datanode_name(node_name, j, dop); /* Local stream transfer through memory rather than net. */ if (!STREAM_IS_LOCAL_NODE(stream->smpDesc.distriType)) appendStringInfo(es->planinfo->m_staticInfo->info_str, "Stream Network: %ldkB, ", spacePeakKb); appendStringInfo(es->planinfo->m_staticInfo->info_str, "Network Poll Time: %.3f", toltal_time); if (copy_time > 0.0) appendStringInfo(es->planinfo->m_staticInfo->info_str, "; Data Copy Time: %.3f\n", copy_time); else appendStringInfo( es->planinfo->m_staticInfo->info_str, "; Data Deserialize Time: %.3f\n", deserialize_time); } } } } /* * ShowRunNodeInfo * show exec node information, including group name and node list * * @param (in) en: * the exec nodes * @param (in) es: * the explain state * @param (in) qlabel: * the leading label of this item in explain information * * @return: void */ static void ShowRunNodeInfo(const ExecNodes* en, ExplainState* es, const char* qlabel) { if (en != NULL && es->nodes) { StringInfo node_names = makeStringInfo(); #ifdef ENABLE_MULTIPLE_NODES if (list_length(en->nodeList) == u_sess->pgxc_cxt.NumDataNodes) { appendStringInfo(node_names, "All datanodes"); } else { ListCell* lcell = NULL; char* sep = ""; int node_no; /* we show group name information except in single installation group scenario */ if (ng_enable_nodegroup_explain()) { char* group_name = ng_get_dist_group_name((Distribution*)&(en->distribution)); appendStringInfo(node_names, "(%s) ", group_name); } foreach (lcell, en->nodeList) { NameData nodename = {{0}}; node_no = lfirst_int(lcell); appendStringInfo(node_names, "%s%s", sep, get_pgxc_nodename(PGXCNodeGetNodeOid(node_no, PGXC_NODE_DATANODE), &nodename)); sep = ", "; } } #else appendStringInfo(node_names, "All datanodes"); #endif ExplainPropertyText(qlabel, node_names->data, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_verboseInfo->info_str, "%s: %s\n", qlabel, node_names->data); } } } /* * ShowStreamRunNodeInfo * show the stream thread spawn on which node, * also include consumer nodes. * * @param (in) stream: * the stream node * @param (in) es: * the explain state * * @return: void */ static void ShowStreamRunNodeInfo(Stream* stream, ExplainState* es) { ExecNodes* en = stream->scan.plan.exec_nodes; ShowRunNodeInfo(en, es, "Spawn on"); /* show consumerNodes */ if (es->nodes && es->verbose) { ExecNodes* cen = stream->consumer_nodes; ShowRunNodeInfo(cen, es, "Consumer Nodes"); } } /* * Emit remote query planning details */ static void ExplainRemoteQuery(RemoteQuery* plan, PlanState* planstate, List* ancestors, ExplainState* es) { ExecNodes* en = plan->exec_nodes; const char* label_name = NULL; if (es->format == EXPLAIN_FORMAT_TEXT) { label_name = "Node/s"; } else { label_name = "Nodes"; } /* add names of the nodes if they exist */ if (en != NULL && es->nodes && plan->position == GATHER) { StringInfo node_names = makeStringInfo(); ListCell* lcell = NULL; char* sep = NULL; int node_no; if (en->primarynodelist) { if (plan->exec_type == EXEC_ON_ALL_NODES) { appendStringInfo(node_names, "All nodes"); } else { char exec_node_type = (plan->exec_type == EXEC_ON_DATANODES) ? (PGXC_NODE_DATANODE) : (PGXC_NODE_COORDINATOR); sep = ""; foreach (lcell, en->primarynodelist) { NameData nodename = {{0}}; node_no = lfirst_int(lcell); appendStringInfo(node_names, "%s%s", sep, get_pgxc_nodename(PGXCNodeGetNodeOid(node_no, exec_node_type), &nodename)); sep = ", "; } } if (es->format == EXPLAIN_FORMAT_TEXT) { ExplainPropertyText("Primary node/s", node_names->data, es); } else { ExplainPropertyText("Primary nodes", node_names->data, es); } } if (en->nodeList) { resetStringInfo(node_names); if (list_length(en->nodeList) == u_sess->pgxc_cxt.NumDataNodes) { appendStringInfo(node_names, "All datanodes"); es->datanodeinfo.all_datanodes = true; } else { char exec_node_type = (plan->exec_type == EXEC_ON_DATANODES) ? (PGXC_NODE_DATANODE) : (PGXC_NODE_COORDINATOR); es->datanodeinfo.all_datanodes = false; es->datanodeinfo.len_nodelist = list_length(en->nodeList); if (es->datanodeinfo.node_index) { pfree_ext(es->datanodeinfo.node_index); es->datanodeinfo.node_index = NULL; } if (es->datanodeinfo.node_index == NULL) es->datanodeinfo.node_index = (int*)palloc0(sizeof(int) * es->datanodeinfo.len_nodelist); sep = ""; /* we show group name information except in single installation group scenario */ if (ng_enable_nodegroup_explain()) { char* group_name = ng_get_dist_group_name(&(en->distribution)); appendStringInfo(node_names, "(%s) ", group_name); } int i = 0; foreach (lcell, en->nodeList) { NameData nodename = {{0}}; node_no = lfirst_int(lcell); es->datanodeinfo.node_index[i++] = node_no; appendStringInfo(node_names, "%s%s", sep, get_pgxc_nodename(PGXCNodeGetNodeOid(node_no, exec_node_type), &nodename)); sep = ", "; } } ExplainPropertyText(label_name, node_names->data, es); if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_verboseInfo->info_str, "Node/s: %s\n", node_names->data); } } } if (plan->position == SCAN_GATHER) { ExplainPropertyText(label_name, "DNs in compute pool", es); } if (plan->position == PLAN_ROUTER) { StringInfo address = makeStringInfo(); Plan* fsplan = get_foreign_scan((Plan*)plan); ServerTypeOption srvtype = getServerType(((ForeignScan*)fsplan)->scan_relid); if (T_OBS_SERVER == srvtype || T_TXT_CSV_OBS_SERVER == srvtype) { ComputePoolConfig** conf = get_cp_conninfo(); appendStringInfo(address, "%s:%s", conf[0]->cpip, conf[0]->cpport); } else { // T_HDFS_SERVER DummyServerOptions* options = getDummyServerOption(); AssertEreport(options != NULL, MOD_EXECUTOR, "unexpect null value"); appendStringInfo(address, "%s", options->address); AssertEreport(address != NULL, MOD_EXECUTOR, "unexpect null value"); } StringInfo si = makeStringInfo(); appendStringInfo(si, "compute pool: %s", address->data); ExplainPropertyText(label_name, si->data, es); } if (en != NULL && en->en_expr && es->pstmt->commandType != CMD_MERGE) show_expression((Node*)en->en_expr, "Node expr", planstate, ancestors, es->verbose, es); else if (en != NULL && en->en_expr && es->pstmt->commandType == CMD_MERGE) { ListCell* lc = NULL; int cnt = 0; StringInfo si = makeStringInfo(); /* the var in merge into en_expr point to the insert cols on the plan's targetlist */ foreach (lc, en->en_expr) { if (IsA(lfirst(lc), Var)) { Var* var = (Var*)lfirst(lc); /* we show it as $%d as it point to the plan's targetlist */ if (cnt == 0) appendStringInfo(si, "$%d", var->varattno); else appendStringInfo(si, ", $%d", var->varattno); cnt++; } } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_detailInfo) { es->planinfo->m_detailInfo->set_plan_name<true, true>(); appendStringInfo(es->planinfo->m_detailInfo->info_str, "%s: %s\n", "Node expr: ", si->data); } /* And add to es->str */ ExplainPropertyText("Node expr", si->data, es); } /* Remote query statement */ if (es->verbose && !plan->is_simple) ExplainPropertyText("Remote query", plan->sql_statement, es); } #endif /* * Emit opening or closing XML tag. * * "flags" must contain X_OPENING, X_CLOSING, or X_CLOSE_IMMEDIATE. * Optionally, OR in X_NOWHITESPACE to suppress the whitespace we'd normally * add. * * XML tag names can't contain white space, so we replace any spaces in * "tagname" with dashes. */ static void ExplainXMLTag(const char* tagname, unsigned int flags, ExplainState* es) { const char* s = NULL; if ((flags & X_NOWHITESPACE) == 0) appendStringInfoSpaces(es->str, 2 * es->indent); appendStringInfoCharMacro(es->str, '<'); if ((flags & X_CLOSING) != 0) appendStringInfoCharMacro(es->str, '/'); for (s = tagname; *s; s++) appendStringInfoCharMacro(es->str, (*s == ' ') ? '-' : *s); if ((flags & X_CLOSE_IMMEDIATE) != 0) appendStringInfoString(es->str, " /"); appendStringInfoCharMacro(es->str, '>'); if ((flags & X_NOWHITESPACE) == 0) appendStringInfoCharMacro(es->str, '\n'); } /* * Emit a JSON line ending. * * JSON requires a comma after each property but the last. To facilitate this, * in JSON format, the text emitted for each property begins just prior to the * preceding line-break (and comma, if applicable). */ static void ExplainJSONLineEnding(ExplainState* es) { AssertEreport(es->format == EXPLAIN_FORMAT_JSON, MOD_EXECUTOR, "unexpect explain state format"); if (linitial_int(es->grouping_stack) != 0) appendStringInfoChar(es->str, ','); else linitial_int(es->grouping_stack) = 1; appendStringInfoChar(es->str, '\n'); } /* * Indent a YAML line. * * YAML lines are ordinarily indented by two spaces per indentation level. * The text emitted for each property begins just prior to the preceding * line-break, except for the first property in an unlabelled group, for which * it begins immediately after the "- " that introduces the group. The first * property of the group appears on the same line as the opening "- ". */ static void ExplainYAMLLineStarting(ExplainState* es) { AssertEreport(es->format == EXPLAIN_FORMAT_YAML, MOD_EXECUTOR, "unexpect explain state format"); if (linitial_int(es->grouping_stack) == 0) { linitial_int(es->grouping_stack) = 1; } else { appendStringInfoChar(es->str, '\n'); appendStringInfoSpaces(es->str, es->indent * 2); } } /* * YAML is a superset of JSON; unfortuantely, the YAML quoting rules are * ridiculously complicated -- as documented in sections 5.3 and 7.3.3 of * http://yaml.org/spec/1.2/spec.html -- so we chose to just quote everything. * Empty strings, strings with leading or trailing whitespace, and strings * containing a variety of special characters must certainly be quoted or the * output is invalid; and other seemingly harmless strings like "0xa" or * "true" must be quoted, lest they be interpreted as a hexadecimal or Boolean * constant rather than a string. */ static void escape_yaml(StringInfo buf, const char* str) { escape_json(buf, str); } #ifndef ENABLE_MULTIPLE_NODES static void SetPredictor(ExplainState* es, PlanTable* m_planInfo) { if (es->opt_model_name != NULL) { /* look up gs_opt_model for predictor's targets */ char *labels = NULL; int nLabel; (void) CheckModelTargets(RLSTM_TEMPLATE_NAME, es->opt_model_name, &labels, &nLabel); for (int i = 0; i < nLabel; ++i) { switch (labels[i]) { case gs_opt_model_label_total_time: { m_planInfo->m_pred_time = true; break; } case gs_opt_model_label_rows: { m_planInfo->m_pred_row = true; break; } case gs_opt_model_label_peak_memory: { m_planInfo->m_pred_mem = true; break; } default: /* keep compiler silent */ break; } } } } #endif void PlanInformation::init(ExplainState* es, int plansize, int num_nodes, bool query_mem_mode) { m_detail = es->detail; m_planInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_planInfo->m_costs = es->costs; m_planInfo->m_verbose = es->verbose; m_planInfo->m_cpu = false; m_planInfo->m_analyze = es->analyze; m_planInfo->m_timing = es->timing; /* determine which prediction columns should be made visible */ m_planInfo->m_pred_time = false; m_planInfo->m_pred_row = false; m_planInfo->m_pred_mem = false; #ifndef ENABLE_MULTIPLE_NODES SetPredictor(es, m_planInfo); #endif if (m_planInfo->m_costs) m_planInfo->m_query_mem_mode = query_mem_mode; m_planInfo->init(PLANINFO); m_planInfo->init_planinfo(plansize); m_detailInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_detailInfo->init(DETAILINFO); m_query_summary = (PlanTable*)palloc0(sizeof(PlanTable)); m_query_summary->init(QUERYSUMMARY); /* Init data struct for explain plan. */ if (es->plan) { m_planTableData = (PlanTable*)palloc0(sizeof(PlanTable)); if (IsExplainPlanSelectForUpdateStmt && plansize == 0) plansize = 1; m_planTableData->init_plan_table_data(plansize); } else m_planTableData = NULL; if (es->analyze) { m_staticInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_staticInfo->init(STATICINFO); m_profileInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_profileInfo->init(PROFILEINFO); } else { m_staticInfo = NULL; m_profileInfo = NULL; } if (es->verbose) { m_verboseInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_verboseInfo->init(VERBOSEINFO); } else m_verboseInfo = NULL; if (es->detail) { m_datanodeInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_datanodeInfo->init(DATANODEINFO); m_runtimeinfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_runtimeinfo->init(RUNTIMEINFO); m_runtimeinfo->init_multi_info(es, plansize, num_nodes); } else { m_datanodeInfo = NULL; m_runtimeinfo = NULL; } if ((es->cpu || es->buffers) && es->detail == false) { m_planInfo->m_cpu = true; m_IOInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_IOInfo->init(IOINFO); } else m_IOInfo = NULL; if (es->detail) { m_recursiveInfo = (PlanTable*)palloc0(sizeof(PlanTable)); m_recursiveInfo->init(RECURSIVEINFO); } else { m_recursiveInfo = NULL; } } void PlanInformation::append_str_info(const char* data, int id, const char* value) { if (m_verboseInfo) appendStringInfo(m_verboseInfo->info_str, data, id, value); if (m_datanodeInfo) appendStringInfo(m_datanodeInfo->info_str, data, id, value); } static void writefile(const char* path, char* text) { FILE* out_file = NULL; char* line = NULL; errno_t rc = 0; if ((out_file = fopen(path, "w")) == NULL) { return; } while (*text) { char* eol = NULL; int len; eol = strchr(text, '\n'); if (eol != NULL) { len = eol - text; eol++; } else { len = strlen(text); eol += len; } line = (char*)palloc0(sizeof(char) * (len + 2)); rc = memcpy_s(line, len, text, len); securec_check(rc, "\0", "\0"); line[len] = '\n'; if (fputs(line, out_file) < 0) { (void)fclose(out_file); return; } pfree_ext(line); text = eol; } if (fclose(out_file)) { return; } } void PlanInformation::dump_runtimeinfo_file() { int rc = 0; char tempdirpath[1024] = {0}; FILE* fp = NULL; bool is_absolute = false; if (u_sess->attr.attr_common.Perf_log == NULL) { is_absolute = is_absolute_path(u_sess->attr.attr_common.Log_directory); if (is_absolute) rc = snprintf_s(tempdirpath, sizeof(tempdirpath), sizeof(tempdirpath) - 1, "%s/explain_table_%d.csv", u_sess->attr.attr_common.Log_directory, m_query_id); else rc = snprintf_s(tempdirpath, sizeof(tempdirpath), sizeof(tempdirpath) - 1, "%s/pg_log/explain_table_%d.csv", g_instance.attr.attr_common.data_directory, m_query_id); } else { rc = snprintf_s( tempdirpath, sizeof(tempdirpath), sizeof(tempdirpath) - 1, "%s", u_sess->attr.attr_common.Perf_log); } securec_check_ss(rc, "\0", "\0"); fp = fopen(tempdirpath, PG_BINARY_W); if (fp == NULL) return; fclose(fp); m_runtimeinfo->flush_data_to_file(); writefile(tempdirpath, m_runtimeinfo->info_str->data); } void PlanInformation::free_memory() { if (m_planInfo) { pfree_ext(m_planInfo); m_planInfo = NULL; } if (m_detailInfo) { pfree_ext(m_detailInfo); m_detailInfo = NULL; } if (m_staticInfo) { pfree_ext(m_staticInfo); m_staticInfo = NULL; } if (m_verboseInfo) { pfree_ext(m_verboseInfo); m_verboseInfo = NULL; } if (m_datanodeInfo) { pfree_ext(m_datanodeInfo); m_datanodeInfo = NULL; } if (m_IOInfo) { pfree_ext(m_IOInfo); m_IOInfo = NULL; } if (m_profileInfo) { pfree_ext(m_profileInfo); m_profileInfo = NULL; } if (m_query_summary) { pfree_ext(m_query_summary); m_query_summary = NULL; } if (m_recursiveInfo) { pfree(m_recursiveInfo); m_recursiveInfo = NULL; } } int PlanInformation::print_plan(Portal portal, DestReceiver* dest) { m_count = 0; /* Do not print tupDesc and result '(xx rows)' for explain plan */ if (m_planTableData) { free_memory(); return m_count; } if (m_planInfo) m_count += m_planInfo->print_plan(portal, dest); if (m_detailInfo && m_detailInfo->m_size > 0) m_count += m_detailInfo->print_plan(portal, dest); if (m_staticInfo && m_staticInfo->m_size > 0) m_count += m_staticInfo->print_plan(portal, dest); if (m_verboseInfo && m_verboseInfo->m_size > 0) m_count += m_verboseInfo->print_plan(portal, dest); if (m_datanodeInfo && m_datanodeInfo->m_size > 0) m_count += m_datanodeInfo->print_plan(portal, dest); if (m_IOInfo && m_IOInfo->m_size) m_count += m_IOInfo->print_plan(portal, dest); if (m_recursiveInfo && m_recursiveInfo->m_size) m_count += m_recursiveInfo->print_plan(portal, dest); if (m_profileInfo && m_profileInfo->m_size > 0) m_count += m_profileInfo->print_plan(portal, dest); if (m_query_summary && m_query_summary->m_size > 0) m_count += m_query_summary->print_plan(portal, dest); free_memory(); return m_count; } void PlanTable::init(int plantype) { switch (plantype) { case PLANINFO: m_desc = getTupleDesc(); initStringInfo(&m_pname); break; case DETAILINFO: m_desc = getTupleDesc("Predicate Information (identified by plan id)"); info_str = makeStringInfo(); break; case STATICINFO: m_desc = getTupleDesc("Memory Information (identified by plan id)"); info_str = makeStringInfo(); break; case VERBOSEINFO: m_desc = getTupleDesc("Targetlist Information (identified by plan id)"); info_str = makeStringInfo(); break; case DATANODEINFO: m_desc = getTupleDesc("Datanode Information (identified by plan id)"); info_str = makeStringInfo(); break; case IOINFO: m_desc = getTupleDesc("Cpu-Buffer Information (identified by plan id)"); info_str = makeStringInfo(); break; case RUNTIMEINFO: m_desc = getTupleDesc_detail(); info_str = makeStringInfo(); break; case PROFILEINFO: m_desc = getTupleDesc("User Define Profiling"); info_str = makeStringInfo(); break; case RECURSIVEINFO: m_desc = getTupleDesc("Recursive Union Plan node (identified by plan id)"); info_str = makeStringInfo(); break; case QUERYSUMMARY: m_desc = getTupleDesc("====== Query Summary ====="); info_str = makeStringInfo(); break; default: ereport(ERROR, (errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE), errmsg("unsupported type %d", plantype))); } } void PlanTable::init_multi_info(ExplainState* es, int plansize, int num_nodes) { int i = 0; int j = 0; m_plan_size = plansize; m_data_size = num_nodes; m_multi_info = (MultiInfo***)palloc0(sizeof(MultiInfo**) * m_data_size); for (i = 0; i < m_data_size; i++) { m_multi_info[i] = (MultiInfo**)palloc0(sizeof(MultiInfo*) * m_plan_size); for (j = 0; j < m_plan_size; j++) { int dop = u_sess->instr_cxt.global_instr->getNodeDop(j + 1); m_multi_info[i][j] = (MultiInfo*)palloc0(sizeof(MultiInfo) * dop); init_multi_info_data(m_multi_info[i][j], dop); } } } /* * @Description: init the data of MultiInfo * * @param[IN] multi_info: each element of m_multi_info * @param[IN] dop: dop of specific operator * @return: void */ void PlanTable::init_multi_info_data(MultiInfo* multi_info, int dop) { for (int i = 0; i < dop; i++) { multi_info[i].m_Datum = (Datum*)palloc0(EXPLAIN_TOTAL_ATTNUM * sizeof(Datum)); multi_info[i].m_Nulls = (bool*)palloc0(EXPLAIN_TOTAL_ATTNUM * sizeof(bool)); for (int j = 0; j < EXPLAIN_TOTAL_ATTNUM; j++) multi_info[i].m_Nulls[j] = true; } } void PlanTable::init_planinfo(int plansize) { int i = 0; int j = 0; m_size = plansize; int attnum; int analyze_num = m_analyze ? 1 : 0; int costs_num = m_costs ? 1 : 0; int verbose_num = m_verbose ? 1 : 0; attnum = (PLAN + 1) + analyze_num * NUM_ANALYZE_COLS + \ costs_num * (NUM_COST_COLS + verbose_num * NUM_VER_COLS + m_pred_time + m_pred_row + m_pred_mem); /* If cost enabled and not query mem mode, don't show estimate_memory column */ if (m_costs && !m_query_mem_mode) attnum = attnum - 1; m_data = (Datum**)palloc0(plansize * sizeof(Datum*)); m_isnull = (bool**)palloc0(plansize * sizeof(bool*)); for (i = 0; i < plansize; i++) { m_data[i] = (Datum*)palloc0(attnum * sizeof(Datum)); m_isnull[i] = (bool*)palloc0(attnum * sizeof(bool)); for (j = 0; j < attnum; j++) m_isnull[i][j] = true; } } /* * Description: Init data struct for plan table according to plan size. * * Parameters: * @in num_plan_nodes: number of plan node. * Return: void */ void PlanTable::init_plan_table_data(int num_plan_nodes) { int i = 0; errno_t rc = EOK; /* for query shipping we do not collect plan info. */ if (num_plan_nodes == 0) return; m_plan_node_num = num_plan_nodes; /* palloc memory for every node */ m_plan_table = (PlanTableMultiData**)palloc0(num_plan_nodes * sizeof(PlanTableMultiData*)); for (i = 0; i < num_plan_nodes; i++) { m_plan_table[i] = (PlanTableMultiData*)palloc0(sizeof(PlanTableMultiData)); m_plan_table[i]->m_datum = (PlanTableData*)palloc0(sizeof(PlanTableData)); m_plan_table[i]->m_isnull = (bool*)palloc0(PLANTABLECOLNUM * sizeof(bool)); /* init m_isnull */ rc = memset_s(m_plan_table[i]->m_isnull, PLANTABLECOLNUM * sizeof(bool), 1, PLANTABLECOLNUM * sizeof(bool)); securec_check(rc, "\0", "\0"); } } TupleDesc PlanTable::getTupleDesc() { TupleDesc tupdesc; int attnum; int cur = 1; int analyze_num = m_analyze ? 1 : 0; int costs_num = m_costs ? 1 : 0; int verbose_num = m_verbose ? 1 : 0; attnum = (PLAN + 1) + analyze_num * NUM_ANALYZE_COLS + \ costs_num * (NUM_COST_COLS + verbose_num * NUM_VER_COLS + m_pred_time + m_pred_row + m_pred_mem); /* If cost enabled and not query mem mode, don't show estimate_memory column */ if (m_costs && !m_query_mem_mode) attnum = attnum - 1; /* If timing not enabled, don't show A-time column */ if (!m_timing && m_analyze) { attnum = attnum - 1; } tupdesc = CreateTemplateTupleDesc(attnum, false, TAM_HEAP); for (int i = 0; i < SLOT_NUMBER; i++) { bool add_slot = false; /* Figure out whether current column should be added */ if (i <= PLAN) add_slot = true; else if (m_analyze && plan_table_cols[i].disoption == ANAL_OPT) { if (!m_timing && plan_table_cols[i].val == ACTUAL_TIME) { add_slot = false; } else { add_slot = true; } } else if (m_costs && plan_table_cols[i].disoption == COST_OPT) { if (m_query_mem_mode || i != ESTIMATE_MEMORY) add_slot = true; } else if (m_costs && (m_verbose && plan_table_cols[i].disoption == VERBOSE_OPT)) { /* cost opt controls distinct display */ add_slot = true; } else if (m_costs && (m_pred_time && plan_table_cols[i].disoption == PRED_OPT_TIME)) { add_slot = true; } else if (m_costs && (m_pred_row && plan_table_cols[i].disoption == PRED_OPT_ROW)) { add_slot = true; } else if (m_costs && (m_pred_mem && plan_table_cols[i].disoption == PRED_OPT_MEM)) { add_slot = true; } if (add_slot) { TupleDescInitEntry(tupdesc, (AttrNumber)cur, plan_table_cols[i].name, plan_table_cols[i].typid, -1, 0); m_col_loc[i] = cur - 1; cur++; } else m_col_loc[i] = -1; } return tupdesc; } TupleDesc PlanTable::getTupleDesc_detail() { TupleDesc tupdesc; int attnum = EXPLAIN_TOTAL_ATTNUM; int i = 1; tupdesc = CreateTemplateTupleDesc(attnum, false, TAM_HEAP); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "query id", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "plan parent node id", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "plan node id", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "plan type", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "from datanode", BOOLOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "node name", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "plan name", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "start time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "total time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "oper time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "plan rows", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "loops", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "ex cyc", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "inc cyc", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "ex cyc/rows", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "memory", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "peak query memory", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "shared hit", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "shared read", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "shared dirtied", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "shared written", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "local hit", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "local read", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "local dirtied", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "local written", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "temp read", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "temp written", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "blk read time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "blk write time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "CU None", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "CU Some", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "sort method", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "sort type", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "sort space", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "hash batch", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "hash batch orignal", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "hash bucket", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "hash space", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "hash file number", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "query network", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "network poll time", FLOAT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "llvm optimization", BOOLOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "bloom filter", BOOLOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "dfs block info", BOOLOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "merge inserted", INT8OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber)i++, "merge updated", INT8OID, -1, 0); return tupdesc; } TupleDesc PlanTable::getTupleDesc(const char* attname) { TupleDesc tupdesc; tupdesc = CreateTemplateTupleDesc(1, false, TAM_HEAP); TupleDescInitEntry(tupdesc, (AttrNumber)1, attname, TEXTOID, -1, 0); return tupdesc; } void PlanTable::put(int type, Datum value) { AssertEreport(type < SLOT_NUMBER && m_col_loc[type] >= 0, MOD_EXECUTOR, "unexpect input value"); m_data[m_plan_node_id - 1][m_col_loc[type]] = value; m_isnull[m_plan_node_id - 1][m_col_loc[type]] = false; } void PlanTable::put(int nodeId, int smpId, int type, Datum value) { if (nodeId == -1) { for (int i = 0; i < m_data_size; i++) { int dop = u_sess->instr_cxt.global_instr->getNodeDop(m_plan_node_id); for (int j = 0; j < dop; j++) { m_multi_info[i][m_plan_node_id - 1][j].m_Datum[type] = value; m_multi_info[i][m_plan_node_id - 1][j].m_Nulls[type] = false; } } } else { m_multi_info[nodeId][m_plan_node_id - 1][smpId].m_Datum[type] = value; m_multi_info[nodeId][m_plan_node_id - 1][smpId].m_Nulls[type] = false; } } void PlanTable::flush(DestReceiver* dest, int plantype) { TupOutputState* tstate = NULL; tstate = begin_tup_output_tupdesc(dest, m_desc); switch (plantype) { case PLANINFO: flush_plan(tstate); break; case DETAILINFO: case STATICINFO: case VERBOSEINFO: case DATANODEINFO: case IOINFO: case PROFILEINFO: case RECURSIVEINFO: case QUERYSUMMARY: flush_other(tstate); break; default: ereport(ERROR, (errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE), errmsg("unsupported type %d", plantype))); } end_tup_output(tstate); } int PlanTable::print_plan(Portal portal, DestReceiver* dest) { TupleTableSlot* slot = NULL; int current_tuple_count = 0; portal->tupDesc = m_desc; slot = MakeSingleTupleTableSlot(portal->tupDesc); current_tuple_count = RunGetSlotFromExplain(portal, slot, dest, m_size); ExecDropSingleTupleTableSlot(slot); return current_tuple_count; } void PlanTable::flush_plan(TupOutputState* tstate) { int i = 0; for (i = 0; i < m_size; i++) { do_tup_output(tstate, m_data[i], tstate->slot->tts_tupleDescriptor->natts, m_isnull[i], tstate->slot->tts_tupleDescriptor->natts); pfree_ext(m_data[i]); pfree_ext(m_isnull[i]); } pfree_ext(m_data); pfree_ext(m_isnull); pfree_ext(m_pname.data); } void PlanTable::flush_other(TupOutputState* tstate) { m_size = do_text_output_multiline(tstate, info_str->data); pfree_ext(info_str->data); } void PlanTable::set_pname(char* data) { m_pname.data = data; } /* * @Description: set datanode name * @in nodename - current datanode name to be set * @in smp_idx - current smp index * @in dop - degree of parallel, 1 means not parallel * @out - void */ void PlanTable::set_datanode_name(char* nodename, int smp_idx, int dop) { if (dop == 1) appendStringInfo(info_str, "%s ", nodename); else appendStringInfo(info_str, "%s[worker %d] ", nodename, smp_idx); } template <bool set_name, bool set_space> void PlanTable::set_plan_name() { if (set_name) { if (m_has_write_planname == false) { appendStringInfo(info_str, "%3d --%s\n", m_plan_node_id, m_pname.data); m_has_write_planname = true; } } if (set_space) { appendStringInfoSpaces(info_str, 8); } } /* --------------------------------function for explain plan--------------------- */ /* * Description: Transform the vaules into upper case. * Parameters: * @in str: string wait transform. * @in len: transform length. * Return: void */ static char* set_strtoupper(const char* str, uint32 len) { if (str == NULL) return NULL; uint32 out_len = 0; if (len < strlen(str)) out_len = len; else out_len = strlen(str); char* ptrout = (char*)palloc0(out_len + 1); for (uint32 i = 0; i < out_len; i++) ptrout[i] = pg_toupper((unsigned char)str[i]); ptrout[out_len] = '\0'; return ptrout; } /* * Description: Make session id and prepare to insert. * Session id is make up of thread start time and thread pid. * Parameters: * @in sessid: session_id. * Return: void */ void PlanTable::make_session_id(char* sessid) { AssertEreport(sessid != NULL, MOD_EXECUTOR, "unexpect null value"); errno_t rc = EOK; rc = snprintf_s(sessid, SESSIONIDLEN, SESSIONIDLEN - 1, "%ld.%lu", IS_THREAD_POOL_WORKER ? u_sess->proc_cxt.MyProcPort->SessionStartTime : t_thrd.proc_cxt.MyStartTime, IS_THREAD_POOL_WORKER ? u_sess->session_id : t_thrd.proc_cxt.MyProcPid); securec_check_ss(rc, "\0", "\0"); } /* * Description: Set session_id, user_id, statement_id, query_id and plan node id for the query. * Parameters: * @in query_id: query id of current plan. * @in es: explain state. * Return: void */ void PlanTable::set_plan_table_ids(uint64 query_id, ExplainState* es) { for (int i = 0; i < m_plan_node_num; i++) { make_session_id(m_plan_table[i]->m_datum->session_id); m_plan_table[i]->m_isnull[PT_SESSION_ID] = false; m_plan_table[i]->m_datum->user_id = GetCurrentUserId(); m_plan_table[i]->m_isnull[PT_USER_ID] = false; /* Print error when statement_id that user input exceeded the STMTIDLEN. */ if (es->statement_id != NULL) { uint32 s_len = strlen(es->statement_id); if (s_len > (STMTIDLEN - 1)) ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("statement_id is too long. Input statement_id length=%u, however max length=%d.", s_len, STMTIDLEN - 1))); errno_t rc = strncpy_s(m_plan_table[i]->m_datum->statement_id, STMTIDLEN, es->statement_id, s_len); securec_check(rc, "\0", "\0"); m_plan_table[i]->m_isnull[PT_STATEMENT_ID] = false; } m_plan_table[i]->m_datum->query_id = u_sess->debug_query_id; m_plan_table[i]->m_isnull[PT_QUERY_ID] = false; m_plan_table[i]->m_datum->node_id = i + 1; m_plan_table[i]->m_isnull[PT_NODE_ID] = false; } } /* * Description: Set operation and options for remote query and stream node. * Parameters: * @in pname: plain description for node. * @out operation: node operation. * @out options: node options. * Return: void */ void PlanTable::set_plan_table_streaming_ops(char* pname, char** operation, char** options) { errno_t rc = EOK; char* start = NULL; char* end = NULL; if (strncasecmp("Streaming", pname, strlen("Streaming")) == 0 || strncasecmp("Vector Streaming", pname, strlen("Vector Streaming")) == 0) { start = strrchr(pname, ':') + 2; end = strrchr(pname, ')'); uint32 option_len = end - start; *options = (char*)palloc0(option_len + 1); rc = memcpy_s(*options, option_len + 1, start, option_len); securec_check(rc, "\0", "\0"); if (pname[0] == 'S') *operation = "Streaming"; else *operation = "Vector Streaming"; } } /* * Description: For join node, we may need to set option 'CARTESIAN' to fit with A db. * Parameters: * @in plan: plan node. * @int options: node options. * Return: void */ void PlanTable::set_plan_table_join_options(Plan* plan, char** options) { switch (nodeTag(plan)) { case T_NestLoop: case T_VecNestLoop: { Join* nestloop = (Join*)plan; if (nestloop->joinqual == NULL) *options = "CARTESIAN"; } break; case T_VecMergeJoin: case T_MergeJoin: { MergeJoin* mergejoin = (MergeJoin*)plan; if (mergejoin->mergeclauses == NULL) *options = "CARTESIAN"; } break; case T_HashJoin: case T_VecHashJoin: { HashJoin* hashjoin = (HashJoin*)plan; if (hashjoin->hashclauses == NULL) *options = "CARTESIAN"; } break; default: break; } } /* * Description: Set operation and options for node except stream node. * Parameters: * @in plan_node_id: plan node id. * @int operation: node operation. * @int options: node options. * Return: void */ void PlanTable::set_plan_table_ops(int plan_node_id, char* operation, char* options) { errno_t rc = EOK; /* * for query shipping we do not collect plan info. * However we need collect plan info for select for update. */ if (plan_node_id == 0) { if (IsExplainPlanSelectForUpdateStmt) plan_node_id = 1; else return; } if (operation != NULL) { /* Transform the vaules into upper case. */ operation = set_strtoupper(operation, OPERATIONLEN); rc = strncpy_s(m_plan_table[plan_node_id - 1]->m_datum->operation, OPERATIONLEN, operation, strlen(operation)); securec_check(rc, "\0", "\0"); pfree(operation); m_plan_table[plan_node_id - 1]->m_isnull[PT_OPERATION] = false; } if (options != NULL) { options = set_strtoupper(options, OPTIONSLEN); rc = strncpy_s(m_plan_table[plan_node_id - 1]->m_datum->options, OPTIONSLEN, options, strlen(options)); securec_check(rc, "\0", "\0"); pfree(options); m_plan_table[plan_node_id - 1]->m_isnull[PT_OPTIONS] = false; } } /* * Description: Set object_type according to relkind in pg_class. * Parameters: * @in rte: related ralation. * @out object_type: object type. * Return: void */ void PlanTable::set_object_type(RangeTblEntry* rte, char** object_type) { if (rte == NULL) return; /* 1.It's on a real relation */ if (rte->rtekind == RTE_RELATION) { switch (rte->relkind) { case 'r': *object_type = "TABLE"; break; case 'i': *object_type = "INDEX"; break; case 'S': *object_type = "SEQUENCE"; break; case 't': *object_type = "TOASTVALUE"; break; case 'v': *object_type = "VIEW"; break; case 'c': *object_type = "COMPOSITE TYPE"; break; case 'f': *object_type = "FOREIGN TABLE"; break; case 'u': *object_type = "UNCATALOGED"; break; default: break; } } else { /* 2. For other rte kind. */ switch (rte->rtekind) { case RTE_SUBQUERY: *object_type = "SUBQUERY"; break; case RTE_JOIN: *object_type = "JOIN"; break; case RTE_FUNCTION: *object_type = "FUNCTION"; break; case RTE_VALUES: *object_type = "VALUES"; break; case RTE_CTE: *object_type = "CTE"; break; #ifdef PGXC case RTE_REMOTE_DUMMY: /* RTEs created by remote plan reduction */ *object_type = "REMOTE_QUERY"; break; #endif /* PGXC */ default: break; } } } /* * Description: Set object_name, object_type, object_owner for one paln node. * Parameters: * @in plan_node_id: plan node id. * @in object_name: object name. * @in object_type: object type. * @in object_owner: object schema. * Return: void */ void PlanTable::set_plan_table_objs( int plan_node_id, const char* object_name, const char* object_type, const char* object_owner) { AssertEreport(plan_node_id <= m_plan_node_num, MOD_EXECUTOR, "plan_node_id exceeds max value"); errno_t rc = EOK; /* * for query shipping we do not collect plan info. * However we need collect plan info for select for update. */ if (plan_node_id == 0) { if (IsExplainPlanSelectForUpdateStmt) plan_node_id = 1; else return; } /* For 'INDEX' operation, we may set twice, so do cleanning before set. */ if (object_name != NULL) { /* the max object name length is 'NAMEDATALEN - 1' byte. */ rc = memset_s(m_plan_table[plan_node_id - 1]->m_datum->object_name, NAMEDATALEN, '0', NAMEDATALEN); securec_check(rc, "\0", "\0"); rc = strncpy_s(m_plan_table[plan_node_id - 1]->m_datum->object_name, NAMEDATALEN, object_name, NAMEDATALEN - 1); securec_check(rc, "\0", "\0"); m_plan_table[plan_node_id - 1]->m_isnull[PT_OBJECT_NAME] = false; } if (object_type != NULL) { rc = memset_s(m_plan_table[plan_node_id - 1]->m_datum->object_type, OBJECTLEN, '0', OBJECTLEN); securec_check(rc, "\0", "\0"); rc = strncpy_s(m_plan_table[plan_node_id - 1]->m_datum->object_type, OBJECTLEN, object_type, OBJECTLEN - 1); securec_check(rc, "\0", "\0"); m_plan_table[plan_node_id - 1]->m_isnull[PT_OBJECT_TYPE] = false; } if (object_owner != NULL) { rc = memset_s(m_plan_table[plan_node_id - 1]->m_datum->object_owner, NAMEDATALEN, '0', NAMEDATALEN); securec_check(rc, "\0", "\0"); rc = strncpy_s( m_plan_table[plan_node_id - 1]->m_datum->object_owner, NAMEDATALEN, object_owner, NAMEDATALEN - 1); securec_check(rc, "\0", "\0"); m_plan_table[plan_node_id - 1]->m_isnull[PT_OBJECT_OWNER] = false; } } /* * Description: Set targetlist into column 'projection' for one plan node. * Parameters: * @in plan_node_id: plan node id. * @in tlist: targetlist of node. * Return: void */ void PlanTable::set_plan_table_projection(int plan_node_id, List* tlist) { if (tlist == NULL) return; ListCell* lc = NULL; bool first = true; /* * for query shipping we do not collect plan info. * However we need collect plan info for select for update. */ if (plan_node_id == 0) { if (IsExplainPlanSelectForUpdateStmt) plan_node_id = 1; else return; } m_plan_table[plan_node_id - 1]->m_datum->projection = makeStringInfo(); /* Add the targetlist into column 'projection' till the length exceed PROJECTIONLEN.*/ foreach (lc, tlist) { if (m_plan_table[plan_node_id - 1]->m_datum->projection->len + strlen((const char*)lfirst(lc)) > PROJECTIONLEN) break; if (!first) appendStringInfoString(m_plan_table[plan_node_id - 1]->m_datum->projection, ", "); appendStringInfoString(m_plan_table[plan_node_id - 1]->m_datum->projection, (const char*)lfirst(lc)); first = false; } m_plan_table[plan_node_id - 1]->m_isnull[PT_PROJECTION] = false; } /* * Description: Call heap_insert to insert all nodes tuples of the plan into table. * Parameters: * Return: void */ void PlanTable::insert_plan_table_tuple() { const char* plan_table_name = T_PLAN_TABLE_DATA; Relation plan_table; TupleDesc plan_table_des; HeapTuple tuple; Datum new_record[PLANTABLECOLNUM]; errno_t rc = EOK; Oid plan_table_oid = RelnameGetRelid(plan_table_name); if (plan_table_oid == InvalidOid) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("Relation 'plan_table_data' does not exist"))); plan_table = heap_open(plan_table_oid, RowExclusiveLock); plan_table_des = RelationGetDescr(plan_table); for (int i = 0; i < m_plan_node_num; i++) { /* * Build a tuple to insert */ rc = memset_s(new_record, sizeof(new_record), 0, sizeof(new_record)); securec_check(rc, "\0", "\0"); new_record[PT_SESSION_ID] = CStringGetTextDatum(m_plan_table[i]->m_datum->session_id); new_record[PT_USER_ID] = ObjectIdGetDatum(m_plan_table[i]->m_datum->user_id); new_record[PT_STATEMENT_ID] = CStringGetTextDatum(m_plan_table[i]->m_datum->statement_id); new_record[PT_QUERY_ID] = UInt64GetDatum(m_plan_table[i]->m_datum->query_id); new_record[PT_NODE_ID] = Int32GetDatum(m_plan_table[i]->m_datum->node_id); new_record[PT_OPERATION] = CStringGetTextDatum(m_plan_table[i]->m_datum->operation); new_record[PT_OPTIONS] = CStringGetTextDatum(m_plan_table[i]->m_datum->options); new_record[PT_OBJECT_NAME] = NameGetDatum(m_plan_table[i]->m_datum->object_name); new_record[PT_OBJECT_TYPE] = CStringGetTextDatum(m_plan_table[i]->m_datum->object_type); new_record[PT_OBJECT_OWNER] = NameGetDatum(m_plan_table[i]->m_datum->object_owner); if (m_plan_table[i]->m_datum->projection != NULL) new_record[PT_PROJECTION] = CStringGetTextDatum(m_plan_table[i]->m_datum->projection->data); tuple = (HeapTuple)heap_form_tuple(plan_table_des, new_record, m_plan_table[i]->m_isnull); /* * Insert new record into plan_table table */ (void)simple_heap_insert(plan_table, tuple); } /* make sure whether need to keep lock till commit */ heap_close(plan_table, RowExclusiveLock); } /* * Description: We only control the select/delete permission for pan_table_data. * For 'plan_table_data' we will handing its permission check espacially, We do not allow ordinary user to * select/D/U/I * 1. "Select xx from plan_table" the rte has subquery contain "plan_table_data" and will be pull up in * subquery_planner. * 2. In function ExecCheckRTEPerms will check the permission for every rte including those been pulled up. * 3. So we need to check whether has rte of "plan_table_data" in origin FromClause in this function for select/delete * cmd. Parameters: * @ in rangeTable: rte list of query * Return: return true if there is no rte of 'plan_table_data' in origin FromClause. */ bool checkSelectStmtForPlanTable(List* rangeTable) { OnlySelectFromPlanTable = false; ListCell* lc = NULL; foreach (lc, rangeTable) { RangeTblEntry* rte = (RangeTblEntry*)lfirst(lc); if (rte->relname != NULL && strcasecmp(rte->relname, T_PLAN_TABLE_DATA) == 0) return false; } return true; } /* * Description: Deal with 'plan_table_data' permission checking here. * We do not allow ordinary user to select from 'plan_table_data'. * Parameters: * @ in rangeTable: rte of "plan_table_data" * Return: return -1 for other action(insert/update). * return 1 if pass permission check. * return 0 if have no permission. */ int checkPermsForPlanTable(RangeTblEntry* rte) { /* * Note that: * 1. Planner will replace 'plan_table' with 'plan_table_data' in subquery_planner routine. * If it is only select/delete from plan_table view, we should return ture. * 2. If current user has superuser or sysdba privileges, we will allow the user do select/delelte on * 'plan_table_data'. */ /* For select action */ if (rte->requiredPerms == ACL_SELECT) { if (OnlySelectFromPlanTable || superuser()) return 1; else return 0; } else if (rte->requiredPerms == (ACL_SELECT + ACL_DELETE) /* for plan_table. */ || rte->requiredPerms == ACL_DELETE /* for plan_table_data.*/) { /* For delete action */ if (OnlyDeleteFromPlanTable || superuser()) return 1; else return 0; } else { /* For other action(insert/update) will be contorl by rel_acl. */ return -1; } } /* ----------------------End for explain plan----------------------------------- */ static inline void appendCSV(StringInfo buf, const char* data) { const char* p = data; char c; /* avoid confusing an empty string with NULL */ if (p == NULL) return; appendStringInfoCharMacro(buf, '"'); while ((c = *p++) != '\0') { if (c == '"') appendStringInfoCharMacro(buf, '"'); appendStringInfoCharMacro(buf, c); } appendStringInfoCharMacro(buf, '"'); } /* * Common code to show sort/group keys, which are represented in plan nodes * as arrays of targetlist indexes. If it's a sort key rather than a group * key, also pass sort operators/collations/nullsFirst arrays. */ static void show_sort_group_keys(PlanState* planstate, const char* qlabel, int nkeys, const AttrNumber* keycols, const Oid* sortOperators, const Oid* collations, const bool* nullsFirst, List* ancestors, ExplainState* es) { Plan* plan = planstate->plan; List* context = NIL; List* result = NIL; StringInfoData sortkeybuf; bool useprefix = false; int keyno; if (nkeys <= 0) return; initStringInfo(&sortkeybuf); context = deparse_context_for_planstate((Node*)planstate, ancestors, es->rtable); useprefix = (list_length(es->rtable) > 1 || es->verbose); for (keyno = 0; keyno < nkeys; keyno++) { /* find key expression in tlist */ AttrNumber keyresno = keycols[keyno]; TargetEntry* target = get_tle_by_resno(plan->targetlist, keyresno); char* exprstr = NULL; if (target == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("no tlist entry for key %d", keyresno))); /* Deparse the expression, showing any top-level cast */ exprstr = deparse_expression((Node*)target->expr, context, useprefix, true); resetStringInfo(&sortkeybuf); appendStringInfoString(&sortkeybuf, exprstr); /* Append sort order information, if relevant */ if (sortOperators != NULL) show_sortorder_options( &sortkeybuf, (Node*)target->expr, sortOperators[keyno], collations[keyno], nullsFirst[keyno]); /* Emit one property-list item per sort key */ result = lappend(result, pstrdup(sortkeybuf.data)); } if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_verboseInfo->info_str, "%s: ", qlabel); ExplainPrettyList(result, es); } else { ExplainPropertyList(qlabel, result, es); } } /* * Append nondefault characteristics of the sort ordering of a column to buf * (collation, direction, NULLS FIRST/LAST) */ static void show_sortorder_options(StringInfo buf, const Node* sortexpr, Oid sortOperator, Oid collation, bool nullsFirst) { Oid sortcoltype = exprType(sortexpr); bool reverse = false; TypeCacheEntry* typentry = NULL; typentry = lookup_type_cache(sortcoltype, TYPECACHE_LT_OPR | TYPECACHE_GT_OPR); /* * Print COLLATE if it's not default. There are some cases where this is * redundant, eg if expression is a column whose declared collation is * that collation, but it's hard to distinguish that here. */ if (OidIsValid(collation) && collation != DEFAULT_COLLATION_OID) { char* collname = get_collation_name(collation); if (collname == NULL) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for collation %u", collation))); appendStringInfo(buf, " COLLATE %s", quote_identifier(collname)); } /* Print direction if not ASC, or USING if non-default sort operator */ if (sortOperator == typentry->gt_opr) { appendStringInfoString(buf, " DESC"); reverse = true; } else if (sortOperator != typentry->lt_opr) { char* opname = get_opname(sortOperator); if (opname == NULL) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for operator %u", sortOperator))); appendStringInfo(buf, " USING %s", opname); /* Determine whether operator would be considered ASC or DESC */ (void)get_equality_op_for_ordering_op(sortOperator, &reverse); } /* Add NULLS FIRST/LAST only if it wouldn't be default */ if (nullsFirst && !reverse) { appendStringInfoString(buf, " NULLS FIRST"); } else if (!nullsFirst && reverse) { appendStringInfoString(buf, " NULLS LAST"); } } /* * Description: Show tablesample properties. * * Parameters: * @in plan: Scan plan. * @in planstate: PlanState node. * @in ancestors: The ancestors list is a list of the PlanState's parent PlanStates. * @in es: Explain state. * * Return: void */ static void show_tablesample(Plan* plan, PlanState* planstate, List* ancestors, ExplainState* es) { List* context = NIL; bool useprefix = false; const char* method_name = NULL; List* params = NIL; char* repeatable = NULL; ListCell* lc = NULL; TableSampleClause* tsc = ((Scan*)plan)->tablesample; if (tsc == NULL) { return; } /* Set up deparsing context */ context = deparse_context_for_planstate((Node*)planstate, ancestors, es->rtable); useprefix = list_length(es->rtable) > 1; /* Get the tablesample method name */ method_name = (tsc->sampleType == SYSTEM_SAMPLE ? "system" : (tsc->sampleType == BERNOULLI_SAMPLE ? "bernoulli" : "hybrid")); /* Deparse parameter expressions */ foreach (lc, tsc->args) { Node* arg = (Node*)lfirst(lc); params = lappend(params, deparse_expression(arg, context, useprefix, false)); } if (tsc->repeatable) { repeatable = deparse_expression((Node*)tsc->repeatable, context, useprefix, false); } else { repeatable = NULL; } /* Print results */ if (es->format == EXPLAIN_FORMAT_TEXT) { bool first = true; appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "Sampling: %s (", method_name); foreach (lc, params) { if (!first) appendStringInfoString(es->str, ", "); appendStringInfoString(es->str, (const char*)lfirst(lc)); first = false; } appendStringInfoChar(es->str, ')'); if (repeatable != NULL) { appendStringInfo(es->str, " REPEATABLE (%s)", repeatable); } appendStringInfoChar(es->str, '\n'); } else { ExplainPropertyText("Sampling Method", method_name, es); ExplainPropertyList("Sampling Parameters", params, es); if (repeatable != NULL) { ExplainPropertyText("Repeatable Seed", repeatable, es); } } list_free_deep(params); } void PlanTable::flush_data_to_file() { int i = 0; int j = 0; int k = 0; Datum* values = NULL; bool* nulls = NULL; bool is_null = false; Datum data; Datum val; Oid typoid; Oid foutoid; bool typisvarlena = false; char* result = NULL; bool from_datanode = false; int node_num = 0; for (i = 0; i < m_plan_size; i++) { values = m_multi_info[0][i][0].m_Datum; from_datanode = values[FROM_DATANODE]; node_num = from_datanode ? m_data_size : 1; for (j = 0; j < node_num; j++) { values = m_multi_info[j][i][0].m_Datum; nulls = m_multi_info[j][i][0].m_Nulls; for (k = 0; k < EXPLAIN_TOTAL_ATTNUM; k++) { is_null = nulls[k]; data = values[k]; if (is_null) { if (k == EXPLAIN_TOTAL_ATTNUM - 1) appendBinaryStringInfo(info_str, "", 0); else appendBinaryStringInfo(info_str, ",", 1); } else { typoid = m_desc->attrs[k]->atttypid; getTypeOutputInfo(typoid, &foutoid, &typisvarlena); if (typisvarlena) val = PointerGetDatum(PG_DETOAST_DATUM(data)); else val = data; result = OidOutputFunctionCall(foutoid, val); if (val != data) pfree(DatumGetPointer(val)); if (typisvarlena) appendCSV(info_str, result); else if (typoid == BOOLOID) { if (strcmp(result, "t") == 0) appendStringInfo(info_str, "true"); else appendStringInfo(info_str, "false"); } else appendStringInfo(info_str, "%s", result); if (k != EXPLAIN_TOTAL_ATTNUM - 1) appendStringInfoChar(info_str, ','); } } appendStringInfoChar(info_str, '\n'); } } } /* * Insert obs scan information into pg_obsscaninfo table */ void insert_obsscaninfo( uint64 queryid, const char* rel_name, int64 file_count, double scan_data_size, double total_time, int format) { Relation pgobsscaninforel; HeapTuple htup; bool nulls[Natts_pg_obsscaninfo]; Datum values[Natts_pg_obsscaninfo]; int i; TimestampTz ts = GetCurrentTimestamp(); StringInfo insert_stmt1, insert_stmt2; const char* billing_info = "unbilled"; char* file_format = NULL; if (format == 0) file_format = "orc"; else if (format == 1) file_format = "text"; else if (format == 2) file_format = "csv"; else file_format = "unknown"; MemoryContext current_ctx = CurrentMemoryContext; /* Initialize tuple data structures */ for (i = 0; i < Natts_pg_obsscaninfo; i++) { nulls[i] = false; values[i] = (Datum)0; } values[Anum_pg_obsscaninfo_query_id - 1] = Int64GetDatum(queryid); values[Anum_pg_obsscaninfo_user_id - 1] = CStringGetTextDatum(u_sess->misc_cxt.CurrentUserName); values[Anum_pg_obsscaninfo_table_name - 1] = CStringGetTextDatum(rel_name); values[Anum_pg_obsscaninfo_file_type - 1] = CStringGetTextDatum(file_format); values[Anum_pg_obsscaninfo_time_stamp - 1] = TimestampTzGetDatum(ts); values[Anum_pg_obsscaninfo_actual_time - 1] = Float8GetDatum(total_time); values[Anum_pg_obsscaninfo_file_scanned - 1] = file_count; values[Anum_pg_obsscaninfo_data_size - 1] = Float8GetDatum(scan_data_size); values[Anum_pg_obsscaninfo_billing_info - 1] = CStringGetTextDatum(billing_info); /* insert the new row into pg_obsscaninfo catalog table */ pgobsscaninforel = heap_open(ObsScanInfoRelationId, RowExclusiveLock); htup = heap_form_tuple(pgobsscaninforel->rd_att, values, nulls); (void)simple_heap_insert(pgobsscaninforel, htup); CatalogUpdateIndexes(pgobsscaninforel, htup); tableam_tops_free_tuple(htup); heap_close(pgobsscaninforel, RowExclusiveLock); /* insert the new row into pg_obsscaninfo catalog table */ pgobsscaninforel = heap_open(GSObsScanInfoRelationId, RowExclusiveLock); htup = heap_form_tuple(pgobsscaninforel->rd_att, values, nulls); (void)simple_heap_insert(pgobsscaninforel, htup); CatalogUpdateIndexes(pgobsscaninforel, htup); tableam_tops_free_tuple(htup); heap_close(pgobsscaninforel, RowExclusiveLock); elog(DEBUG1, "SyncUp with other CN"); insert_stmt1 = makeStringInfo(); appendStringInfo(insert_stmt1, "insert into pg_obsscaninfo values (%lu, '%s', '%s', '%s', '%s', '%lf', %ld, %lf, '%s');", queryid, /* we delibrately let it as a int64 due to unsupporting uint64 in pg */ u_sess->misc_cxt.CurrentUserName, rel_name, file_format, timestamptz_to_str(ts), total_time, file_count, scan_data_size, billing_info); insert_stmt2 = makeStringInfo(); appendStringInfo(insert_stmt2, "insert into gs_obsscaninfo values (%lu, '%s', '%s', '%s', '%s', '%lf', %ld, %lf, '%s');", queryid, /* we delibrately let it as a int64 due to unsupporting uint64 in pg */ u_sess->misc_cxt.CurrentUserName, rel_name, file_format, timestamptz_to_str(ts), total_time, file_count, scan_data_size, billing_info); elog(DEBUG1, "%s", insert_stmt1->data); elog(DEBUG1, "%s", insert_stmt2->data); PG_TRY(); { /* * If insert job status in local success and only synchronize to other coordinator fail, * we should consider the worker success, so that we at least have one record for billing. */ ExecUtilityStmtOnNodes(insert_stmt1->data, NULL, false, false, EXEC_ON_COORDS, false); ExecUtilityStmtOnNodes(insert_stmt2->data, NULL, false, false, EXEC_ON_COORDS, false); } PG_CATCH(); { /* t_thrd.int_cxt.InterruptHoldoffCount is set 0 in function "errfinish" * So if we invoke LWLockrelease, we must call HOLD_INTERRUPT * the function called by OBSInstrumentation::insertData() which holds * OBSRuntimeLock. */ HOLD_INTERRUPTS(); MemoryContextSwitchTo(current_ctx); /* Save error info */ ErrorData* edata = CopyErrorData(); FlushErrorState(); ereport(LOG, (errcode(ERRCODE_OPERATE_FAILED), errmsg("Synchronize OBS scan info to other coordinator failed, OBS billing info may be out of sync"), errdetail("Synchronize fail reason: %s.", edata->message))); FreeErrorData(edata); } PG_END_TRY(); pfree_ext(insert_stmt1); pfree_ext(insert_stmt2); } static void show_unique_check_info(PlanState *planstate, ExplainState *es) { Agg *aggnode = (Agg *) planstate->plan; if (aggnode->unique_check) { const char *str = "Unique Check Required"; if (t_thrd.explain_cxt.explain_perf_mode != EXPLAIN_NORMAL && es->planinfo->m_verboseInfo) { es->planinfo->m_verboseInfo->set_plan_name<false, true>(); appendStringInfo(es->planinfo->m_verboseInfo->info_str, "%s\n", str); } else { if (es->format == EXPLAIN_FORMAT_TEXT && !es->wlm_statistics_plan_max_digit) { appendStringInfoSpaces(es->str, es->indent * 2); appendStringInfo(es->str, "%s\n", str); } } } }
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Tests/Streamer/StreamStackEntryConformityTests.h> namespace AZ::IO { class StreamStackEntryTestDescription : public StreamStackEntryConformityTestsDescriptor<StreamStackEntry> { public: StreamStackEntry CreateInstance() override { return StreamStackEntry("Name"); } bool UsesSlots() const override { return false; } }; INSTANTIATE_TYPED_TEST_CASE_P(Streamer_StreamStackEntryConformityTests, StreamStackEntryConformityTests, StreamStackEntryTestDescription); } // namespace AZ::IO
#include <iostream> #include <iomanip> #include "color/color.hpp" int main( int argc, char *argv[] ) { ::color::hsv< float > c0; //!< Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double ::color::lms< std::uint8_t > c1; //!< Instead of std::uint8_t you may put std::uint16_t, std::uint32_t, std::uint64_t, float, double, long double c0 = ::color::constant::lavender_t{}; c1 = ::color::constant::orange_t{}; // Assign c0 = c1; std::cout << c0[0] << ", " << c0[1] << ", " << c0[2] << std::endl; // .. and vice versa c1 = c0; std::cout << c1[0] << ", " << c1[1] << ", " << c1[2] << std::endl; return EXIT_SUCCESS; }
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkBioRadImageIO.h" #include "itkBioRadImageIOFactory.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" // Specific ImageIO test int itkBioRadImageIOTest(int argc, char * argv[]) { if (argc < 3) { std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " BioRad.pic OutputImage.pic\n"; return EXIT_FAILURE; } itk::ObjectFactoryBase::RegisterFactory(itk::BioRadImageIOFactory::New()); using InputPixelType = unsigned char; using InputImageType = itk::Image<InputPixelType, 2>; using ReaderType = itk::ImageFileReader<InputImageType>; using ImageIOType = itk::BioRadImageIO; const char * filename = argv[1]; const char * outfilename = argv[2]; auto reader = ReaderType::New(); reader->SetFileName(filename); auto bioradImageIO = ImageIOType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(bioradImageIO, BioRadImageIO, ImageIOBase); // Not used; empty method body; called for coverage purposes bioradImageIO->WriteImageInformation(); reader->SetImageIO(bioradImageIO); ITK_TRY_EXPECT_NO_EXCEPTION(reader->Update()); using WriterType = itk::ImageFileWriter<InputImageType>; auto writer = WriterType::New(); writer->SetFileName(outfilename); writer->SetInput(reader->GetOutput()); writer->SetImageIO(bioradImageIO); ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); return EXIT_SUCCESS; }
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/html/canvas/OESElementIndexUint.h" namespace blink { OESElementIndexUint::OESElementIndexUint(WebGLRenderingContextBase* context) : WebGLExtension(context) { context->extensionsUtil()->ensureExtensionEnabled("GL_OES_element_index_uint"); } OESElementIndexUint::~OESElementIndexUint() { } WebGLExtensionName OESElementIndexUint::name() const { return OESElementIndexUintName; } PassRefPtrWillBeRawPtr<OESElementIndexUint> OESElementIndexUint::create(WebGLRenderingContextBase* context) { return adoptRefWillBeNoop(new OESElementIndexUint(context)); } bool OESElementIndexUint::supported(WebGLRenderingContextBase* context) { return context->extensionsUtil()->supportsExtension("GL_OES_element_index_uint"); } const char* OESElementIndexUint::extensionName() { return "OES_element_index_uint"; } } // namespace blink
// NCCode.cpp /* * Copyright (c) 2009, Dan Heeks * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include <math.h> #include "NCCode.h" #include "OutputCanvas.h" #include "interface/Geom.h" #include "interface/MarkedObject.h" #include "interface/PropertyList.h" #include "interface/Tool.h" #include "CNCConfig.h" #include "CTool.h" #include "Program.h" #include <TopoDS_Shape.hxx> #include <TopoDS_Solid.hxx> #include <TopoDS_Compound.hxx> #include <BRep_Builder.hxx> #include <BRepBuilderAPI_Transform.hxx> #include <BRepAlgoAPI_Fuse.hxx> #include <BRepAlgoAPI_Cut.hxx> #include <Standard_Failure.hxx> #include <StdFail_NotDone.hxx> #include "tinyxml/tinyxml.h" #include <wx/progdlg.h> #include <memory> #include <sstream> int CNCCode::s_arc_interpolation_count = 20; wxFont format_font(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, _T("Lucida Console"), wxFONTENCODING_SYSTEM); void ColouredText::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = heeksCAD->NewXMLElement( "text" ); heeksCAD->LinkXMLEndChild( root, element ); // add actual text as a child object TiXmlText* text = heeksCAD->NewXMLText(m_str.utf8_str()); element->LinkEndChild(text); if(m_color_type != ColorDefaultType)element->SetAttribute( "col", CNCCode::GetColor(m_color_type)); } void ColouredText::ReadFromXMLElement(TiXmlElement* element) { m_color_type = CNCCode::GetColor(element->Attribute("col")); // get the text const char* text = element->GetText(); if(text) m_str = wxString(Ctt(text)); else m_str = _(" "); // Assume a single space that xml trimmed. } // static double PathObject::m_current_x[3] = {0, 0, 0}; double PathObject::m_prev_x[3] = {0, 0, 0}; void PathObject::WriteBaseXML(TiXmlElement *pElem) { pElem->SetAttribute("tool_number", m_tool_number); pElem->SetDoubleAttribute("x", m_x[0]); pElem->SetDoubleAttribute("y", m_x[1]); pElem->SetDoubleAttribute("z", m_x[2]); } // End WriteXML() method void PathObject::ReadFromXMLElement(TiXmlElement* pElem) { memcpy(m_prev_x, m_current_x, 3*sizeof(double)); double x; if(pElem->Attribute("x", &x))m_current_x[0] = x * CNCCodeBlock::multiplier; if(pElem->Attribute("y", &x))m_current_x[1] = x * CNCCodeBlock::multiplier; if(pElem->Attribute("z", &x))m_current_x[2] = x * CNCCodeBlock::multiplier; memcpy(m_x, m_current_x, 3*sizeof(double)); if (pElem->Attribute("tool_number")) { pElem->Attribute("tool_number", &m_tool_number); } // End if - then else { m_tool_number = 0; // No tool selected. } // End if - else } void PathLine::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = heeksCAD->NewXMLElement( "line" ); heeksCAD->LinkXMLEndChild( root, element ); PathObject::WriteBaseXML(element); } void PathLine::ReadFromXMLElement(TiXmlElement* pElem) { PathObject::ReadFromXMLElement(pElem); } void PathLine::glVertices(const PathObject* prev_po) { if(prev_po)glVertex3dv(prev_po->m_x); glVertex3dv(m_x); } void PathArc::GetBox(CBox &box,const PathObject* prev_po) { PathObject::GetBox(box,prev_po); if(IsIncluded(gp_Pnt(0,1,0),prev_po)) box.Insert(prev_po->m_x[0]+m_c[0],prev_po->m_x[1]+m_c[1]+m_radius,0); if(IsIncluded(gp_Pnt(0,-1,0),prev_po)) box.Insert(prev_po->m_x[0]+m_c[0],prev_po->m_x[1]+m_c[1]-m_radius,0); if(IsIncluded(gp_Pnt(1,0,0),prev_po)) box.Insert(prev_po->m_x[0]+m_c[0]+m_radius,prev_po->m_x[1]+m_c[1],0); if(IsIncluded(gp_Pnt(-1,0,0),prev_po)) box.Insert(prev_po->m_x[0]+m_c[0]-m_radius,prev_po->m_x[1]+m_c[1],0); } bool PathArc::IsIncluded(gp_Pnt pnt,const PathObject* prev_po) { double sx = -m_c[0]; double sy = -m_c[1]; // e = cs + se = -c + e - s double ex = -m_c[0] + m_x[0] - prev_po->m_x[0]; double ey = -m_c[1] + m_x[1] - prev_po->m_x[1]; double rs = sqrt(sx * sx + sy * sy); // double re = sqrt(ex * ex + ey * ey); m_radius = rs; double start_angle = atan2(sy, sx); double end_angle = atan2(ey, ex); if(m_dir == 1){ if(end_angle < start_angle)end_angle += 6.283185307179; } else{ if(start_angle < end_angle)start_angle += 6.283185307179; } // double angle_step = 0; if (start_angle == end_angle) // It's a full circle. return true; double the_angle = atan2(pnt.Y(),pnt.X()); double the_angle2 = the_angle + 2*PI; return (the_angle >= start_angle && the_angle <= end_angle) || (the_angle2 >= start_angle && the_angle2 <= end_angle); } void PathArc::WriteXML(TiXmlNode *root) { TiXmlElement * element = heeksCAD->NewXMLElement( "arc" ); heeksCAD->LinkXMLEndChild( root, element ); element->SetDoubleAttribute( "i", m_c[0]); element->SetDoubleAttribute( "j", m_c[1]); element->SetDoubleAttribute( "k", m_c[2]); element->SetDoubleAttribute( "d", m_dir); PathObject::WriteBaseXML(element); } void PathArc::ReadFromXMLElement(TiXmlElement* pElem) { // get the attributes bool radius_set = false; if (pElem->Attribute("r")) { pElem->Attribute("r", &m_radius); m_radius *= CNCCodeBlock::multiplier; radius_set = true; } else { if (pElem->Attribute("i")) pElem->Attribute("i", &m_c[0]); if (pElem->Attribute("j")) pElem->Attribute("j", &m_c[1]); if (pElem->Attribute("k")) pElem->Attribute("k", &m_c[2]); if (pElem->Attribute("d")) pElem->Attribute("d", &m_dir); m_c[0] *= CNCCodeBlock::multiplier; m_c[1] *= CNCCodeBlock::multiplier; m_c[2] *= CNCCodeBlock::multiplier; } PathObject::ReadFromXMLElement(pElem); if(radius_set) { // set ij and direction from radius SetFromRadius(); } } void PathArc::SetFromRadius() { // make a circle at start point and end point gp_Pnt ps(m_prev_x[0], m_prev_x[1], m_prev_x[2]); gp_Pnt pe(m_x[0], m_x[1], m_x[2]); double r = fabs(m_radius); gp_Circ c1(gp_Ax2(ps, gp_Dir(0, 0, 1)), r); gp_Circ c2(gp_Ax2(pe, gp_Dir(0, 0, 1)), r); std::list<gp_Pnt> plist; intersect(c1, c2, plist); if(plist.size() == 2) { gp_Pnt p1 = plist.front(); gp_Pnt p2 = plist.back(); gp_Vec along(ps, pe); gp_Vec right = gp_Vec(0, 0, 1).Crossed(along); gp_Vec vc(p1, p2); bool left = vc.Dot(right) < 0; if((m_radius < 0) == left) { extract(gp_Vec(ps, p1), this->m_c); this->m_dir = 1; } else { extract(gp_Vec(ps, p2), this->m_c); this->m_dir = -1; } m_radius = r; } } void PathArc::glVertices(const PathObject* prev_po) { if (prev_po == NULL) return; std::list<gp_Pnt> vertices = Interpolate( prev_po, CNCCode::s_arc_interpolation_count ); glVertex3dv(prev_po->m_x); for (std::list<gp_Pnt>::const_iterator l_itVertex = vertices.begin(); l_itVertex != vertices.end(); l_itVertex++) { glVertex3d(l_itVertex->X(), l_itVertex->Y(), l_itVertex->Z()); } // End for } std::list<gp_Pnt> PathArc::Interpolate( const PathObject *prev_po, const unsigned int number_of_points ) const { std::list<gp_Pnt> points; double sx = -m_c[0]; double sy = -m_c[1]; // e = cs + se = -c + e - s double ex = -m_c[0] + m_x[0] - prev_po->m_x[0]; double ey = -m_c[1] + m_x[1] - prev_po->m_x[1]; double rs = sqrt(sx * sx + sy * sy); double re = sqrt(ex * ex + ey * ey); double start_angle = atan2(sy, sx); double end_angle = atan2(ey, ex); if(m_dir == 1){ if(end_angle < start_angle)end_angle += 6.283185307179; } else{ if(start_angle < end_angle)start_angle += 6.283185307179; } double angle_step = 0; if (start_angle == end_angle) { // It's a full circle. angle_step = (2 * PI) / number_of_points; if (m_dir == -1) { angle_step = -angle_step; // fix preview of full cw arcs } } // End if - then else { // It's an arc. angle_step = (end_angle - start_angle) / number_of_points; } // End if - else points.push_back( gp_Pnt( prev_po->m_x[0], prev_po->m_x[1], prev_po->m_x[2] ) ); for(unsigned int i = 0; i< number_of_points; i++) { double angle = start_angle + angle_step * (i + 1); double r = rs + ((re - rs) * (i + 1)) /number_of_points; double x = prev_po->m_x[0] + m_c[0] + r * cos(angle); double y = prev_po->m_x[1] + m_c[1] + r * sin(angle); double z = prev_po->m_x[2] + ((m_x[2] - prev_po->m_x[2]) * (i+1))/number_of_points; points.push_back( gp_Pnt( x, y, z ) ); } return(points); } ColouredPath::ColouredPath(const ColouredPath& c) { operator=(c); } const ColouredPath &ColouredPath::operator=(const ColouredPath& c) { Clear(); m_color_type = c.m_color_type; for(std::list< PathObject* >::const_iterator It = c.m_points.begin(); It != c.m_points.end(); It++) { PathObject* object = *It; m_points.push_back(object->MakeACopy()); } return *this; } void ColouredPath::Clear() { for(std::list< PathObject* >::iterator It = m_points.begin(); It != m_points.end(); It++) { PathObject* object = *It; delete object; } m_points.clear(); } void ColouredPath::glCommands() { CNCCode::Color(m_color_type).glColor(); glBegin(GL_LINE_STRIP); for(std::list< PathObject* >::iterator It = m_points.begin(); It != m_points.end(); It++) { PathObject* po = *It; po->glVertices(CNCCode::prev_po); CNCCode::prev_po = po; } glEnd(); } void ColouredPath::GetBox(CBox &box) { for(std::list< PathObject* >::iterator It = m_points.begin(); It != m_points.end(); It++) { PathObject* po= *It; po->GetBox(box,CNCCode::prev_po); CNCCode::prev_po = po; } } void ColouredPath::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = heeksCAD->NewXMLElement( "path" ); heeksCAD->LinkXMLEndChild( root, element ); element->SetAttribute( "col", CNCCode::GetColor(m_color_type)); for(std::list< PathObject* >::iterator It = m_points.begin(); It != m_points.end(); It++) { PathObject* po = *It; po->WriteXML(element); } } void ColouredPath::ReadFromXMLElement(TiXmlElement* element) { // get the attributes m_color_type = CNCCode::GetColor(element->Attribute("col"), ColorRapidType); // loop through all the objects for(TiXmlElement* pElem = heeksCAD->FirstXMLChildElement( element ) ; pElem; pElem = pElem->NextSiblingElement()) { std::string name(pElem->Value()); if(name == "line") { PathLine *new_object = new PathLine; new_object->ReadFromXMLElement(pElem); m_points.push_back(new_object); } else if(name == "arc") { PathArc *new_object = new PathArc; new_object->ReadFromXMLElement(pElem); m_points.push_back(new_object); } } } double CNCCodeBlock::multiplier = 1.0; HeeksObj *CNCCodeBlock::MakeACopy(void)const{return new CNCCodeBlock(*this);} void CNCCodeBlock::WriteNCCode(wxTextFile &f, double ox, double oy) { //TODO: offset is always in millimeters, but this gcode block could be in anything //I used inches, so I hacked it into working. wxString movement; std::list<ColouredText>::iterator it; for(it = m_text.begin(); it != m_text.end(); it++) { ColouredText ct = *it; switch(ct.m_color_type) { case ColorPrepType: f.AddLine(ct.m_str); break; case ColorRapidType: case ColorFeedType: movement = ct.m_str; break; case ColorAxisType: { wxString str = ct.m_str; wxChar axis = ct.m_str[0]; double pos=0; ct.m_str.SubString(1,ct.m_str.size()-1).ToDouble(&pos); if(axis == 'X' || axis == 'x') { str = wxString::Format(_T("%c%f"),axis,pos+ox/25.4); } if(axis == 'Y' || axis == 'y') { str = wxString::Format(_T("%c%f"),axis,pos+oy/25.4); } movement.append(str); } break; default: break; } } if(movement.size()) f.AddLine(movement); } void CNCCodeBlock::glCommands(bool select, bool marked, bool no_color) { if(marked)glLineWidth(3); for(std::list<ColouredPath>::iterator It = m_line_strips.begin(); It != m_line_strips.end(); It++) { ColouredPath& line_strip = *It; line_strip.glCommands(); } if(marked)glLineWidth(1); } void CNCCodeBlock::GetBox(CBox &box) { for(std::list<ColouredPath>::iterator It = m_line_strips.begin(); It != m_line_strips.end(); It++) { ColouredPath& line_strip = *It; line_strip.GetBox(box); } } void CNCCodeBlock::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = heeksCAD->NewXMLElement( "ncblock" ); heeksCAD->LinkXMLEndChild( root, element ); for(std::list<ColouredText>::iterator It = m_text.begin(); It != m_text.end(); It++) { ColouredText &text = *It; text.WriteXML(element); } for(std::list<ColouredPath>::iterator It = m_line_strips.begin(); It != m_line_strips.end(); It++) { ColouredPath &line_strip = *It; line_strip.WriteXML(element); } WriteBaseXML(element); } // static HeeksObj* CNCCodeBlock::ReadFromXMLElement(TiXmlElement* element) { CNCCodeBlock* new_object = new CNCCodeBlock; new_object->m_from_pos = CNCCode::pos; // loop through all the objects for(TiXmlElement* pElem = heeksCAD->FirstXMLChildElement( element ) ; pElem; pElem = pElem->NextSiblingElement()) { std::string name(pElem->Value()); if(name == "text") { ColouredText t; t.ReadFromXMLElement(pElem); new_object->m_text.push_back(t); CNCCode::pos += t.m_str.Len(); } else if(name == "path") { ColouredPath l; l.ReadFromXMLElement(pElem); new_object->m_line_strips.push_back(l); } else if(name == "mode") { const char* units = pElem->Attribute("units"); if(units)pElem->Attribute("units", &CNCCodeBlock::multiplier); } } if(new_object->m_text.size() > 0)CNCCode::pos++; new_object->m_to_pos = CNCCode::pos; new_object->ReadBaseXML(element); return new_object; } void CNCCodeBlock::AppendText(wxString& str) { if(m_text.size() == 0) return; for(std::list<ColouredText>::iterator It = m_text.begin(); It != m_text.end(); It++) { ColouredText &text = *It; str.append(text.m_str); } str.append(_T("\n")); } void CNCCodeBlock::FormatText(COutputTextCtrl *textCtrl) { if (m_formatted) return; textCtrl->StartStyling(m_from_pos, wxSTC_STYLE_DEFAULT - 1); for(std::list<ColouredText>::iterator It = m_text.begin(); It != m_text.end(); It++) { ColouredText &text = *It; textCtrl->SetStyling((int)text.m_str.size(), (int)text.m_color_type); } m_formatted = true; } long CNCCode::pos = 0; // static PathObject* CNCCode::prev_po = NULL; std::map<std::string,ColorEnum> CNCCode::m_colors_s_i; std::map<ColorEnum,std::string> CNCCode::m_colors_i_s; std::vector<PropertyColor> CNCCode::m_colors; const wxBitmap &CNCCode::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL)icon = new wxBitmap(wxImage(theApp.GetResFolder() + _T("/icons/nccode.png"))); return *icon; } void CNCCode::InitializeColorProperties(PropertyList * owner) { // Don't set the owner on the local copy m_colors.push_back ( PropertyColor ( _("default_color"), _("default color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("block_color"), _("block color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("misc_color"), _("misc color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("program_color"), _("program color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("tool_color"), _("tool color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("comment_color"), _("comment color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("variable_color"), _("variable color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("prep_color"), _("prep color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("axis_color"), _("axis color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("rapid_color"), _("rapid color"), NULL ) ); m_colors.push_back ( PropertyColor ( _("feed_color"), _("feed color"), NULL ) ); std::vector<PropertyColor>::iterator it; for (it = m_colors.begin(); it != m_colors.end(); it++) { PropertyColor& prop = *it; owner->AddProperty(&prop); } } void CNCCode::ClearColors(void) { CNCCode::m_colors_s_i.clear(); CNCCode::m_colors_i_s.clear(); CNCCode::m_colors.clear(); } void CNCCode::AddColor(const char* name, const PropertyColor& prop, long col, PropertyList * owner) { ColorEnum i = (ColorEnum)ColorCount(); m_colors_s_i.insert(std::pair<std::string,ColorEnum>(std::string(name), i)); m_colors_i_s.insert(std::pair<ColorEnum,std::string>(i, std::string(name))); m_colors.push_back(prop); m_colors.back() = col; m_colors.back().SetOwner(owner); } ColorEnum CNCCode::GetColor(const char* name, ColorEnum def) { if (name == NULL) return def; std::map<std::string,ColorEnum>::iterator it = m_colors_s_i.find(std::string(name)); if (it != m_colors_s_i.end()) return it->second; else return def; } const char* CNCCode::GetColor(ColorEnum i, const char* def) { std::map<ColorEnum,std::string>::iterator it = m_colors_i_s.find(i); if (it != m_colors_i_s.end()) return it->second.c_str(); else return def; } // static void CNCCode::ReadColorsFromConfig(PropertyList * owner) { CNCConfig config(ConfigScope()); long col; ClearColors(); config.Read(_T("ColorDefaultType"), &col, HeeksColor(0, 0, 0).COLORREF_color()); AddColor("default", PropertyColor ( _("default_color"), _("default color"), NULL ), col, owner ); config.Read(_T("ColorBlockType"), &col, HeeksColor(0, 0, 222).COLORREF_color()); AddColor("blocknum", PropertyColor ( _("block_color"), _("block color"), NULL ), col, owner ); config.Read(_T("ColorMiscType"), &col, HeeksColor(0, 200, 0).COLORREF_color()); AddColor("misc", PropertyColor ( _("misc_color"), _("misc color"), NULL ), col, owner ); config.Read(_T("ColorProgramType"), &col, HeeksColor(255, 128, 0).COLORREF_color()); AddColor("program", PropertyColor ( _("program_color"), _("program color"), NULL ), col, owner ); config.Read(_T("ColorToolType"), &col, HeeksColor(200, 200, 0).COLORREF_color()); AddColor("tool", PropertyColor ( _("tool_color"), _("tool color"), NULL ), col, owner ); config.Read(_T("ColorCommentType"), &col, HeeksColor(0, 200, 200).COLORREF_color()); AddColor("comment", PropertyColor ( _("comment_color"), _("comment color"), NULL ), col, owner ); config.Read(_T("ColorVariableType"), &col, HeeksColor(164, 88, 188).COLORREF_color()); AddColor("variable", PropertyColor ( _("variable_color"), _("variable color"), NULL ), col, owner ); config.Read(_T("ColorPrepType"), &col, HeeksColor(255, 0, 175).COLORREF_color()); AddColor("prep", PropertyColor ( _("prep_color"), _("prep color"), NULL ), col, owner ); config.Read(_T("ColorAxisType"), &col, HeeksColor(128, 0, 255).COLORREF_color()); AddColor("axis", PropertyColor ( _("axis_color"), _("axis color"), NULL ), col, owner ); config.Read(_T("ColorRapidType"), &col, HeeksColor(222, 0, 0).COLORREF_color()); AddColor("rapid", PropertyColor ( _("rapid_color"), _("rapid color"), NULL ), col, owner ); config.Read(_T("ColorFeedType"), &col, HeeksColor(0, 179, 0).COLORREF_color()); AddColor("feed", PropertyColor ( _("feed_color"), _("feed color"), NULL ), col, owner ); } // static void CNCCode::WriteColorsToConfig() { CNCConfig config(ConfigScope()); config.Write(_T("ColorDefaultType"), CNCCode::m_colors[ColorDefaultType ].COLORREF_color()); config.Write(_T("ColorBlockType"), CNCCode::m_colors[ColorBlockType ].COLORREF_color()); config.Write(_T("ColorMiscType"), CNCCode::m_colors[ColorMiscType ].COLORREF_color()); config.Write(_T("ColorProgramType"), CNCCode::m_colors[ColorProgramType ].COLORREF_color()); config.Write(_T("ColorToolType"), CNCCode::m_colors[ColorToolType ].COLORREF_color()); config.Write(_T("ColorCommentType"), CNCCode::m_colors[ColorCommentType ].COLORREF_color()); config.Write(_T("ColorVariableType"), CNCCode::m_colors[ColorVariableType].COLORREF_color()); config.Write(_T("ColorPrepType"), CNCCode::m_colors[ColorPrepType ].COLORREF_color()); config.Write(_T("ColorAxisType"), CNCCode::m_colors[ColorAxisType ].COLORREF_color()); config.Write(_T("ColorRapidType"), CNCCode::m_colors[ColorRapidType ].COLORREF_color()); config.Write(_T("ColorFeedType"), CNCCode::m_colors[ColorFeedType ].COLORREF_color()); } CNCCode::CNCCode() : HeeksObj(ObjType), m_gl_list(0), m_highlighted_block(NULL), m_user_edited(false) { CNCConfig config(ConfigScope()); config.Read(_T("CNCCode_ArcInterpolationCount"), &CNCCode::s_arc_interpolation_count, 20); } CNCCode::~CNCCode() { Clear(); } const CNCCode &CNCCode::operator=(const CNCCode &rhs) { HeeksObj::operator =(rhs); Clear(); for(std::list<CNCCodeBlock*>::const_iterator It = rhs.m_blocks.begin(); It != rhs.m_blocks.end(); It++) { CNCCodeBlock* block = *It; CNCCodeBlock* new_block = new CNCCodeBlock(*block); m_blocks.push_back(new_block); } return *this; } void CNCCode::Clear() { for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; delete block; } m_blocks.clear(); DestroyGLLists(); m_box = CBox(); m_highlighted_block = NULL; } void CNCCode::glCommands(bool select, bool marked, bool no_color) { if(m_gl_list) { glCallList(m_gl_list); } else{ m_gl_list = glGenLists(1); glNewList(m_gl_list, GL_COMPILE_AND_EXECUTE); // render all the blocks CNCCode::prev_po = NULL; for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; glPushName(block->GetIndex()); block->glCommands(true, block == m_highlighted_block, false); glPopName(); } glEndList(); } } void CNCCode::GetBox(CBox &box) { if(!m_box.m_valid) { for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; block->GetBox(m_box); } } box.Insert(m_box); } /* void on_set_arc_interpolation_count(int value, HeeksObj*object) { CNCCode::s_arc_interpolation_count = value; CNCConfig config(CNCCode::ConfigScope()); config.Write(_T("CNCCode_ArcInterpolationCount"), CNCCode::s_arc_interpolation_count); } void CNCCode::GetProperties(std::list<Property *> *list) { list->push_back( new PropertyInt(_("Arc Interpolation Count"), CNCCode::s_arc_interpolation_count, this, on_set_arc_interpolation_count) ); HeeksObj::GetProperties(list); } */ /** Define an 'apply' button class so that we can apply a combination of the tools and the GCode paths into a solid and use it to remove sections of the solids in the data model. */ class ApplyNCCode: public Tool{ // Tool's virtual functions const wxChar* GetTitle(){return _("Apply NC Code to solids. NOTE: This is not ready yet.");} void Run() { try { // Aggregate a list of solid objects. The Cut code re-arranges some of these // objects so we don't want to traverse the same list we're changing. Get our // own list to traverse here first. typedef std::map<int, HeeksObj *> Solids_t; Solids_t solids; typedef std::list<std::pair<int, TopoDS_Shape> > Shapes_t; Shapes_t shapes; for(HeeksObj* object = heeksCAD->GetFirstObject(); object; object = heeksCAD->GetNextObject()) { if (object->GetType() == SolidType) solids.insert(std::make_pair(object->GetID(), object)); if (! object->GetShape().IsNull()) shapes.push_back( std::make_pair(object->GetID(), TopoDS_Shape( object->GetShape() ) ) ); } // End for std::map<int, TopoDS_Shape> tools; std::list< std::pair<PathObject *, CTool *> > paths = theApp.m_program->NCCode()->GetPaths(); std::list< std::pair<PathObject *, CTool *> >::const_iterator l_itPath; // This stuff takes a long time. Give the user something to look at in the meantime. int progress = 1; std::auto_ptr<wxProgressDialog> pProgressBar = std::auto_ptr<wxProgressDialog>(new wxProgressDialog( wxString(_T("Apply")), wxString(_T("Applying NC operations to solid")), paths.size(), NULL, wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME | wxPD_AUTO_HIDE )); PathObject *pPreviousPoint = NULL; for (l_itPath = paths.begin(); l_itPath != paths.end(); l_itPath++) { pProgressBar->Update( ++progress ); if (pPreviousPoint == NULL) { pPreviousPoint = l_itPath->first; } // End if - then else { if (tools.find( l_itPath->first->m_tool_number ) == tools.end()) { try { tools.insert( std::make_pair( l_itPath->first->m_tool_number, l_itPath->second->GetShape() ) ); } catch(...) { // There must be something wrong with the parameters that describe // the tool. Just skip this one. continue; } } // End if - then gp_Pnt previous_point(pPreviousPoint->m_x[0], pPreviousPoint->m_x[1], pPreviousPoint->m_x[2] ); gp_Pnt this_point(l_itPath->first->m_x[0], l_itPath->first->m_x[1], l_itPath->first->m_x[2] ); pPreviousPoint = l_itPath->first; // Just put some values here for now. The feed_rate and spindle_rpm will eventually come from // the GCode. The number_of_cutting_edges will come from the CTool class. double feed_rate = 100.0; double spindle_rpm = 50; unsigned int number_of_cutting_edges = 2; std::list<gp_Pnt> interpolated_points; switch (l_itPath->first->GetType()) { case PathObject::eArc: interpolated_points = ((PathArc *) l_itPath->first)->Interpolate(pPreviousPoint, feed_rate, spindle_rpm, number_of_cutting_edges ); break; case PathObject::eLine: default: interpolated_points = ((PathLine *) l_itPath->first)->Interpolate(previous_point, this_point, feed_rate, spindle_rpm, number_of_cutting_edges ); break; } // End switch for (std::list<gp_Pnt>::const_iterator l_itPnt = interpolated_points.begin(); l_itPnt != interpolated_points.end(); l_itPnt++) { // Now move the tool to this point's location. gp_Trsf move; move.SetTranslation( gp_Pnt(0,0,0), *l_itPnt ); TopoDS_Shape tool = BRepBuilderAPI_Transform( tools[ l_itPath->first->m_tool_number ], move, true ); Shapes_t::iterator l_itShape; for (l_itShape = shapes.begin(); l_itShape != shapes.end(); l_itShape++) { try { l_itShape->second = BRepAlgoAPI_Cut(l_itShape->second, tool); } // End try catch(StdFail_NotDone) { // There are exceptions that are thrown by the OpenCascade library when // the two shape objects don't intersect. We just want to ignore such // problems. } // End catch } // End for } // End for } // End if - else } // End for progress = 1; pProgressBar = std::auto_ptr<wxProgressDialog>(new wxProgressDialog( wxString(_T("Apply")), wxString(_T("Replacing solids in model")), shapes.size(), NULL, wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME | wxPD_AUTO_HIDE )); for (Shapes_t::iterator l_itShape = shapes.begin(); l_itShape != shapes.end(); l_itShape++) { pProgressBar->Update( ++progress ); #ifdef UNICODE std::wostringstream l_ossTitle; #else std::ostringstream l_ossTitle; #endif HeeksObj * solid = solids[ l_itShape->first ]; l_ossTitle << "Machined " << solid->GetTitle(); HeeksObj *pNewSolid = heeksCAD->NewSolid( *((TopoDS_Solid *) &(l_itShape->second)), l_ossTitle.str().c_str(), HeeksColor(234, 123, 89) ); if (pNewSolid != NULL) { heeksCAD->Add( pNewSolid, NULL ); // Add the machined solid heeksCAD->Remove( solid ); // Delete the original. } // End if - then } // End for heeksCAD->Repaint(); } // End try catch(Standard_ConstructionError) { } catch(Standard_DomainError) { wxMessageBox(_T("Standard_DomainError thrown during shape operations\n")); } catch(...) { // Let's not kill everything just because I can't write clean code. wxMessageBox(_T("Unexpected exception thrown during shape operations\n")); } } wxString BitmapPath(){ return theApp.GetResFolder() + _T("/bitmaps/setinactive.png"); } }; static ApplyNCCode apply_nc_code; void CNCCode::GetTools(std::list<Tool*>* t_list, const wxPoint* p) { // t_list->push_back(&apply_nc_code); // It's not ready yet. HeeksObj::GetTools(t_list, p); } HeeksObj *CNCCode::MakeACopy(void)const{return new CNCCode(*this);} void CNCCode::CopyFrom(const HeeksObj* object){operator=(*((CNCCode*)object));} void CNCCode::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = heeksCAD->NewXMLElement( "nccode" ); heeksCAD->LinkXMLEndChild( root, element ); for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; block->WriteXML(element); } element->SetAttribute( "edited", m_user_edited ? 1:0); WriteBaseXML(element); } bool CNCCode::CanAdd(HeeksObj* object) { return ((object != NULL) && (object->GetType() == NCCodeBlockType)); } bool CNCCode::CanAddTo(HeeksObj* owner) { return ((owner != NULL) && (owner->GetType() == ProgramType || owner->GetType() == TrsfNCCodeType)); } void CNCCode::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction) { if(marked_object->m_map.size() > 0) { MarkedObject* sub_marked_object = marked_object->m_map.begin()->second; if(sub_marked_object) { if(sub_marked_object->m_map.size() > 0) { HeeksObj* object = sub_marked_object->m_map.begin()->first; if(object && object->GetType() == NCCodeBlockType) { m_highlighted_block = (CNCCodeBlock*)object; int from_pos = m_highlighted_block->m_from_pos; int to_pos = m_highlighted_block->m_to_pos; DestroyGLLists(); theApp.m_output_canvas->m_textCtrl->ShowPosition(from_pos); theApp.m_output_canvas->m_textCtrl->SetSelection(from_pos, to_pos); } } } } } //static HeeksObj* CNCCode::ReadFromXMLElement(TiXmlElement* element) { CNCCode* new_object = new CNCCode; pos = 0; CNCCodeBlock::multiplier = 1.0; PathObject::m_current_x[0] = PathObject::m_current_x[1] = PathObject::m_current_x[2] = 0.0; // loop through all the objects for(TiXmlElement* pElem = heeksCAD->FirstXMLChildElement( element ); pElem; pElem = pElem->NextSiblingElement()) { std::string name(pElem->Value()); if(name == "ncblock") { HeeksObj* object = CNCCodeBlock::ReadFromXMLElement(pElem); new_object->m_blocks.push_back((CNCCodeBlock*)object); } } // loop through the attributes int i; element->Attribute("edited", &i); new_object->m_user_edited = (i != 0); new_object->ReadBaseXML(element); new_object->SetTextCtrl(theApp.m_output_canvas->m_textCtrl); return new_object; } void CNCCode::DestroyGLLists(void) { if (m_gl_list) { glDeleteLists(m_gl_list, 1); m_gl_list = 0; } } void CNCCode::SetTextCtrlStyles(COutputTextCtrl *textCtrl) { textCtrl->StyleSetFontAttr(wxSTC_STYLE_DEFAULT, 10, _T("Lucida Console"), 0, 0, 0); textCtrl->StyleClearAll(); for (int i = 0; i < m_colors.size(); i++) { const HeeksColor &col = m_colors[i]; wxColour c(col.red, col.green, col.blue); textCtrl->StyleSetForeground(i, c); } } void CNCCode::SetTextCtrl(COutputTextCtrl *textCtrl) { textCtrl->Clear(); textCtrl->Freeze(); SetTextCtrlStyles(textCtrl); wxString str; for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; block->AppendText(str); } textCtrl->SetValue(str); for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; block->FormatText(textCtrl); } textCtrl->Thaw(); } void CNCCode::FormatBlocks(COutputTextCtrl *textCtrl, int i0, int i1) { textCtrl->Freeze(); SetTextCtrlStyles(textCtrl); for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; if (i0 <= block->m_from_pos && block->m_from_pos <= i1) block->FormatText(textCtrl); } textCtrl->Thaw(); } void CNCCode::HighlightBlock(long pos) { m_highlighted_block = NULL; for(std::list<CNCCodeBlock*>::iterator It = m_blocks.begin(); It != m_blocks.end(); It++) { CNCCodeBlock* block = *It; if(pos < block->m_to_pos) { m_highlighted_block = block; break; } } DestroyGLLists(); } static double Distance( const gp_Pnt start, const gp_Pnt end ) { double x_squared = (start.X() - end.X()) * (start.X() - end.X()); double y_squared = (start.Y() - end.Y()) * (start.Y() - end.Y()); double z_squared = (start.Z() - end.Z()) * (start.Z() - end.Z()); return( sqrt( x_squared + y_squared + z_squared ) ); } // End Distance() routine /** Generate as many points as is necessary such that the tool turns to the next cutting edge and, in that time (based on the spindle speed) advances at the feed rate. We want to calculate material removal rate on a per-cutting edge basis. */ std::list<gp_Pnt> PathLine::Interpolate( const gp_Pnt & start_point, const gp_Pnt & end_point, const double feed_rate, const double spindle_rpm, const unsigned int number_of_cutting_edges) const { std::list<gp_Pnt> points; double spindle_rps = spindle_rpm / 60.0; // Revolutions Per Second. double time_between_cutting_edges = (1 / spindle_rps) / number_of_cutting_edges; double advance_distance = (feed_rate / 60.0) * time_between_cutting_edges; double number_of_interpolated_points = Distance( start_point, end_point ) / advance_distance; points.push_back( start_point ); for ( int i=0; i < int(floor(number_of_interpolated_points)); i++) { double x = (((start_point.X() - end_point.X()) / number_of_interpolated_points) * i) + start_point.X(); double y = (((start_point.Y() - end_point.Y()) / number_of_interpolated_points) * i) + start_point.Y(); double z = (((start_point.Z() - end_point.Z()) / number_of_interpolated_points) * i) + start_point.Z(); points.push_back( gp_Pnt( x, y, z ) ); } // End for points.push_back( end_point ); return(points); } // End Interpolate() method std::list<gp_Pnt> PathArc::Interpolate( const PathObject *previous_point, const double feed_rate, const double spindle_rpm, const unsigned int number_of_cutting_edges) const { std::list<gp_Pnt> points; double spindle_rps = spindle_rpm / 60.0; // Revolutions Per Second. double time_between_cutting_edges = (1 / spindle_rps) / number_of_cutting_edges; double advance_distance = (feed_rate / 60.0) * time_between_cutting_edges; // This distance is wrong for arcs. We're doing a straight line distance but we really want a distance // around the arc. TODO Fix this. double number_of_interpolated_points = Distance( gp_Pnt( previous_point->m_x[0], previous_point->m_x[1], previous_point->m_x[2] ), gp_Pnt( m_x[0], m_x[1], m_x[2] ) ) / advance_distance; points = Interpolate( previous_point, (unsigned int) (floor(number_of_interpolated_points)) ); return(points); } // End Interpolate() method std::list< std::pair<PathObject *, CTool *> > CNCCode::GetPaths() const { std::list< std::pair<PathObject *, CTool *> > paths; for(std::list<CNCCodeBlock*>::const_iterator l_itCodeBlock = m_blocks.begin(); l_itCodeBlock != m_blocks.end(); l_itCodeBlock++) { for (std::list<ColouredPath>::const_iterator l_itColouredPath = (*l_itCodeBlock)->m_line_strips.begin(); l_itColouredPath != (*l_itCodeBlock)->m_line_strips.end(); l_itColouredPath++) { for (std::list< PathObject* >::const_iterator l_itPoint = l_itColouredPath->m_points.begin(); l_itPoint != l_itColouredPath->m_points.end(); l_itPoint++) { CTool *pTool = CTool::Find( (*l_itPoint)->m_tool_number ); if (pTool != NULL) { paths.push_back( std::make_pair( *l_itPoint, pTool ) ); } // End if - then } // End for } // End for } // End for return(paths); } // End GetPaths() method
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkGradientShader.h" using namespace skiagm; struct GradData { int fCount; const SkColor* fColors; const SkScalar* fPos; }; static const SkColor gColors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK, }; //static const SkScalar gPos[] = { SK_Scalar1*999/2000, SK_Scalar1*1001/2000 }; static const GradData gGradData[] = { { 40, gColors, NULL }, // { 2, gColors, gPos }, // { 2, gCol2, NULL }, }; static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateRadial(center, center.fX, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount, mapper); } typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper); static const GradMaker gGradMakers[] = { MakeLinear, MakeRadial, MakeSweep, }; /////////////////////////////////////////////////////////////////////////////// class GradientsGM : public GM { public: GradientsGM() { this->setBGColor(0xFFDDDDDD); } protected: SkString onShortName() SK_OVERRIDE { return SkString("gradient_dirty_laundry"); } virtual SkISize onISize() SK_OVERRIDE { return make_isize(640, 615); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkPoint pts[2] = { { 0, 0 }, { SkIntToScalar(100), SkIntToScalar(100) } }; SkShader::TileMode tm = SkShader::kClamp_TileMode; SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) }; SkPaint paint; paint.setAntiAlias(true); canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) { canvas->save(); for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) { SkShader* shader = gGradMakers[j](pts, gGradData[i], tm, NULL); paint.setShader(shader)->unref(); canvas->drawRect(r, paint); canvas->translate(0, SkIntToScalar(120)); } canvas->restore(); canvas->translate(SkIntToScalar(120), 0); } } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new GradientsGM; } static GMRegistry reg(MyFactory);
/* * Swift Parallel Scripting Language (http://swift-lang.org) * * Copyright 2012-2014 University of Chicago * * 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 "Command.h" #include "CmdCBCV.h" #include "Logger.h" #include "CoasterError.h" using std::list; using std::string; using std::vector; using namespace Coaster; Command::Command(const string* pname) { name = pname; ferrorReceived = false; freceiveCompleted = false; } const string* Command::getName() { return name; } void Command::send(CoasterChannel* channel) { send(channel, NULL); } void Command::send(CoasterChannel* channel, CommandCallback* pcb) { cb = pcb; channel->registerCommand(this); list<Buffer*>* od = getOutData(); channel->send(tag, Buffer::wrap(name), od->empty() ? FLAG_FINAL + FLAG_INITIAL : FLAG_INITIAL, this); while (od->size() > 0) { Buffer* b = od->front(); channel->send(tag, b, od->size() == 1 ? FLAG_FINAL : 0, this); od->pop_front(); } } void Command::execute(CoasterChannel* channel) { CmdCBCV cb; send(channel, &cb); cb.wait(); if (ferrorReceived) { string* msg = getErrorMessage(); RemoteCoasterException* detail = getErrorDetail(); if (msg == NULL) { throw CoasterError("Command failed"); } else if (detail == NULL) { throw CoasterError("Command failed: %s", msg->c_str()); } else { throw CoasterError("Command failed: %s\n%s", msg->c_str(), detail->str().c_str()); } delete detail; delete msg; } } void Command::receiveCompleted(int flags) { freceiveCompleted = true; if (flags & FLAG_ERROR) { ferrorReceived = true; errorReceived(); } else { replyReceived(); } } void Command::errorReceived() { if (cb != NULL) { string* msg = getErrorMessage(); RemoteCoasterException* detail = getErrorDetail(); cb->errorReceived(this, msg, detail); delete msg; delete detail; } } string* Command::getErrorMessage() { vector<Buffer*>* errorData = getErrorData(); if (errorData != NULL && errorData->size() > 0) { return errorData->at(0)->str(); } else { return NULL; } } RemoteCoasterException* Command::getErrorDetail() { vector<Buffer*>* errorData = getErrorData(); if (errorData != NULL && errorData->size() > 1) { return new RemoteCoasterException(errorData->at(1)->getData(), errorData->at(1)->getLen()); } else { return NULL; } } void Command::replyReceived() { if (cb != NULL) { cb->replyReceived(this); } } bool Command::isReceiveCompleted() const { return freceiveCompleted; } bool Command::isErrorReceived() const { return ferrorReceived; } void Command::dataSent(Buffer* buf) { delete buf; }
class C { std::mutex mutex; int f_impl(int n) { return (n == 0) ? 1 : n*f_impl(n-1); } public: // GOOD: recursion is delegated to f_impl. int f(int n) { mutex.lock(); int result = f_impl(n); mutex.unlock(); return result; } };
// Copyright (c) 2022 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // // $hash=1a7a3f0cd61dab86aae86ca54e5554671d1850b7$ // #include "libcef_dll/cpptoc/views/textfield_delegate_cpptoc.h" #include "libcef_dll/ctocpp/views/textfield_ctocpp.h" #include "libcef_dll/ctocpp/views/view_ctocpp.h" #include "libcef_dll/shutdown_checker.h" #include "libcef_dll/template_util.h" namespace { // MEMBER FUNCTIONS - Body may be edited by hand. int CEF_CALLBACK textfield_delegate_on_key_event(struct _cef_textfield_delegate_t* self, cef_textfield_t* textfield, const struct _cef_key_event_t* event) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: textfield; type: refptr_diff DCHECK(textfield); if (!textfield) return 0; // Verify param: event; type: struct_byref_const DCHECK(event); if (!event) return 0; if (!template_util::has_valid_size(event)) { NOTREACHED() << "invalid event->[base.]size"; return 0; } // Translate param: event; type: struct_byref_const CefKeyEvent eventObj; if (event) eventObj.Set(*event, false); // Execute bool _retval = CefTextfieldDelegateCppToC::Get(self)->OnKeyEvent( CefTextfieldCToCpp::Wrap(textfield), eventObj); // Return type: bool return _retval; } void CEF_CALLBACK textfield_delegate_on_after_user_action(struct _cef_textfield_delegate_t* self, cef_textfield_t* textfield) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: textfield; type: refptr_diff DCHECK(textfield); if (!textfield) return; // Execute CefTextfieldDelegateCppToC::Get(self)->OnAfterUserAction( CefTextfieldCToCpp::Wrap(textfield)); } cef_size_t CEF_CALLBACK textfield_delegate_get_preferred_size(struct _cef_view_delegate_t* self, cef_view_t* view) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->GetPreferredSize(CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK textfield_delegate_get_minimum_size(struct _cef_view_delegate_t* self, cef_view_t* view) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->GetMinimumSize(CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK textfield_delegate_get_maximum_size(struct _cef_view_delegate_t* self, cef_view_t* view) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return CefSize(); // Execute cef_size_t _retval = CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->GetMaximumSize(CefViewCToCpp::Wrap(view)); // Return type: simple return _retval; } int CEF_CALLBACK textfield_delegate_get_height_for_width(struct _cef_view_delegate_t* self, cef_view_t* view, int width) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return 0; // Execute int _retval = CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->GetHeightForWidth(CefViewCToCpp::Wrap(view), width); // Return type: simple return _retval; } void CEF_CALLBACK textfield_delegate_on_parent_view_changed(struct _cef_view_delegate_t* self, cef_view_t* view, int added, cef_view_t* parent) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Verify param: parent; type: refptr_diff DCHECK(parent); if (!parent) return; // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnParentViewChanged(CefViewCToCpp::Wrap(view), added ? true : false, CefViewCToCpp::Wrap(parent)); } void CEF_CALLBACK textfield_delegate_on_child_view_changed(struct _cef_view_delegate_t* self, cef_view_t* view, int added, cef_view_t* child) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Verify param: child; type: refptr_diff DCHECK(child); if (!child) return; // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnChildViewChanged(CefViewCToCpp::Wrap(view), added ? true : false, CefViewCToCpp::Wrap(child)); } void CEF_CALLBACK textfield_delegate_on_window_changed(struct _cef_view_delegate_t* self, cef_view_t* view, int added) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnWindowChanged(CefViewCToCpp::Wrap(view), added ? true : false); } void CEF_CALLBACK textfield_delegate_on_layout_changed(struct _cef_view_delegate_t* self, cef_view_t* view, const cef_rect_t* new_bounds) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Verify param: new_bounds; type: simple_byref_const DCHECK(new_bounds); if (!new_bounds) return; // Translate param: new_bounds; type: simple_byref_const CefRect new_boundsVal = new_bounds ? *new_bounds : CefRect(); // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnLayoutChanged(CefViewCToCpp::Wrap(view), new_boundsVal); } void CEF_CALLBACK textfield_delegate_on_focus(struct _cef_view_delegate_t* self, cef_view_t* view) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnFocus(CefViewCToCpp::Wrap(view)); } void CEF_CALLBACK textfield_delegate_on_blur(struct _cef_view_delegate_t* self, cef_view_t* view) { shutdown_checker::AssertNotShutdown(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: view; type: refptr_diff DCHECK(view); if (!view) return; // Execute CefTextfieldDelegateCppToC::Get( reinterpret_cast<cef_textfield_delegate_t*>(self)) ->OnBlur(CefViewCToCpp::Wrap(view)); } } // namespace // CONSTRUCTOR - Do not edit by hand. CefTextfieldDelegateCppToC::CefTextfieldDelegateCppToC() { GetStruct()->on_key_event = textfield_delegate_on_key_event; GetStruct()->on_after_user_action = textfield_delegate_on_after_user_action; GetStruct()->base.get_preferred_size = textfield_delegate_get_preferred_size; GetStruct()->base.get_minimum_size = textfield_delegate_get_minimum_size; GetStruct()->base.get_maximum_size = textfield_delegate_get_maximum_size; GetStruct()->base.get_height_for_width = textfield_delegate_get_height_for_width; GetStruct()->base.on_parent_view_changed = textfield_delegate_on_parent_view_changed; GetStruct()->base.on_child_view_changed = textfield_delegate_on_child_view_changed; GetStruct()->base.on_window_changed = textfield_delegate_on_window_changed; GetStruct()->base.on_layout_changed = textfield_delegate_on_layout_changed; GetStruct()->base.on_focus = textfield_delegate_on_focus; GetStruct()->base.on_blur = textfield_delegate_on_blur; } // DESTRUCTOR - Do not edit by hand. CefTextfieldDelegateCppToC::~CefTextfieldDelegateCppToC() { shutdown_checker::AssertNotShutdown(); } template <> CefRefPtr<CefTextfieldDelegate> CefCppToCRefCounted< CefTextfieldDelegateCppToC, CefTextfieldDelegate, cef_textfield_delegate_t>::UnwrapDerived(CefWrapperType type, cef_textfield_delegate_t* s) { NOTREACHED() << "Unexpected class type: " << type; return nullptr; } template <> CefWrapperType CefCppToCRefCounted<CefTextfieldDelegateCppToC, CefTextfieldDelegate, cef_textfield_delegate_t>::kWrapperType = WT_TEXTFIELD_DELEGATE;
#ifndef SPROUT_RANGE_ALGORITHM_FIT_COPY_HPP #define SPROUT_RANGE_ALGORITHM_FIT_COPY_HPP #include <sprout/config.hpp> #include <sprout/container/traits.hpp> #include <sprout/container/functions.hpp> #include <sprout/algorithm/fit/result_of.hpp> #include <sprout/algorithm/fit/copy.hpp> namespace sprout { namespace range { namespace fit { // // copy // template<typename Input, typename Result> inline SPROUT_CONSTEXPR typename sprout::fit::result_of::algorithm<Result>::type copy( Input const& input, Result const& result ) { return sprout::fit::copy(sprout::begin(input), sprout::end(input), result); } } // namespace fit } // namespace range } // namespace sprout #endif // #ifndef SPROUT_RANGE_ALGORITHM_FIT_COPY_HPP
#include "pxt.h" using namespace pxt; namespace test { //% void dammy(int32_t x, int32_t y){ uBit.display.image.setPixelValue(0, 0, 255); } }
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 "tvgLoader.h" #include "tvgPngLoader.h" /************************************************************************/ /* Internal Class Implementation */ /************************************************************************/ /************************************************************************/ /* External Class Implementation */ /************************************************************************/ PngLoader::PngLoader() { //TODO: } PngLoader::~PngLoader() { //TODO: } bool PngLoader::open(const string& path) { //TODO: return false; } bool PngLoader::open(const char* data, uint32_t size, bool copy) { //TODO: return false; } bool PngLoader::read() { //TODO: return false; } bool PngLoader::close() { //TODO: return false; } const uint32_t* PngLoader::pixels() { //TODO: return nullptr; }
#include <boost/config/warning_disable.hpp>
#include "unit_tests.h" void testFlow() { System* s1 = new System(); System* s2 = new System(); //Testing the exponential model Flow* test1 = new Exponential(s1,s2); assert(test1->getSource() == s1); assert(test1->getDestination() == s2); //Testing the logistic model Flow* test2 = new Logistic(s1,s2); assert(test2->getSource() == s1); assert(test2->getDestination() == s2); } void testModel(){ Model* modelTest = new Model(); System* s1= new System(); s1->setValue(100.0); System* s2 = new System(); s2->setValue(0.0); Exponential* f = new Exponential(s1,s2); modelTest->add(f); modelTest->add(s1); modelTest->add(s2); } void testSystem(){ System* s1 = new System(); s1->setName("Name"); s1->setValue(0); assert(s1->getName() == "Name"); assert(s1->getValue() == 0); }
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /// \file container_adaptor/multimap_adaptor.hpp /// \brief Container adaptor to easily build a std::multimap signature compatible container. #ifndef BOOST_BIMAP_CONTAINER_ADAPTOR_MULTIMAP_ADAPTOR_HPP #define BOOST_BIMAP_CONTAINER_ADAPTOR_MULTIMAP_ADAPTOR_HPP #if defined(_MSC_VER) #pragma once #endif #include <boost/config.hpp> #include <boost/bimap/container_adaptor/ordered_associative_container_adaptor.hpp> #include <boost/bimap/container_adaptor/detail/non_unique_container_helper.hpp> #include <boost/mpl/aux_/na.hpp> #include <boost/mpl/vector.hpp> namespace boost { namespace bimaps { namespace container_adaptor { /// \brief Container adaptor to easily build a std::multimap signature compatible container. template < class Base, class Iterator, class ConstIterator, class ReverseIterator, class ConstReverseIterator, class IteratorToBaseConverter = ::boost::mpl::na, class IteratorFromBaseConverter = ::boost::mpl::na, class ReverseIteratorFromBaseConverter = ::boost::mpl::na, class ValueToBaseConverter = ::boost::mpl::na, class ValueFromBaseConverter = ::boost::mpl::na, class KeyToBaseConverter = ::boost::mpl::na, class FunctorsFromDerivedClasses = mpl::vector<> > class multimap_adaptor : public ::boost::bimaps::container_adaptor:: ordered_associative_container_adaptor < Base, Iterator, ConstIterator, ReverseIterator, ConstReverseIterator, BOOST_DEDUCED_TYPENAME Iterator::value_type::first_type, IteratorToBaseConverter, IteratorFromBaseConverter, ReverseIteratorFromBaseConverter, ValueToBaseConverter, ValueFromBaseConverter, KeyToBaseConverter, FunctorsFromDerivedClasses > { typedef ::boost::bimaps::container_adaptor:: ordered_associative_container_adaptor < Base, Iterator, ConstIterator, ReverseIterator, ConstReverseIterator, BOOST_DEDUCED_TYPENAME Iterator::value_type::first_type, IteratorToBaseConverter, IteratorFromBaseConverter, ReverseIteratorFromBaseConverter, ValueToBaseConverter, ValueFromBaseConverter, KeyToBaseConverter, FunctorsFromDerivedClasses > base_; // MetaData ------------------------------------------------------------- public: typedef BOOST_DEDUCED_TYPENAME Iterator::value_type::second_type data_type; typedef data_type mapped_type; // Access ----------------------------------------------------------------- public: explicit multimap_adaptor(Base & c) : base_(c) {} protected: typedef multimap_adaptor multimap_adaptor_; public: BOOST_BIMAP_NON_UNIQUE_CONTAINER_ADAPTOR_INSERT_FUNCTIONS }; } // namespace container_adaptor } // namespace bimaps } // namespace boost #endif // BOOST_BIMAP_CONTAINER_ADAPTOR_MULTIMAP_ADAPTOR_HPP
/* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. */ #include <iostream> #include <vector> using namespace std; class Solution { public: // int result = 0; // int len = height.size(); // if (len <= 2) // return 0; // int l = 0; // int w = 1; // bool leftwall = false; // int temp = 0; // while (l + w <= len - 1) { // while (height[l + w] < height[l] && l + w <= len - 1) { // temp += height[l + w]; // w++; // if (l + w > len - 1 && w > 1) { // w = 1; // temp = 0; // l++; // leftwall = true; // } // } // if (leftwall) { // result += (max(height[l], height[l + w]) * w) - temp - // (min(height[l], height[l + w])); // } else // result += (min(height[l], height[l + w]) * (w - 1)) - temp; // leftwall = false; // l = l + w; // w = 1; // temp = 0; // } // return result; // } int trap(vector<int>& height) { int l = 0, r = height.size()-1, level = 0, water = 0; while (l < r) { int lower = height[height[l] < height[r] ? l++ : r--]; level = max(level, lower); water += level - lower; } return water; } }; int main() { vector<int> height = {4, 2, 3}; //{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; Solution obj; cout << obj.trap(height); }
// RUN: %clang -cc1 -verify -std=c++11 %s 8gi///===--- recovery.cpp ---===// // expected-error {{unqualified-id}} namespace Std { // expected-note {{here}} typedef int Important; } / redeclare as an inline namespace // expected-error {{unqualified-id}} inline namespace Std { // expected-error {{cannot be reopened as inline}} Important n; } / end namespace Std // expected-error {{unqualified-id}} int x; Std::Important y; extenr "C" { // expected-error {{did you mean the keyword 'extern'}} void f(); } void g() { z = 1; // expected-error {{undeclared}} f(); } struct S { int a, b, c; S(); }; 8S::S() : a{ 5 }, b{ 6 }, c{ 2 } { // expected-error {{unqualified-id}} return; } int k; int l = k; 5int m = { l }, n = m; // expected-error {{unqualified-id}} namespace N { int } // expected-error {{unqualified-id}} strcut Uuuu { // expected-error {{did you mean the keyword 'struct'}} \ // expected-note {{'Uuuu' declared here}} } *u[3]; uuuu v; // expected-error {{did you mean 'Uuuu'}}
#include "globalSignalHandle.h" namespace global_sighandle { int no_meaning_test = 0; } // namespace global_sighandle
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "font_collection.h" #include <algorithm> #include <list> #include <memory> #include <mutex> #include <set> #include <string> #include <unordered_map> #include <vector> #include "flutter/fml/logging.h" #include "font_skia.h" #include "txt/platform.h" #include "txt/text_style.h" namespace txt { namespace { const std::shared_ptr<minikin::FontFamily> g_null_family; } // anonymous namespace FontCollection::FamilyKey::FamilyKey(const std::vector<std::string>& families, const std::string& loc) { locale = loc; std::stringstream stream; for_each(families.begin(), families.end(), [&stream](const std::string& str) { stream << str << ','; }); font_families = stream.str(); } bool FontCollection::FamilyKey::operator==( const FontCollection::FamilyKey& other) const { return font_families == other.font_families && locale == other.locale; } size_t FontCollection::FamilyKey::Hasher::operator()( const FontCollection::FamilyKey& key) const { return std::hash<std::string>()(key.font_families) ^ std::hash<std::string>()(key.locale); } class TxtFallbackFontProvider : public minikin::FontCollection::FallbackFontProvider { public: TxtFallbackFontProvider(std::shared_ptr<FontCollection> font_collection) : font_collection_(font_collection) {} virtual const std::shared_ptr<minikin::FontFamily>& matchFallbackFont( uint32_t ch, std::string locale) { std::shared_ptr<FontCollection> fc = font_collection_.lock(); if (fc) { return fc->MatchFallbackFont(ch, locale); } else { return g_null_family; } } private: std::weak_ptr<FontCollection> font_collection_; }; FontCollection::FontCollection() : enable_font_fallback_(true) {} FontCollection::~FontCollection() = default; size_t FontCollection::GetFontManagersCount() const { return GetFontManagerOrder().size(); } void FontCollection::SetDefaultFontManager(sk_sp<SkFontMgr> font_manager) { default_font_manager_ = font_manager; } void FontCollection::SetAssetFontManager(sk_sp<SkFontMgr> font_manager) { asset_font_manager_ = font_manager; } void FontCollection::SetDynamicFontManager(sk_sp<SkFontMgr> font_manager) { dynamic_font_manager_ = font_manager; } void FontCollection::SetTestFontManager(sk_sp<SkFontMgr> font_manager) { test_font_manager_ = font_manager; } // Return the available font managers in the order they should be queried. std::vector<sk_sp<SkFontMgr>> FontCollection::GetFontManagerOrder() const { std::vector<sk_sp<SkFontMgr>> order; if (dynamic_font_manager_) order.push_back(dynamic_font_manager_); if (asset_font_manager_) order.push_back(asset_font_manager_); if (test_font_manager_) order.push_back(test_font_manager_); if (default_font_manager_) order.push_back(default_font_manager_); return order; } void FontCollection::DisableFontFallback() { enable_font_fallback_ = false; } std::shared_ptr<minikin::FontCollection> FontCollection::GetMinikinFontCollectionForFamilies( const std::vector<std::string>& font_families, const std::string& locale) { // Look inside the font collections cache first. FamilyKey family_key(font_families, locale); auto cached = font_collections_cache_.find(family_key); if (cached != font_collections_cache_.end()) { return cached->second; } std::vector<std::shared_ptr<minikin::FontFamily>> minikin_families; // Search for all user provided font families. for (size_t fallback_index = 0; fallback_index < font_families.size(); fallback_index++) { std::shared_ptr<minikin::FontFamily> minikin_family = FindFontFamilyInManagers(font_families[fallback_index]); if (minikin_family != nullptr) { minikin_families.push_back(minikin_family); } } // Search for default font family if no user font families were found. if (minikin_families.empty()) { const auto default_font_family = GetDefaultFontFamily(); std::shared_ptr<minikin::FontFamily> minikin_family = FindFontFamilyInManagers(default_font_family); if (minikin_family != nullptr) { minikin_families.push_back(minikin_family); } } // Default font family also not found. We fail to get a FontCollection. if (minikin_families.empty()) { return nullptr; } if (enable_font_fallback_) { for (std::string fallback_family : fallback_fonts_for_locale_[locale]) { auto it = fallback_fonts_.find(fallback_family); if (it != fallback_fonts_.end()) { minikin_families.push_back(it->second); } } } // Create the minikin font collection. auto font_collection = std::make_shared<minikin::FontCollection>(std::move(minikin_families)); if (enable_font_fallback_) { font_collection->set_fallback_font_provider( std::make_unique<TxtFallbackFontProvider>(shared_from_this())); } // Cache the font collection for future queries. font_collections_cache_[family_key] = font_collection; return font_collection; } std::shared_ptr<minikin::FontFamily> FontCollection::FindFontFamilyInManagers( const std::string& family_name) { // Search for the font family in each font manager. for (sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) { std::shared_ptr<minikin::FontFamily> minikin_family = CreateMinikinFontFamily(manager, family_name); if (!minikin_family) continue; return minikin_family; } return nullptr; } std::shared_ptr<minikin::FontFamily> FontCollection::CreateMinikinFontFamily( const sk_sp<SkFontMgr>& manager, const std::string& family_name) { sk_sp<SkFontStyleSet> font_style_set( manager->matchFamily(family_name.c_str())); if (font_style_set == nullptr || font_style_set->count() == 0) { return nullptr; } std::vector<minikin::Font> minikin_fonts; // Add fonts to the Minikin font family. for (int i = 0; i < font_style_set->count(); ++i) { // Create the skia typeface. sk_sp<SkTypeface> skia_typeface( sk_sp<SkTypeface>(font_style_set->createTypeface(i))); if (skia_typeface == nullptr) { continue; } // Create the minikin font from the skia typeface. // Divide by 100 because the weights are given as "100", "200", etc. minikin::Font minikin_font( std::make_shared<FontSkia>(skia_typeface), minikin::FontStyle{skia_typeface->fontStyle().weight() / 100, skia_typeface->isItalic()}); minikin_fonts.emplace_back(std::move(minikin_font)); } return std::make_shared<minikin::FontFamily>(std::move(minikin_fonts)); } const std::shared_ptr<minikin::FontFamily>& FontCollection::MatchFallbackFont( uint32_t ch, std::string locale) { // Check if the ch's matched font has been cached. We cache the results of // this method as repeated matchFamilyStyleCharacter calls can become // extremely laggy when typing a large number of complex emojis. auto lookup = fallback_match_cache_.find(ch); if (lookup != fallback_match_cache_.end()) { return *lookup->second; } const std::shared_ptr<minikin::FontFamily>* match = &DoMatchFallbackFont(ch, locale); fallback_match_cache_.insert(std::make_pair(ch, match)); return *match; } const std::shared_ptr<minikin::FontFamily>& FontCollection::DoMatchFallbackFont( uint32_t ch, std::string locale) { for (const sk_sp<SkFontMgr>& manager : GetFontManagerOrder()) { std::vector<const char*> bcp47; if (!locale.empty()) bcp47.push_back(locale.c_str()); sk_sp<SkTypeface> typeface(manager->matchFamilyStyleCharacter( 0, SkFontStyle(), bcp47.data(), bcp47.size(), ch)); if (!typeface) continue; SkString sk_family_name; typeface->getFamilyName(&sk_family_name); std::string family_name(sk_family_name.c_str()); fallback_fonts_for_locale_[locale].insert(family_name); return GetFallbackFontFamily(manager, family_name); } return g_null_family; } const std::shared_ptr<minikin::FontFamily>& FontCollection::GetFallbackFontFamily(const sk_sp<SkFontMgr>& manager, const std::string& family_name) { auto fallback_it = fallback_fonts_.find(family_name); if (fallback_it != fallback_fonts_.end()) { return fallback_it->second; } std::shared_ptr<minikin::FontFamily> minikin_family = CreateMinikinFontFamily(manager, family_name); if (!minikin_family) return g_null_family; auto insert_it = fallback_fonts_.insert(std::make_pair(family_name, minikin_family)); // Clear the cache to force creation of new font collections that will // include this fallback font. font_collections_cache_.clear(); return insert_it.first->second; } void FontCollection::ClearFontFamilyCache() { font_collections_cache_.clear(); } } // namespace txt
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <armadillo> namespace py = pybind11; using namespace arma; typedef py::array_t<double, py::array::f_style | py::array::forcecast> array_tf; typedef py::array_t<double, py::array::c_style | py::array::forcecast> array_tc; cube array_to_cube(array_tf m) { py::buffer_info _m_buff = m.request(); int n_rows = _m_buff.shape[0]; int n_cols = _m_buff.shape[1]; int n_slices = _m_buff.shape[2]; cube _m_arma((double *)_m_buff.ptr, n_rows, n_cols, n_slices); return _m_arma; } mat array_to_mat(array_tf m) { py::buffer_info _m_buff = m.request(); int n_rows = _m_buff.shape[0]; int n_cols = _m_buff.shape[1]; mat _m_arma((double *)_m_buff.ptr, n_rows, n_cols); return _m_arma; } vec array_to_vec(array_tf m) { py::buffer_info _m_buff = m.request(); int n_rows = _m_buff.shape[0]; vec _m_vec((double *)_m_buff.ptr, n_rows); return _m_vec; } array_tf cube_to_array(cube m) { auto _m_array = array_tf({m.n_rows, m.n_cols, m.n_slices}); py::buffer_info _m_buff = _m_array.request(); std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols * m.n_slices); return _m_array; } array_tf mat_to_array(mat m) { auto _m_array = array_tf({m.n_rows, m.n_cols}); py::buffer_info _m_buff = _m_array.request(); std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols); return _m_array; } array_tf vec_to_array(vec m) { auto _m_array = array_tf({m.n_rows}); py::buffer_info _m_buff = _m_array.request(); std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows); return _m_array; } py::tuple backward_pass(array_tf _Q, array_tf _q, array_tf _R, array_tf _r, array_tf _P, array_tf _p, array_tf _F, array_tf _G, array_tf _T, array_tf _U, array_tf _V, array_tf _X, array_tf _Y, array_tf _Z, double lmbda, int reg, int nb_bdim, int nb_udim, int nb_steps) { // inputs cube Q = array_to_cube(_Q); mat q = array_to_mat(_q); cube R = array_to_cube(_R); mat r = array_to_mat(_r); cube P = array_to_cube(_P); mat p = array_to_mat(_p); cube F = array_to_cube(_F); cube G = array_to_cube(_G); cube T = array_to_cube(_T); cube U = array_to_cube(_U); cube V = array_to_cube(_V); cube X = array_to_cube(_X); cube Y = array_to_cube(_Y); cube Z = array_to_cube(_Z); // outputs cube C(nb_bdim, nb_bdim, nb_steps); mat c(nb_bdim, nb_steps); cube D(nb_udim, nb_udim, nb_steps); mat d(nb_udim, nb_steps); cube E(nb_udim, nb_bdim, nb_steps); mat e(nb_bdim * nb_bdim, nb_steps); cube Ereg(nb_udim, nb_bdim, nb_steps); cube Dreg(nb_udim, nb_udim, nb_steps); cube Dinv(nb_udim, nb_udim, nb_steps); cube S(nb_bdim, nb_bdim, nb_steps + 1); mat s(nb_bdim, nb_steps + 1); mat tau(nb_bdim * nb_bdim, nb_steps + 1); vec dS(2); cube Sreg(nb_bdim, nb_bdim, nb_steps + 1); cube K(nb_udim, nb_bdim, nb_steps); mat kff(nb_udim, nb_steps); int _diverge = 0; // init last time step S.slice(nb_steps) = Q.slice(nb_steps); s.col(nb_steps) = q.col(nb_steps); tau.col(nb_steps) = p.col(nb_steps); for(int i = nb_steps - 1; i>= 0; --i) { C.slice(i) = Q.slice(i) + F.slice(i).t() * S.slice(i+1) * F.slice(i); D.slice(i) = R.slice(i) + G.slice(i).t() * S.slice(i+1) * G.slice(i); E.slice(i) = (P.slice(i) + F.slice(i).t() * S.slice(i+1) * G.slice(i)).t(); c.col(i) = q.col(i) + F.slice(i).t() * s.col(i+1) + T.slice(i).t() * tau.col(i+1) + 0.5 * X.slice(i).t() * vectorise(S.slice(i+1)); d.col(i) = r.col(i) + G.slice(i).t() * s.col(i+1) + V.slice(i).t() * tau.col(i+1) + 0.5 * Z.slice(i).t() * vectorise(S.slice(i+1)); e.col(i) = p.col(i) + U.slice(i).t() * tau.col(i) + 0.5 * Y.slice(i).t() * vectorise(S.slice(i+1)); Sreg.slice(i+1) = S.slice(i+1); if (reg==2) Sreg.slice(i+1) += lmbda * eye(nb_bdim, nb_bdim); Ereg.slice(i) = (P.slice(i) + F.slice(i).t() * Sreg.slice(i+1) * G.slice(i)).t(); Dreg.slice(i) = R.slice(i) + G.slice(i).t() * Sreg.slice(i+1) * G.slice(i); if (reg==1) Dreg.slice(i) += lmbda * eye(nb_udim, nb_udim); if (!(Dreg.slice(i)).is_sympd()) { _diverge = i; break; } Dinv.slice(i) = inv(Dreg.slice(i)); K.slice(i) = - Dinv.slice(i) * Ereg.slice(i); kff.col(i) = - Dinv.slice(i) * d.col(i); dS += join_vert(kff.col(i).t() * d.col(i), 0.5 * kff.col(i).t() * D.slice(i) * kff.col(i)); tau.col(i) = e.col(i); s.col(i) = c.col(i) + K.slice(i).t() * D.slice(i) * kff.col(i) + K.slice(i).t() * d.col(i) + E.slice(i).t() * kff.col(i); S.slice(i) = C.slice(i) + K.slice(i).t() * D.slice(i) * K.slice(i) + K.slice(i).t() * E.slice(i) + E.slice(i).t() * K.slice(i); S.slice(i) = 0.5 * (S.slice(i) + S.slice(i).t()); } // transform outputs to numpy array_tf _S = cube_to_array(S); array_tf _s = mat_to_array(s); array_tf _tau = mat_to_array(tau); array_tf _dS = vec_to_array(dS); array_tf _K = cube_to_array(K); array_tf _kff = mat_to_array(kff); py::tuple output = py::make_tuple(_S, _s, _tau, _dS, _K, _kff, _diverge); return output; } PYBIND11_MODULE(core, m) { m.def("backward_pass", &backward_pass); }
/* * Scene_Middleage_Jail.cpp * enigma * * Created by Rockford on 06/10/10. * Copyright 2010 Casual Games France. All rights reserved. * */ #include "EScene.h" #include "Scene_Middleage_Jail.h" #include "ESceneDirector.h" #include "GlobalBank.h" #include "EMiniJeuPlantAddition.h" #include "EMiniJeuGardening.h" #include "MusicBank.h" /* Constructeur */ Scene_Middleage_Jail::Scene_Middleage_Jail(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector) { _lpBgGraphic = KPTK::createKGraphic (); EMiniJeuGardening::Preload(); EMiniJeuPlantAddition::Preload(); } /* Destructeur */ Scene_Middleage_Jail::~Scene_Middleage_Jail() { delete _lpBgGraphic; } void Scene_Middleage_Jail::Init() { // Le contenu est prêt, on efface l'ancien if (TaskResolved("task_middleage_getplant4")) { SetupItem("middleage_contentplate_ready"); } if (isVisible("middleage_contentplate_ready")) { StartEmitter("flake_content"); SetVisible("middleage_contentplate", false, true); } else { StopEmitter("flake_content"); if (_lpSceneDirector->getInventory()->getItemFromInventory("inv_middleage_contentplate_ready")) { SetVisible("middleage_contentplate", false, true); } } // Sorcière par défait attend SetVisible("middleage_witch_wait", true, true); // Si on n'a pas encore rencontré la sorcière if (!TaskResolved("task_middleage_contactwitch")) { SetVisible("middleage_witch_wait", true, true); SetVisible("middleage_witch_ask", false, true); } else { int x,y; // Attente de la sorcière en fonction de la quête en cours if (TaskToResolve("task_middleage_getplate")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKPLATE"), "", false); } // Attend qu'on pose l'assiette else if (TaskToResolve("task_middleage_putplate")) { _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_SETPLATE"), "", false); } // Attend qu'on mettre une plante dans l'assiette else if (TaskToResolve("task_middleage_getplant1") || TaskToResolve("task_middleage_getplant2") || TaskToResolve("task_middleage_getplant3") || TaskToResolve("task_middleage_getplant4")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_SOWHAT"), "", false); } // Attend la préparation terminée else if (TaskToResolve("task_middleage_givecontent")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKCONTENT"), "", false); } // Attend la fiole else if (TaskToResolve("task_middleage_giveflask")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKFLASK"), "", false); } // Attend le bouchon else if (TaskToResolve("task_middleage_givecap")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKCAP"), "", false); } // Plantes à préparer else if (TaskToResolve("task_middleage_prepareplant1") || TaskToResolve("task_middleage_prepareplant2") || TaskToResolve("task_middleage_prepareplant3") || TaskToResolve("task_middleage_prepareplant4")) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); } else { _lpSceneDirector->getSequencer()->ShowImage(NULL,"middleage_witch_wait", true); GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_SOWHAT"), "", false); } } // Le plat a été posé if (TaskResolved("task_middleage_putplate")) { SetVisible("middleage_emptyplate", true); } // Les plantes dans l'assiette if (TaskResolved("task_middleage_startprepare") && !isVisible("middleage_contentplate_ready") && !_lpSceneDirector->getInventory()->getItemFromInventory("inv_middleage_contentplate_ready")) { // Affiche une plante dans l'assiette SetVisible("middleage_contentplate", true, true); } } void Scene_Middleage_Jail::Check() { EScene::Check(); #ifdef SCENE_SHORTCUT if (KInput::isPressed(K_VK_F5)) { _lpSceneDirector->GoToScene("menu"); } if (KInput::isPressed(K_VK_F6)) { } #endif } void Scene_Middleage_Jail::Logic() { EScene::Logic(); } void Scene_Middleage_Jail::Draw() { EScene::Draw(); } void Scene_Middleage_Jail::Close() { } bool Scene_Middleage_Jail::ObjectClicked(const char *szObjectName, float x, float y) { // Clic sur la sorcière la 1ère fois if (strcmp(szObjectName, "middleage_witch_wait") == 0) { int x,y; if( !TaskResolved("task_middleage_contactwitch")) { ResolveTask("task_middleage_contactwitch"); _lpSceneDirector->getSequencer()->PlaySound(NULL,"spooky_piano"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_RHAAA"), "", false); _lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_DIALOG, true); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_AFFRAID"), "", false, true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_IMNOT"), "", false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_LETMEHELP"), "", false); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_POISON"), "", false, true); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_OPEN"), "", false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_DIDYOUSAVE"), "", false); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_NOSAVE"), "", false, true); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_BRINGMEPLATE"), "", false); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_DIALOG, false); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_TRUSTHER"), "", true, false); AddObjective("middleage","help"); AddHint("middleage","help","plate"); AddHint("middleage","help","pestle"); AddTask("task_middleage_getplate"); return true; } if (TaskToResolve("task_middleage_putplant1") || TaskToResolve("task_middleage_putplant2") || TaskToResolve("task_middleage_putplant3") || TaskToResolve("task_middleage_putplant4")) { GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_PUTINPLATE"), "", true); } } // Clic sur la sorcière qui demande quelque chose if (strcmp(szObjectName, "middleage_witch_ask") == 0 || strcmp(szObjectName, "middleage_witch_wait") == 0) { int x,y; GetObjectPosition("middleage_witch_ask", x, y, true, false); if (TaskToResolve("task_middleage_getplate")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_BRINGMEPLATE"), "", false); } else if (TaskToResolve("task_middleage_putplate")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_SETPLATE"), "", false); } else if (TaskToResolve("task_middleage_getplant1")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT1"), "", false); } else if (TaskToResolve("task_middleage_getplant2")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT2"), "", false); } else if (TaskToResolve("task_middleage_getplant3")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT3"), "", false); } else if (TaskToResolve("task_middleage_getplant4")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT4"), "", false); } else if (TaskToResolve("task_middleage_giveflask")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKFLASK"), "", false); } else if (TaskToResolve("task_middleage_givecap")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_ASKCAP"), "", false); } else if (TaskToResolve("task_middleage_prepareplant1") || TaskToResolve("task_middleage_prepareplant2") || TaskToResolve("task_middleage_prepareplant3") || TaskToResolve("task_middleage_prepareplant4")) { _lpSceneDirector->getSequencer()->Talk(szObjectName, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); } } // Clic sur le bol if (strcmp(szObjectName, "middleage_emptyplate") == 0) { _lpSceneDirector->getSequencer()->Talk(szObjectName, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_EMPTYPLATE"), "", true, false); } // Clic sur le contenu if (strcmp(szObjectName, "middleage_contentplate_ready") == 0) { StopEmitter("flake_content"); PickupSimple("middleage_contentplate_ready", "inv_middleage_contentplate_ready"); } return false; } bool Scene_Middleage_Jail::ObjectOver(char *szObjectName, float x, float y) { return false; } bool Scene_Middleage_Jail::ItemUsed(const char *szItemName, const char *szObjectName) { // Le joueur donne quelque chose à la sorcière if (strcmp(szObjectName, "middleage_witch_wait") == 0) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WHATAREU"), "", false); return true; } // Le joueur donne quelque chose à la sorcière if (strcmp(szObjectName, "middleage_witch_ask") == 0) { int x,y; GetObjectPosition("middleage_witch_ask", x, y, true, false); // Donne l'assiette if (strcmp(szItemName, "inv_middleage_plate") == 0) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_SETPLATE"), "", false); return true; } // Donne la plante 1 else if (strcmp(szItemName, "inv_middleage_poppy") == 0 && TaskToResolve("task_middleage_getplant1")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PUTINPLATE"), "", false); return true; } // Donne la plante 2 else if (strcmp(szItemName, "inv_middleage_ginkgo") == 0 && TaskToResolve("task_middleage_getplant2")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PUTINPLATE"), "", false); return true; } // Donne la plante 3 else if (strcmp(szItemName, "inv_middleage_garlic") == 0 && TaskToResolve("task_middleage_getplant3")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PUTINPLATE"), "", false); return true; } // Donne la plante 4 else if (strcmp(szItemName, "inv_middleage_rue") == 0 && TaskToResolve("task_middleage_getplant4")) { _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PUTINPLATE"), "", false); return true; } // Donne la préparation else if (strcmp(szItemName, "inv_middleage_contentplate_ready") == 0 && TaskToResolve("task_middleage_givecontent")) { _lpSceneDirector->DropItem(szItemName); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKFLASK"), "", false); ResolveObjective("middleage","plant"); ResolveTask("task_middleage_givecontent"); AddTask("task_middleage_giveflask"); AddHint("middleage","help","flask"); return true; } // Donne la fiole else if (strcmp(szItemName, "inv_middleage_flask_empty") == 0 && TaskToResolve("task_middleage_giveflask")) { _lpSceneDirector->DropItem(szItemName); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKCAP"), "", false); ResolveTask("task_middleage_giveflask"); AddTask("task_middleage_givecap"); return true; } // Donne le bouchon, on obtient le remède !! else if (strcmp(szItemName, "inv_middleage_cap") == 0 && TaskToResolve("task_middleage_givecap")) { _lpSceneDirector->DropItem(szItemName); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); // On obtient la fiole _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->PickupItem(NULL, "inv_middleage_flask_full", 450, 475, 1); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_GONOW"), "", false); ResolveObjective("middleage","help"); ResolveTask("task_middleage_giveflask"); AddTask("task_middleage_treatabbot"); return true; } // Donne le liège else if (strcmp(szItemName, "inv_middleage_cork") == 0 && TaskToResolve("task_middleage_givecap")) { _lpSceneDirector->getSequencer()->VoiceOver(NULL, KStr("MIDDLEAGE_MONK_NEEDSHAPE"), ""); return true; } else { _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_NOTSUITABLE"), "", false); return true; } } // Le joueur pose l'assiette sur l'emplacement prévu if (strcmp(szObjectName, "middleage_plate_zone") == 0) { if (strcmp(szItemName, "inv_middleage_plate") == 0 && TaskResolved("task_middleage_contactwitch")) { SetVisible("middleage_emptyplate", true); // On n'a plus besoin de l'assiette dans l'inventaire _lpSceneDirector->DropItem(szItemName); ResolveTask("task_middleage_getplate"); ResolveTask("task_middleage_putplate"); int x,y; _lpSceneDirector->getSequencer()->PlaySound(NULL,"spooky_piano"); GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT1"), "", false); AddTask("task_middleage_getplant1"); RemoveHint("middleage","help","plate"); AddObjective("middleage","plant"); AddHint("middleage","plant","nextpoppy"); return true; } else { int x,y; GetObjectPosition("middleage_witch_ask", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WHATAREU"), "", false); return true; } } // Le joueur pose la plante dans l'assiette if (strcmp(szObjectName, "middleage_emptyplate") == 0 || strcmp(szObjectName, "middleage_contentplate") == 0) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); if (strcmp(szItemName, "inv_middleage_poppy") == 0 && TaskToResolve("task_middleage_getplant1")) { _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->DropItem(szItemName); ResolveTask("task_middleage_startprepare"); ResolveTask("task_middleage_getplant1"); AddTask("task_middleage_prepareplant1"); _lpSceneDirector->getSequencer()->ShowImage(NULL, "middleage_contentplate", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); return true; } else if (strcmp(szItemName, "inv_middleage_ginkgo") == 0 && TaskToResolve("task_middleage_getplant2")) { _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->DropItem(szItemName); ResolveTask("task_middleage_getplant2"); AddTask("task_middleage_prepareplant2"); _lpSceneDirector->getSequencer()->ShowImage(NULL, "middleage_contentplate", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); return true; } else if (strcmp(szItemName, "inv_middleage_garlic") == 0 && TaskToResolve("task_middleage_getplant3")) { _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->DropItem(szItemName); ResolveTask("task_middleage_startprepare"); ResolveTask("task_middleage_getplant3"); AddTask("task_middleage_prepareplant3"); _lpSceneDirector->getSequencer()->ShowImage(NULL, "middleage_contentplate", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); return true; } else if (strcmp(szItemName, "inv_middleage_rue") == 0 && TaskToResolve("task_middleage_getplant4")) { _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); _lpSceneDirector->DropItem(szItemName); ResolveTask("task_middleage_startprepare"); ResolveTask("task_middleage_getplant4"); AddTask("task_middleage_prepareplant4"); RemoveHint("middleage","plant","nextrue"); AddHint("middleage","plant","how"); _lpSceneDirector->getSequencer()->ShowImage(NULL, "middleage_contentplate", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_ask", "middleage_witch_wait"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_PREPARE"), "", false); return true; } else { _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_NOTSUITABLE"), "", false); } } // Le joueur utilise le pilon sur le contenu de l'assiette if (strcmp(szObjectName, "middleage_emptyplate") == 0 || strcmp(szObjectName, "middleage_contentplate") == 0) { // Morceau de bois non façonné if (strcmp(szItemName, "inv_middleage_wood") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_NEEDSHAPE"), "", false, false); return true; } // Pilon ok if (strcmp(szItemName, "inv_middleage_pestle") == 0 && TaskToResolve("task_middleage_prepareplant1")) { EMiniJeuBase *lpMiniJeu = new EMiniJeuPlantAddition(); _lpSceneDirector->GoToMiniGame("prepare_plant1", lpMiniJeu); return true; } if (strcmp(szItemName, "inv_middleage_pestle") == 0 && TaskToResolve("task_middleage_prepareplant2")) { EMiniJeuBase *lpMiniJeu = new EMiniJeuGardening(); _lpSceneDirector->GoToMiniGame("prepare_plant2", lpMiniJeu); return true; } if (strcmp(szItemName, "inv_middleage_pestle") == 0 && TaskToResolve("task_middleage_prepareplant3")) { EMiniJeuBase *lpMiniJeu = new EMiniJeuPlantAddition(); _lpSceneDirector->GoToMiniGame("prepare_plant3", lpMiniJeu); return true; } if (strcmp(szItemName, "inv_middleage_pestle") == 0 && TaskToResolve("task_middleage_prepareplant4")) { EMiniJeuBase *lpMiniJeu = new EMiniJeuGardening(); _lpSceneDirector->GoToMiniGame("prepare_plant4", lpMiniJeu); return true; } } return false; } void Scene_Middleage_Jail::MiniGameDone(const char *szGameName, bool bIsRevolved) { if (!bIsRevolved) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WHATAREU"), "", true); return; } _lpSceneDirector->getSequencer()->PlaySound(NULL,"success"); if (strcmp(szGameName, "prepare_plant1") == 0 && bIsRevolved) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WELLDONE"), "", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT2"), "", true); ResolveTask("task_middleage_prepareplant1"); AddTask("task_middleage_getplant2"); RemoveHint("middleage","plant","nextpoppy"); AddHint("middleage","plant","nextginkgo"); return; } if (strcmp(szGameName, "prepare_plant2") == 0 && bIsRevolved) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WELLDONE"), "", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT3"), "", true); ResolveTask("task_middleage_prepareplant2"); AddTask("task_middleage_getplant3"); RemoveHint("middleage","plant","nextginkgo"); AddHint("middleage","plant","nextgarlic"); return; } if (strcmp(szGameName, "prepare_plant3") == 0 && bIsRevolved) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WELLDONE"), "", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKPLANT4"), "", true); ResolveTask("task_middleage_prepareplant3"); AddTask("task_middleage_getplant4"); RemoveHint("middleage","plant","nextgarlic"); AddHint("middleage","plant","nextrue"); return; } if (strcmp(szGameName, "prepare_plant4") == 0 && bIsRevolved) { int x,y; GetObjectPosition("middleage_witch_wait", x, y, true, false); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_WELLDONE"), "", true); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_witch_wait", "middleage_witch_ask"); _lpSceneDirector->getSequencer()->SwitchImage(NULL,"middleage_contentplate", "middleage_contentplate_ready"); _lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("MIDDLEAGE_WITCH_ASKCONTENT"), "", true); ResolveTask("task_middleage_prepareplant4"); AddTask("task_middleage_givecontent"); StartEmitter("flake_content"); return; } }
// // VertexData.cpp // HEAssets // // Created by Sid on 22/04/13. // Copyright (c) 2013 whackylabs. All rights reserved. // #include <he/Vertex/VertexData.h> #include <he/Utils/Screen.h> #include <gtest.h> TEST(VertexData, Equality){ he::Vertex::V2 a; he::Vertex::Set(a, GLKVector2Make(50, -100), GLKVector2Make(50, 100), GLKVector2Make(-50, -100), GLKVector2Make(-50, 100)); he::Vertex::V2 b; he::Vertex::Set(b, GLKVector2Make(50, -100), GLKVector2Make(50, 100), GLKVector2Make(-50, -100), GLKVector2Make(-50, 100)); EXPECT_EQ(a, b); } TEST(VertexData, GlobalTransformTranslate){ he::g_Screen = new he::Screen(480, 320); he::Vertex::V2 start; he::Vertex::Set(start, GLKVector2Make(-100, -50), GLKVector2Make(100, 50)); he::Vertex::V2 end; he::Vertex::Set(end, GLKVector2Make(0, 0), GLKVector2Make(200, 100)); he::Transform global = he::Transform_Create(GLKVector2Make(-100, -50)); he::Vertex::ApplyTransform(end, global); EXPECT_EQ(start, end); delete he::g_Screen; } TEST(VertexData, GlobalTransformRotate){ he::g_Screen = new he::Screen(480, 320); he::Vertex::V2 start; he::Vertex::Set(start, GLKVector2Make(-100, -50), GLKVector2Make(100, 50)); he::Vertex::V2 end; he::Vertex::Set(end, GLKVector2Make(50, -100), GLKVector2Make(50, 100), GLKVector2Make(-50, -100), GLKVector2Make(-50, 100)); he::Transform global = he::Transform_Create(GLKVector2Make(0, 0), GLKVector4Make(0, 0, 1, GLKMathDegreesToRadians(90))); he::Vertex::ApplyTransform(start, global); EXPECT_EQ(start, end); delete he::g_Screen; }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkNavigationData.h" #include "mitkVector.h" #include <vnl/vnl_math.h> #include <itkIndent.h> using namespace mitk; /** * helper function which checks if the non position / orientation / covariance related members are all set to certain values */ static bool AreBasicNavigationMembersEqual(const NavigationData::Pointer nd, const bool dataValid, const NavigationData::TimeStampType timeStamp, const std::string name) { bool result = true; result = result && (nd->IsDataValid() == dataValid); result = result && (mitk::Equal(nd->GetIGTTimeStamp(), timeStamp)); result = result && (0 == name.compare(nd->GetName())); return result; } /** * helper function which checks if the basic members, meaning the members not related to position / orientation / covariance * are the same for two NavigationData objects. */ static bool AreBasicNavigationMembersEqual(const NavigationData::Pointer nd1, const NavigationData::Pointer nd2) { return AreBasicNavigationMembersEqual(nd1, nd2->IsDataValid(), nd2->GetIGTTimeStamp(), nd2->GetName()); } /** * Test if the NavigationData object nd has the correct settings for covariance matrix specific members. * * @param nd * @param hasPosition the desired value for the hasPosition member * @param hasOrientation the desired value for the hasOrientation member * @param covMatrix the covariance matrix nd should have * @return */ static bool AreCovarianceNavigationMembersEqual(const NavigationData::Pointer nd, bool hasPosition, bool hasOrientation, NavigationData::CovarianceMatrixType covMatrix) { bool result = true; result = result && (nd->GetHasPosition() == hasPosition); result = result && (nd->GetHasOrientation() == hasOrientation); result = result && (mitk::MatrixEqualElementWise(nd->GetCovErrorMatrix(), covMatrix)); return result; } /** * Checks if the covariance related members of the two NavigationData objects are the same * * @see AreCovarianceNavigationMembersEqual * * @param nd1 * @param nd2 * @return */ static bool AreCovarianceNavigationMembersEqual(const NavigationData::Pointer nd1, const NavigationData::Pointer nd2) { return AreCovarianceNavigationMembersEqual(nd1, nd2->GetHasPosition(), nd2->GetHasOrientation(), nd2->GetCovErrorMatrix()); } /** * Creates a fully set NavigationData object for testing purposes. * * @return a smartpointer to the object */ static mitk::NavigationData::Pointer GetTestData() { mitk::NavigationData::Pointer nd = mitk::NavigationData::New(); mitk::NavigationData::PositionType p; mitk::FillVector3D(p, 44.4, 55.5, 66.66); nd->SetPosition(p); mitk::NavigationData::OrientationType o(1.0, 2.0, 3.0, 4.0); nd->SetOrientation(o); nd->SetDataValid(true); nd->SetIGTTimeStamp(100.111); nd->SetHasPosition(false); nd->SetHasOrientation(false); mitk::NavigationData::CovarianceMatrixType m; m.Fill(17.17); m(2, 2) = 1000.01; nd->SetCovErrorMatrix(m); nd->SetName("my NavigationData"); nd->SetPositionAccuracy(100.0); nd->SetOrientationAccuracy(10.0); return nd; } static void TestInstatiation() { // Test instantiation of NavigationData mitk::NavigationData::Pointer nd = mitk::NavigationData::New(); MITK_TEST_CONDITION(nd.IsNotNull(),"Test instatiation"); } static void TestGetterSetter() { mitk::NavigationData::Pointer nd = mitk::NavigationData::New(); mitk::NavigationData::PositionType p; mitk::FillVector3D(p, 44.4, 55.5, 66.66); nd->SetPosition(p); MITK_TEST_CONDITION(nd->GetPosition() == p, "Set-/GetPosition()"); mitk::NavigationData::OrientationType o(1.0, 2.0, 3.0, 4.0); nd->SetOrientation(o); MITK_TEST_CONDITION(nd->GetOrientation() == o, "Set-/GetOrientation()"); nd->SetDataValid(true); MITK_TEST_CONDITION(nd->IsDataValid() == true, "Set-/IsDataValid()"); nd->SetIGTTimeStamp(100.111); MITK_TEST_CONDITION(mitk::Equal(nd->GetIGTTimeStamp(), 100.111), "Set-/GetIGTTimeStamp()"); nd->SetHasPosition(false); MITK_TEST_CONDITION(nd->GetHasPosition() == false, "Set-/GetHasPosition()"); nd->SetHasOrientation(false); MITK_TEST_CONDITION(nd->GetHasOrientation() == false, "Set-/GetHasOrientation()"); mitk::NavigationData::CovarianceMatrixType m; m.Fill(17.17); m(2, 2) = 1000.01; nd->SetCovErrorMatrix(m); MITK_TEST_CONDITION(nd->GetCovErrorMatrix() == m, "Set-/GetCovErrorMatrix()"); nd->SetName("my NavigationData"); MITK_TEST_CONDITION(std::string(nd->GetName()) == "my NavigationData", "Set-/GetName()"); nd->SetPositionAccuracy(100.0); mitk::NavigationData::CovarianceMatrixType result = nd->GetCovErrorMatrix(); MITK_TEST_CONDITION(mitk::Equal(result(0, 0), 10000.0) && mitk::Equal(result(1, 1), 10000.0) && mitk::Equal(result(2, 2), 10000.0), "SetPositionAccuracy()"); nd->SetOrientationAccuracy(10.0); mitk::NavigationData::CovarianceMatrixType result2 = nd->GetCovErrorMatrix(); MITK_TEST_CONDITION(mitk::Equal(result2(3, 3), 100.0) && mitk::Equal(result2(4, 4), 100.0) && mitk::Equal(result2(5, 5), 100.0), "SetOrientationAccuracy()"); } static void TestGraft() { //create test data mitk::NavigationData::Pointer nd = GetTestData(); mitk::NavigationData::Pointer graftedCopy = mitk::NavigationData::New(); graftedCopy->Graft(nd); bool graftIsEqual = (nd->GetPosition() == graftedCopy->GetPosition()) && (nd->GetOrientation() == graftedCopy->GetOrientation()) && AreCovarianceNavigationMembersEqual(nd, graftedCopy) && AreBasicNavigationMembersEqual(nd, graftedCopy); MITK_TEST_CONDITION(graftIsEqual, "Graft() produces equal NavigationData object"); } static void TestPrintSelf() { mitk::NavigationData::Pointer nd = GetTestData(); itk::Indent myIndent = itk::Indent(); MITK_TEST_OUTPUT(<<"Testing method PrintSelf(), method output will follow:"); bool success = true; try { nd->PrintSelf(std::cout,myIndent); } catch(...) { success = false; } MITK_TEST_CONDITION(success, "Testing method PrintSelf()."); } static void TestWrongInputs() { mitk::NavigationData::Pointer nd = GetTestData(); // Test CopyInformation bool success = false; try { nd->CopyInformation(nullptr); } catch(itk::ExceptionObject e) { success = true; } MITK_TEST_CONDITION(success, "Testing wrong input for method CopyInformation."); // Test Graft success = false; try { nd->Graft(nullptr); } catch(itk::ExceptionObject e) { success = true; } MITK_TEST_CONDITION(success, "Testing wrong input for method Graft."); } static mitk::Quaternion quaternion; static mitk::Quaternion quaternion_realistic; static mitk::Vector3D offsetVector; static mitk::Point3D offsetPoint; static mitk::Matrix3D rotation; static mitk::Quaternion quaternion2; static mitk::Vector3D offsetVector2; static mitk::Point3D offsetPoint2; static mitk::Matrix3D rotation2; static mitk::Point3D point; /** * Helper method setting up data required for tests (like points which shall be transformed by the NavigationData). */ static void SetupNaviDataTests() { // set rotation matrix to /* * 0 -1 0 * 1 0 0 * 0 0 1 */ rotation.Fill(0); rotation[0][1] = -1; rotation[1][0] = 1; rotation[2][2] = 1; // set quaternion to quaternion equivalent // values calculated with javascript at // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ quaternion = mitk::Quaternion(0, 0, 0.7071067811865475, 0.7071067811865476); // a more realistic quaternion from real tracking data quaternion_realistic = mitk::Quaternion(-0.57747,0.225593,0.366371,0.693933); // set offset to some value. Some tests need vectors, offers points. double offsetArray[3] = {1.0,2.0,3.123456}; offsetVector = offsetArray; offsetPoint = offsetArray; /***** Second set of data for compose tests ****/ // set rotation2 matrix to /* * 1 0 0 * 0 0 -1 * 0 1 0 */ rotation2.Fill(0); rotation2[0][0] = 1; rotation2[1][2] = -1; rotation2[2][1] = 1; quaternion2 = mitk::Quaternion(0.7071067811865475, 0, 0, 0.7071067811865476); mitk::ScalarType offsetArray2[3] = {1, 0, 0}; offsetVector2 = offsetArray2; offsetPoint2 = offsetArray2; /***** Create a point to be transformed *****/ mitk::ScalarType pointArray[] = {1.0, 3.0, 5.0}; point = pointArray; } /** * Helper method, which creates a NavigationData object using the data created in SetupNaviDataTests() */ static mitk::NavigationData::Pointer CreateNavidata(mitk::Quaternion quaternion, mitk::Point3D offset) { mitk::NavigationData::Pointer navigationData = mitk::NavigationData::New(); navigationData->SetOrientation(quaternion); navigationData->SetPosition(offset); return navigationData; } /** * Helper method which creates an affine transformation only composed by a rotation and a translation (no scalings and the likes). * * @param rotationMatrix * @param offset * @return */ static mitk::AffineTransform3D::Pointer CreateAffineTransform(mitk::Matrix3D rotationMatrix, mitk::Vector3D offset) { mitk::AffineTransform3D::Pointer affineTransform3D = mitk::AffineTransform3D::New(); affineTransform3D->SetOffset(offset); affineTransform3D->SetMatrix(rotationMatrix); return affineTransform3D; } /** * Test if NavigationData::GetInverse returns the correct inverse */ static void TestInverse() { SetupNaviDataTests(); mitk::NavigationData::Pointer nd = CreateNavidata(quaternion, offsetPoint); mitk::NavigationData::Pointer ndInverse = nd->GetInverse(); // calculate expected inverted position vector: b2 = -A2b1 // for -A2b1 we need vnl_vectors. vnl_vector_fixed<mitk::ScalarType, 3> b1; for (int i = 0; i < 3; ++i) { b1[i] = nd->GetPosition()[i]; } vnl_vector_fixed<mitk::ScalarType, 3> b2; b2 = -(ndInverse->GetOrientation().rotate(b1)); // now copy result back into our mitk::Point3D mitk::Point3D invertedPosition; for (int i = 0; i < 3; ++i) { invertedPosition[i] = b2[i]; } MITK_TEST_CONDITION(mitk::Equal(nd->GetOrientation().inverse(), ndInverse->GetOrientation()),"Testing GetInverse: orientation inverted"); MITK_TEST_CONDITION(mitk::Equal(invertedPosition, ndInverse->GetPosition()), "Testing GetInverse: position inverted"); bool otherFlagsOk = AreBasicNavigationMembersEqual(nd, ndInverse) && AreCovarianceNavigationMembersEqual(ndInverse, false, false, nd->GetCovErrorMatrix()); // covariance update mechanism not yet implemented, thus validities are set to false. MITK_TEST_CONDITION(otherFlagsOk, "Testing GetInverse: other flags are same"); //######################################################################################## //################### Second test with more realistic quaternion ######################### //######################################################################################## //just copy data to be real sure that it is not overwritten during the test mitk::Quaternion referenceQuaternion; referenceQuaternion[0] = quaternion_realistic[0]; referenceQuaternion[1] = quaternion_realistic[1]; referenceQuaternion[2] = quaternion_realistic[2]; referenceQuaternion[3] = quaternion_realistic[3]; mitk::Point3D referencePoint; referencePoint[0] = offsetPoint[0]; referencePoint[1] = offsetPoint[1]; referencePoint[2] = offsetPoint[2]; referencePoint[3] = offsetPoint[3]; mitk::NavigationData::Pointer nd2 = CreateNavidata(quaternion_realistic, offsetPoint); mitk::NavigationData::Pointer ndInverse2 = nd2->GetInverse(); MITK_TEST_CONDITION(mitk::Equal(nd2->GetOrientation(),referenceQuaternion),"Testing if the method GetInverse() modifies the data which should never happen!"); MITK_TEST_CONDITION(mitk::Equal(ndInverse2->GetOrientation(),referenceQuaternion.inverse()),"Testing if the Qrientation was inverted correctly with the realistic quaternion"); } /** * Test if the original orientation and position are retained after inverting two times. */ static void TestDoubleInverse() { SetupNaviDataTests(); mitk::NavigationData::Pointer nd = CreateNavidata(quaternion, offsetPoint); mitk::NavigationData::Pointer ndDoubleInverse = nd->GetInverse()->GetInverse(); MITK_TEST_CONDITION(mitk::Equal(nd->GetOrientation(), ndDoubleInverse->GetOrientation()),"Testing GetInverse double application: orientation preserved"); MITK_TEST_CONDITION(mitk::Equal(nd->GetPosition(), ndDoubleInverse->GetPosition()), "Testing GetInverse double application: position preserved"); } /** * Tests if NavigationData::GetInverse throws an error if the NavigationData has no inverse * (e.g. after it is initialized, no rotation is stored -> the transformation cannot be inverted). */ static void TestInverseError() { // initialize empty NavigationData (quaternion is zeroed) mitk::NavigationData::Pointer nd = mitk::NavigationData::New(); mitk::Quaternion quaternion; quaternion.fill(0); nd->SetOrientation(quaternion); MITK_TEST_FOR_EXCEPTION(mitk::Exception&, nd->GetInverse()); } /** * Tests if NavigationData::TransformPoint works. */ static void TestTransform() { SetupNaviDataTests(); mitk::NavigationData::Pointer navigationData = CreateNavidata(quaternion, offsetPoint); point = navigationData->TransformPoint(point); mitk::ScalarType resultingPointArray[] = {-2, 3, 8.123456}; mitk::Point3D resultingPoint = resultingPointArray; MITK_TEST_CONDITION(mitk::Equal(resultingPoint, point), "Testing point transformation"); } /** * Tests if the construction of a NavigationData object from an * affine transformation which is only composed of a rotation and translation works. */ static void TestAffineConstructor() { SetupNaviDataTests(); mitk::AffineTransform3D::Pointer affineTransform3D = CreateAffineTransform(rotation, offsetVector); mitk::NavigationData::Pointer navigationData = mitk::NavigationData::New(affineTransform3D); MITK_TEST_CONDITION(AreBasicNavigationMembersEqual(navigationData, true, 0.0, ""), "Testing affine constructor: dataValid, timeStamp and name have been initialized to default values"); NavigationData::CovarianceMatrixType covMatrix; // empty covariance matrix MITK_TEST_CONDITION(AreCovarianceNavigationMembersEqual(navigationData, true, true, covMatrix), "Testing affine constructor: covariance matrix values have been correctly initialized"); // TODO: discuss with Alfred // why this is the desired initialization of the covariance information. MITK_TEST_CONDITION(mitk::Equal(navigationData->GetPosition(), offsetPoint), "Testing affine constructor: offset"); MITK_TEST_CONDITION(mitk::Equal(navigationData->GetOrientation(), quaternion), "Testing affine constructor: quaternion"); } /** * Tests if the construction of a NavigationData object throws an error when constructing from an * affine transformation which is orthogonal. */ static void TestAffineConstructorErrorTransposedNotInverse() { SetupNaviDataTests(); rotation.SetIdentity(); rotation[1][0] = 2; // this matrix has determinant = 1 (triangular matrix with ones in diagonal) but transposed != inverse mitk::AffineTransform3D::Pointer affineTransform3D = CreateAffineTransform(rotation, offsetVector); MITK_TEST_FOR_EXCEPTION(mitk::Exception&, mitk::NavigationData::New(affineTransform3D)); } /** * Tests if the construction of a NavigationData object throws an error when constructing from an * affine transformation which is not normal. */ static void TestAffineConstructorErrorDeterminantNonEqualOne() { SetupNaviDataTests(); rotation.SetIdentity(); rotation[0][0] = 2; // determinant for diagonal matrices is product of diagonal elements => det = 2 mitk::AffineTransform3D::Pointer affineTransform3D = CreateAffineTransform(rotation, offsetVector); MITK_TEST_FOR_EXCEPTION(mitk::Exception&, mitk::NavigationData::New(affineTransform3D)); } /** * Tests if the error suppression mechanism works if a NavigationData object is created from a * invalid affine transformation (one that is not only rotation and translation). */ static void TestAffineConstructorErrorCheckingFalse() { SetupNaviDataTests(); rotation.SetIdentity(); rotation[0][0] = 2; // determinant for diagonal matrices is product of diagonal elements => det = 2 mitk::AffineTransform3D::Pointer affineTransform3D = CreateAffineTransform(rotation, offsetVector); bool exceptionSuppressed = true; try { mitk::NavigationData::New(affineTransform3D, false); } catch (mitk::Exception&) { exceptionSuppressed = false; } MITK_TEST_CONDITION(exceptionSuppressed, "Test affine constructor: exception can be suppressed.") } /** * Test if NavigationData::GetAffineTransform3D() returns the correct affine transformation. */ static void TestAffineGetter() { SetupNaviDataTests(); mitk::NavigationData::Pointer navigationData = CreateNavidata(quaternion, offsetPoint); mitk::AffineTransform3D::Pointer affineTransform = navigationData->GetAffineTransform3D(); MITK_TEST_CONDITION(mitk::Equal(affineTransform->GetOffset(), offsetVector), "Testing AffineTransform3D getter: offset"); MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(affineTransform->GetMatrix(), rotation), "Testing AffineTransform3D getter: rotation"); } /** * This test tests the complete chain from affineTransform -> NavigationData -> affineTransform */ static void TestAffineToNaviDataToAffine() { SetupNaviDataTests(); mitk::AffineTransform3D::Pointer affineTransform3D = CreateAffineTransform(rotation, offsetVector); // there and back again: affineTransform -> NavigationData -> affineTransform mitk::NavigationData::Pointer navigationData = mitk::NavigationData::New(affineTransform3D); mitk::AffineTransform3D::Pointer affineTransform3D_2; affineTransform3D_2 = navigationData->GetAffineTransform3D(); MITK_TEST_CONDITION(mitk::Equal(affineTransform3D->GetOffset(), affineTransform3D_2->GetOffset()), "Testing affine -> navidata -> affine chain: offset"); MITK_TEST_CONDITION(mitk::MatrixEqualElementWise(affineTransform3D->GetMatrix(), affineTransform3D_2->GetMatrix()), "Testing affine -> navidata -> affine chain: rotation"); } static void TestCompose(bool pre = false) { SetupNaviDataTests(); mitk::NavigationData::Pointer nd = CreateNavidata(quaternion, offsetPoint); mitk::AffineTransform3D::Pointer at = CreateAffineTransform(rotation, offsetVector); // second transform for composition mitk::NavigationData::Pointer nd2 = CreateNavidata(quaternion2, offsetPoint2); mitk::AffineTransform3D::Pointer at2 = CreateAffineTransform(rotation2, offsetVector2); // save point for affinetransform mitk::Point3D point2 = point; nd->Compose(nd2, pre); point = nd->TransformPoint(point); at->Compose(at2, pre); point2 = at->TransformPoint(point2); MITK_TEST_CONDITION(mitk::Equal(point, point2), "Compose pre = " << pre << ": composition works "); bool covarianceValidityReset = !nd->GetHasOrientation() && !nd->GetHasPosition(); MITK_TEST_CONDITION(covarianceValidityReset, "Compose pre = " << pre << ": covariance validities reset because not implemented yet."); } static void TestReverseCompose() { TestCompose(true); } /** * Tests the clone method. */ static void TestClone() { SetupNaviDataTests(); mitk::NavigationData::Pointer nd = CreateNavidata(quaternion, offsetPoint); mitk::NavigationData::Pointer myClone = nd->Clone(); MITK_TEST_CONDITION(mitk::Equal(*nd,*myClone,mitk::eps,true), "Test if clone is equal to original object."); //change clone, original object should not change mitk::Point3D myPoint; mitk::FillVector3D(myPoint,121,32132,433); myClone->SetPosition(myPoint); MITK_TEST_CONDITION(!mitk::Equal(*nd,*myClone), "Test if clone could be modified without changing the original object."); } /** * This function is testing the Class mitk::NavigationData. For most tests we would need the MicronTracker hardware, so only a few * simple tests, which can run without the hardware are implemented yet (2009, January, 23rd). As soon as there is a working * concept to test the tracking classes which are very close to the hardware on all systems more tests are needed here. */ int mitkNavigationDataTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationData"); TestInstatiation(); TestGetterSetter(); TestGraft(); TestPrintSelf(); TestWrongInputs(); TestAffineConstructor(); TestAffineConstructorErrorDeterminantNonEqualOne(); TestAffineConstructorErrorTransposedNotInverse(); TestAffineConstructorErrorCheckingFalse(); TestAffineGetter(); TestAffineToNaviDataToAffine(); TestTransform(); //TestInverse(); Fails under MAC, see bug 18306 TestDoubleInverse(); TestInverseError(); TestCompose(); TestReverseCompose(); TestClone(); MITK_TEST_END(); }
#ifdef _WIN32 #include "uv.h" #include "windows.h" namespace xprofiler { #define GET_CURRENT_TIME(curtime) \ HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, getpid()); \ BOOL bRetCode = FALSE; \ FILETIME CreateTime, ExitTime, KernelTime, UserTime; \ LARGE_INTEGER lgKernelTime; \ LARGE_INTEGER lgUserTime; \ LARGE_INTEGER lgCurTimeTmp; \ bRetCode = GetProcessTimes(hProcess, &CreateTime, &ExitTime, &KernelTime, \ &UserTime); \ if (!bRetCode) { \ return -1; \ } \ lgKernelTime.HighPart = KernelTime.dwHighDateTime; \ lgKernelTime.LowPart = KernelTime.dwLowDateTime; \ lgUserTime.HighPart = UserTime.dwHighDateTime; \ lgUserTime.LowPart = UserTime.dwLowDateTime; \ lgCurTimeTmp.QuadPart = \ (lgKernelTime.QuadPart + lgUserTime.QuadPart) / 10000; \ curtime = lgCurTimeTmp; double GetNowCpuUsage() { static LARGE_INTEGER g_slgProcessTimeOld = {0}; static uint64_t last_time = 0; // first time if (last_time == 0) { GET_CURRENT_TIME(g_slgProcessTimeOld); last_time = uv_hrtime(); return -1; } LARGE_INTEGER lgCurTime = {0}; GET_CURRENT_TIME(lgCurTime) double cpu_now_ = ((lgCurTime.QuadPart - g_slgProcessTimeOld.QuadPart) * 100 / ((uv_hrtime() - last_time) / 10e5)); // update time & cpu usage g_slgProcessTimeOld = lgCurTime; last_time = uv_hrtime(); return cpu_now_; } } // namespace xprofiler #endif
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "CoreFixture.hpp" using openstudio::FileLogSink; using openstudio::toPath; void CoreFixture::SetUpTestCase() { // set up logging logFile = FileLogSink(toPath("./CoreFixture.log")); logFile->setLogLevel(Info); } void CoreFixture::TearDownTestCase() { logFile->disable(); } boost::optional<openstudio::FileLogSink> CoreFixture::logFile;
// // "$Id$" // // Filename expansion routines for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2010 by Bill Spitzak and others. // // This library is free software. Distribution and use rights are outlined in // the file "COPYING" which should have been included with this file. If this // file is missing or damaged, see the license at: // // http://www.fltk.org/COPYING.php // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // /* expand a file name by substuting environment variables and home directories. Returns true if any changes were made. to & from may be the same buffer. */ #include <FL/filename.H> #include <FL/fl_utf8.h> #include <stdlib.h> #include "flstring.h" #if defined(WIN32) && !defined(__CYGWIN__) #include <windows.h> #else # include <unistd.h> # include <pwd.h> #endif #if defined(WIN32) || defined(__EMX__) && !defined(__CYGWIN__) static inline int isdirsep(char c) {return c=='/' || c=='\\';} #else #define isdirsep(c) ((c)=='/') #endif /** Expands a filename containing shell variables and tilde (~). Currently handles these variants: \code "~username" // if 'username' does not exist, result will be unchanged "~/file" "$VARNAME" // does NOT handle ${VARNAME} \endcode \b Examples: \code #include <FL/filename.H> [..] putenv("TMPDIR=/var/tmp"); fl_filename_expand(out, sizeof(out), "~fred/.cshrc"); // out="/usr/fred/.cshrc" fl_filename_expand(out, sizeof(out), "~/.cshrc"); // out="/usr/<yourname>/.cshrc" fl_filename_expand(out, sizeof(out), "$TMPDIR/foo.txt"); // out="/var/tmp/foo.txt" \endcode \param[out] to resulting expanded filename \param[in] tolen size of the expanded filename buffer \param[in] from filename containing shell variables \return 0 if no change, non zero otherwise */ int fl_filename_expand(char *to,int tolen, const char *from) { char *temp = new char[tolen]; strlcpy(temp,from, tolen); char *start = temp; char *end = temp+strlen(temp); int ret = 0; for (char *a=temp; a<end; ) { // for each slash component char *e; for (e=a; e<end && !isdirsep(*e); e++) {/*empty*/} // find next slash const char *value = 0; // this will point at substitute value switch (*a) { case '~': // a home directory name if (e <= a+1) { // current user's directory value = fl_getenv("HOME"); #ifndef WIN32 } else { // another user's directory struct passwd *pwd; char t = *e; *(char *)e = 0; pwd = getpwnam(a+1); *(char *)e = t; if (pwd) value = pwd->pw_dir; #endif } break; case '$': /* an environment variable */ {char t = *e; *(char *)e = 0; value = fl_getenv(a+1); *(char *)e = t;} break; } if (value) { // substitutions that start with slash delete everything before them: if (isdirsep(value[0])) start = a; #if defined(WIN32) || defined(__EMX__) && !defined(__CYGWIN__) // also if it starts with "A:" if (value[0] && value[1]==':') start = a; #endif int t = (int) strlen(value); if (isdirsep(value[t-1])) t--; if ((end+1-e+t) >= tolen) end += tolen - (end+1-e+t); memmove(a+t, e, end+1-e); end = a+t+(end-e); *end = '\0'; memcpy(a, value, t); ret++; } else { a = e+1; #if defined(WIN32) || defined(__EMX__) && !defined(__CYGWIN__) if (*e == '\\') {*e = '/'; ret++;} // ha ha! #endif } } strlcpy(to, start, tolen); delete[] temp; return ret; } // // End of "$Id$". //
/***************************************************************************************** Copyright 2011 Rafael Muñoz Salinas. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Rafael Muñoz Salinas. ********************************************************************************************/ #include <iostream> #include <fstream> #include <sstream> #include "aruco.h" #include "cvdrawingutils.h" #include <opencv2/highgui/highgui.hpp> using namespace cv; using namespace aruco; string TheInputVideo; string TheIntrinsicFile; float TheMarkerSize = -1; int ThePyrDownLevel; MarkerDetector MDetector; VideoCapture TheVideoCapturer; vector< Marker > TheMarkers; Mat TheInputImage, TheInputImageCopy; CameraParameters TheCameraParameters; void cvTackBarEvents(int pos, void *); bool readCameraParameters(string TheIntrinsicFile, CameraParameters &CP, Size size); pair< double, double > AvrgTime(0, 0); // determines the average time required for detection double ThresParam1, ThresParam2; int iThresParam1, iThresParam2; int waitTime = 0; /************************************ * * * * ************************************/ bool readArguments(int argc, char **argv) { if (argc < 2) { cerr << "Invalid number of arguments" << endl; cerr << "Usage: (in.avi|live[:idx_cam=0]) [intrinsics.yml] [size]" << endl; return false; } TheInputVideo = argv[1]; if (argc >= 3) TheIntrinsicFile = argv[2]; if (argc >= 4) TheMarkerSize = atof(argv[3]); if (argc == 3) cerr << "NOTE: You need makersize to see 3d info!!!!" << endl; return true; } int findParam(std::string param, int argc, char *argv[]) { for (int i = 0; i < argc; i++) if (string(argv[i]) == param) return i; return -1; } /************************************ * * * * ************************************/ int main(int argc, char **argv) { try { if (readArguments(argc, argv) == false) { return 0; } // parse arguments // read from camera or from file if (TheInputVideo.find("live") != string::npos) { int vIdx = 0; // check if the :idx is here char cad[100]; if (TheInputVideo.find(":") != string::npos) { std::replace(TheInputVideo.begin(), TheInputVideo.end(), ':', ' '); sscanf(TheInputVideo.c_str(), "%s %d", cad, &vIdx); } cout << "Opening camera index " << vIdx << endl; TheVideoCapturer.open(vIdx); waitTime = 10; } else TheVideoCapturer.open(TheInputVideo); // check video is open if (!TheVideoCapturer.isOpened()) { cerr << "Could not open video" << endl; return -1; } bool isVideoFile = false; if (TheInputVideo.find(".avi") != std::string::npos || TheInputVideo.find("live") != string::npos) isVideoFile = true; // read first image to get the dimensions TheVideoCapturer >> TheInputImage; // read camera parameters if passed if (TheIntrinsicFile != "") { TheCameraParameters.readFromXMLFile(TheIntrinsicFile); TheCameraParameters.resize(TheInputImage.size()); } // Configure other parameters if (ThePyrDownLevel > 0) MDetector.pyrDown(ThePyrDownLevel); // Create gui cv::namedWindow("thres", 1); cv::namedWindow("in", 1); MDetector.setThresholdParams(7, 7); MDetector.setThresholdParamRange(2, 0); // MDetector.enableLockedCornersMethod(true); // MDetector.setCornerRefinementMethod ( MarkerDetector::SUBPIX ); MDetector.getThresholdParams(ThresParam1, ThresParam2); iThresParam1 = ThresParam1; iThresParam2 = ThresParam2; //cv::createTrackbar("ThresParam1", "in", &iThresParam1, 25, cvTackBarEvents); //cv::createTrackbar("ThresParam2", "in", &iThresParam2, 13, cvTackBarEvents); char key = 0; int index = 0; // capture until press ESC or until the end of the video TheVideoCapturer.retrieve(TheInputImage); cv::Size sz = TheInputImage.size(); MDetector.createCudaBuffers(sz.width, sz.height); do { // copy image index++; // number of images captured double tick = (double)getTickCount(); // for checking the speed // Detection of markers in the image passed MDetector.detect(TheInputImage, TheMarkers, TheCameraParameters, TheMarkerSize); // chekc the speed by calculating the mean speed of all iterations AvrgTime.first += ((double)getTickCount() - tick) / getTickFrequency(); AvrgTime.second++; cout << "\rTime detection=" << 1000 * AvrgTime.first / AvrgTime.second << " milliseconds nmarkers=" << TheMarkers.size() << std::flush; // print marker info and draw the markers in image TheInputImage.copyTo(TheInputImageCopy); for (unsigned int i = 0; i < TheMarkers.size(); i++) { cout << endl << TheMarkers[i]; TheMarkers[i].draw(TheInputImageCopy, Scalar(0, 0, 255), 1); } if (TheMarkers.size() != 0) cout << endl; // print other rectangles that contains no valid markers /** for (unsigned int i=0;i<MDetector.getCandidates().size();i++) { aruco::Marker m( MDetector.getCandidates()[i],999); m.draw(TheInputImageCopy,cv::Scalar(255,0,0)); }*/ // draw a 3d cube in each marker if there is 3d info if (TheCameraParameters.isValid()) for (unsigned int i = 0; i < TheMarkers.size(); i++) { CvDrawingUtils::draw3dCube(TheInputImageCopy, TheMarkers[i], TheCameraParameters); CvDrawingUtils::draw3dAxis(TheInputImageCopy, TheMarkers[i], TheCameraParameters); } // DONE! Easy, right? // show input with augmented information and the thresholded image cv::imshow("in", TheInputImageCopy); cv::imshow("thres", MDetector.getThresholdedImage()); //cv::imshow("thres_gpu", MDetector.getThresholdedImageGPU()); key = cv::waitKey(waitTime); // wait for key to be pressed if (isVideoFile) TheVideoCapturer.retrieve(TheInputImage); } while (key != 27 && (TheVideoCapturer.grab() || !isVideoFile)); } catch (std::exception &ex) { cout << "Exception :" << ex.what() << endl; } } /************************************ * * * * ************************************/ void cvTackBarEvents(int pos, void *) { if (iThresParam1 < 3) iThresParam1 = 3; if (iThresParam1 % 2 != 1) iThresParam1++; if (ThresParam2 < 1) ThresParam2 = 1; ThresParam1 = iThresParam1; ThresParam2 = iThresParam2; MDetector.setThresholdParams(ThresParam1, ThresParam2); // recompute MDetector.detect(TheInputImage, TheMarkers, TheCameraParameters); TheInputImage.copyTo(TheInputImageCopy); for (unsigned int i = 0; i < TheMarkers.size(); i++) TheMarkers[i].draw(TheInputImageCopy, Scalar(0, 0, 255), 1); // print other rectangles that contains no valid markers /*for (unsigned int i=0;i<MDetector.getCandidates().size();i++) { aruco::Marker m( MDetector.getCandidates()[i],999); m.draw(TheInputImageCopy,cv::Scalar(255,0,0)); }*/ // draw a 3d cube in each marker if there is 3d info if (TheCameraParameters.isValid()) for (unsigned int i = 0; i < TheMarkers.size(); i++) CvDrawingUtils::draw3dCube(TheInputImageCopy, TheMarkers[i], TheCameraParameters); cv::imshow("in", TheInputImageCopy); cv::imshow("thres", MDetector.getThresholdedImage()); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <forward_list> // void push_front(value_type&& v); #include <forward_list> #include <cassert> #include "../../../MoveOnly.h" int main() { #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { typedef MoveOnly T; typedef std::forward_list<T> C; C c; c.push_front(1); assert(c.front() == 1); assert(distance(c.begin(), c.end()) == 1); c.push_front(3); assert(c.front() == 3); assert(*next(c.begin()) == 1); assert(distance(c.begin(), c.end()) == 2); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/prefs/json_pref_store.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/prefs/pref_filter.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread.h" #include "base/values.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { const char kHomePage[] = "homepage"; // A PrefFilter that will intercept all calls to FilterOnLoad() and hold on // to the |prefs| until explicitly asked to release them. class InterceptingPrefFilter : public PrefFilter { public: InterceptingPrefFilter(); ~InterceptingPrefFilter() override; // PrefFilter implementation: void FilterOnLoad( const PostFilterOnLoadCallback& post_filter_on_load_callback, scoped_ptr<base::DictionaryValue> pref_store_contents) override; void FilterUpdate(const std::string& path) override {} void FilterSerializeData( base::DictionaryValue* pref_store_contents) override {} bool has_intercepted_prefs() const { return intercepted_prefs_ != NULL; } // Finalize an intercepted read, handing |intercepted_prefs_| back to its // JsonPrefStore. void ReleasePrefs(); private: PostFilterOnLoadCallback post_filter_on_load_callback_; scoped_ptr<base::DictionaryValue> intercepted_prefs_; DISALLOW_COPY_AND_ASSIGN(InterceptingPrefFilter); }; InterceptingPrefFilter::InterceptingPrefFilter() {} InterceptingPrefFilter::~InterceptingPrefFilter() {} void InterceptingPrefFilter::FilterOnLoad( const PostFilterOnLoadCallback& post_filter_on_load_callback, scoped_ptr<base::DictionaryValue> pref_store_contents) { post_filter_on_load_callback_ = post_filter_on_load_callback; intercepted_prefs_ = pref_store_contents.Pass(); } void InterceptingPrefFilter::ReleasePrefs() { EXPECT_FALSE(post_filter_on_load_callback_.is_null()); post_filter_on_load_callback_.Run(intercepted_prefs_.Pass(), false); post_filter_on_load_callback_.Reset(); } class MockPrefStoreObserver : public PrefStore::Observer { public: MOCK_METHOD1(OnPrefValueChanged, void (const std::string&)); MOCK_METHOD1(OnInitializationCompleted, void (bool)); }; class MockReadErrorDelegate : public PersistentPrefStore::ReadErrorDelegate { public: MOCK_METHOD1(OnError, void(PersistentPrefStore::PrefReadError)); }; } // namespace class JsonPrefStoreTest : public testing::Test { protected: void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(PathService::Get(base::DIR_TEST_DATA, &data_dir_)); data_dir_ = data_dir_.AppendASCII("prefs"); ASSERT_TRUE(PathExists(data_dir_)); } void TearDown() override { // Make sure all pending tasks have been processed (e.g., deleting the // JsonPrefStore may post write tasks). message_loop_.PostTask(FROM_HERE, MessageLoop::QuitWhenIdleClosure()); message_loop_.Run(); } // The path to temporary directory used to contain the test operations. base::ScopedTempDir temp_dir_; // The path to the directory where the test data is stored. base::FilePath data_dir_; // A message loop that we can use as the file thread message loop. MessageLoop message_loop_; }; // Test fallback behavior for a nonexistent file. TEST_F(JsonPrefStoreTest, NonExistentFile) { base::FilePath bogus_input_file = data_dir_.AppendASCII("read.txt"); ASSERT_FALSE(PathExists(bogus_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( bogus_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_NO_FILE, pref_store->ReadPrefs()); EXPECT_FALSE(pref_store->ReadOnly()); } // Test fallback behavior for a nonexistent file and alternate file. TEST_F(JsonPrefStoreTest, NonExistentFileAndAlternateFile) { base::FilePath bogus_input_file = data_dir_.AppendASCII("read.txt"); base::FilePath bogus_alternate_input_file = data_dir_.AppendASCII("read_alternate.txt"); ASSERT_FALSE(PathExists(bogus_input_file)); ASSERT_FALSE(PathExists(bogus_alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( bogus_input_file, bogus_alternate_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_NO_FILE, pref_store->ReadPrefs()); EXPECT_FALSE(pref_store->ReadOnly()); } // Test fallback behavior for an invalid file. TEST_F(JsonPrefStoreTest, InvalidFile) { base::FilePath invalid_file_original = data_dir_.AppendASCII("invalid.json"); base::FilePath invalid_file = temp_dir_.path().AppendASCII("invalid.json"); ASSERT_TRUE(base::CopyFile(invalid_file_original, invalid_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(invalid_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE, pref_store->ReadPrefs()); EXPECT_FALSE(pref_store->ReadOnly()); // The file should have been moved aside. EXPECT_FALSE(PathExists(invalid_file)); base::FilePath moved_aside = temp_dir_.path().AppendASCII("invalid.bad"); EXPECT_TRUE(PathExists(moved_aside)); EXPECT_TRUE(TextContentsEqual(invalid_file_original, moved_aside)); } // This function is used to avoid code duplication while testing synchronous and // asynchronous version of the JsonPrefStore loading. void RunBasicJsonPrefStoreTest(JsonPrefStore* pref_store, const base::FilePath& output_file, const base::FilePath& golden_output_file) { const char kNewWindowsInTabs[] = "tabs.new_windows_in_tabs"; const char kMaxTabs[] = "tabs.max_tabs"; const char kLongIntPref[] = "long_int.pref"; std::string cnn("http://www.cnn.com"); const Value* actual; EXPECT_TRUE(pref_store->GetValue(kHomePage, &actual)); std::string string_value; EXPECT_TRUE(actual->GetAsString(&string_value)); EXPECT_EQ(cnn, string_value); const char kSomeDirectory[] = "some_directory"; EXPECT_TRUE(pref_store->GetValue(kSomeDirectory, &actual)); base::FilePath::StringType path; EXPECT_TRUE(actual->GetAsString(&path)); EXPECT_EQ(base::FilePath::StringType(FILE_PATH_LITERAL("/usr/local/")), path); base::FilePath some_path(FILE_PATH_LITERAL("/usr/sbin/")); pref_store->SetValue(kSomeDirectory, new StringValue(some_path.value())); EXPECT_TRUE(pref_store->GetValue(kSomeDirectory, &actual)); EXPECT_TRUE(actual->GetAsString(&path)); EXPECT_EQ(some_path.value(), path); // Test reading some other data types from sub-dictionaries. EXPECT_TRUE(pref_store->GetValue(kNewWindowsInTabs, &actual)); bool boolean = false; EXPECT_TRUE(actual->GetAsBoolean(&boolean)); EXPECT_TRUE(boolean); pref_store->SetValue(kNewWindowsInTabs, new FundamentalValue(false)); EXPECT_TRUE(pref_store->GetValue(kNewWindowsInTabs, &actual)); EXPECT_TRUE(actual->GetAsBoolean(&boolean)); EXPECT_FALSE(boolean); EXPECT_TRUE(pref_store->GetValue(kMaxTabs, &actual)); int integer = 0; EXPECT_TRUE(actual->GetAsInteger(&integer)); EXPECT_EQ(20, integer); pref_store->SetValue(kMaxTabs, new FundamentalValue(10)); EXPECT_TRUE(pref_store->GetValue(kMaxTabs, &actual)); EXPECT_TRUE(actual->GetAsInteger(&integer)); EXPECT_EQ(10, integer); pref_store->SetValue(kLongIntPref, new StringValue(base::Int64ToString(214748364842LL))); EXPECT_TRUE(pref_store->GetValue(kLongIntPref, &actual)); EXPECT_TRUE(actual->GetAsString(&string_value)); int64 value; base::StringToInt64(string_value, &value); EXPECT_EQ(214748364842LL, value); // Serialize and compare to expected output. ASSERT_TRUE(PathExists(golden_output_file)); pref_store->CommitPendingWrite(); RunLoop().RunUntilIdle(); EXPECT_TRUE(TextContentsEqual(golden_output_file, output_file)); ASSERT_TRUE(base::DeleteFile(output_file, false)); } TEST_F(JsonPrefStoreTest, Basic) { ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); ASSERT_TRUE(PathExists(input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs()); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, BasicAsync) { ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); ASSERT_TRUE(PathExists(input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); { MockPrefStoreObserver mock_observer; pref_store->AddObserver(&mock_observer); MockReadErrorDelegate* mock_error_delegate = new MockReadErrorDelegate; pref_store->ReadPrefsAsync(mock_error_delegate); EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1); EXPECT_CALL(*mock_error_delegate, OnError(PersistentPrefStore::PREF_READ_ERROR_NONE)).Times(0); RunLoop().RunUntilIdle(); pref_store->RemoveObserver(&mock_observer); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); } // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, PreserveEmptyValues) { FilePath pref_file = temp_dir_.path().AppendASCII("empty_values.json"); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( pref_file, message_loop_.message_loop_proxy(), scoped_ptr<PrefFilter>()); // Set some keys with empty values. pref_store->SetValue("list", new base::ListValue); pref_store->SetValue("dict", new base::DictionaryValue); // Write to file. pref_store->CommitPendingWrite(); MessageLoop::current()->RunUntilIdle(); // Reload. pref_store = new JsonPrefStore( pref_file, message_loop_.message_loop_proxy(), scoped_ptr<PrefFilter>()); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs()); ASSERT_FALSE(pref_store->ReadOnly()); // Check values. const Value* result = NULL; EXPECT_TRUE(pref_store->GetValue("list", &result)); EXPECT_TRUE(ListValue().Equals(result)); EXPECT_TRUE(pref_store->GetValue("dict", &result)); EXPECT_TRUE(DictionaryValue().Equals(result)); } // This test is just documenting some potentially non-obvious behavior. It // shouldn't be taken as normative. TEST_F(JsonPrefStoreTest, RemoveClearsEmptyParent) { FilePath pref_file = temp_dir_.path().AppendASCII("empty_values.json"); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( pref_file, message_loop_.message_loop_proxy(), scoped_ptr<PrefFilter>()); base::DictionaryValue* dict = new base::DictionaryValue; dict->SetString("key", "value"); pref_store->SetValue("dict", dict); pref_store->RemoveValue("dict.key"); const base::Value* retrieved_dict = NULL; bool has_dict = pref_store->GetValue("dict", &retrieved_dict); EXPECT_FALSE(has_dict); } // Tests asynchronous reading of the file when there is no file. TEST_F(JsonPrefStoreTest, AsyncNonExistingFile) { base::FilePath bogus_input_file = data_dir_.AppendASCII("read.txt"); ASSERT_FALSE(PathExists(bogus_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( bogus_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); MockPrefStoreObserver mock_observer; pref_store->AddObserver(&mock_observer); MockReadErrorDelegate *mock_error_delegate = new MockReadErrorDelegate; pref_store->ReadPrefsAsync(mock_error_delegate); EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1); EXPECT_CALL(*mock_error_delegate, OnError(PersistentPrefStore::PREF_READ_ERROR_NO_FILE)).Times(1); RunLoop().RunUntilIdle(); pref_store->RemoveObserver(&mock_observer); EXPECT_FALSE(pref_store->ReadOnly()); } TEST_F(JsonPrefStoreTest, ReadWithInterceptor) { ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); ASSERT_TRUE(PathExists(input_file)); scoped_ptr<InterceptingPrefFilter> intercepting_pref_filter( new InterceptingPrefFilter()); InterceptingPrefFilter* raw_intercepting_pref_filter_ = intercepting_pref_filter.get(); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(input_file, message_loop_.message_loop_proxy().get(), intercepting_pref_filter.Pass()); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE, pref_store->ReadPrefs()); EXPECT_FALSE(pref_store->ReadOnly()); // The store shouldn't be considered initialized until the interceptor // returns. EXPECT_TRUE(raw_intercepting_pref_filter_->has_intercepted_prefs()); EXPECT_FALSE(pref_store->IsInitializationComplete()); EXPECT_FALSE(pref_store->GetValue(kHomePage, NULL)); raw_intercepting_pref_filter_->ReleasePrefs(); EXPECT_FALSE(raw_intercepting_pref_filter_->has_intercepted_prefs()); EXPECT_TRUE(pref_store->IsInitializationComplete()); EXPECT_TRUE(pref_store->GetValue(kHomePage, NULL)); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, ReadAsyncWithInterceptor) { ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); ASSERT_TRUE(PathExists(input_file)); scoped_ptr<InterceptingPrefFilter> intercepting_pref_filter( new InterceptingPrefFilter()); InterceptingPrefFilter* raw_intercepting_pref_filter_ = intercepting_pref_filter.get(); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(input_file, message_loop_.message_loop_proxy().get(), intercepting_pref_filter.Pass()); MockPrefStoreObserver mock_observer; pref_store->AddObserver(&mock_observer); // Ownership of the |mock_error_delegate| is handed to the |pref_store| below. MockReadErrorDelegate* mock_error_delegate = new MockReadErrorDelegate; { pref_store->ReadPrefsAsync(mock_error_delegate); EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(0); // EXPECT_CALL(*mock_error_delegate, // OnError(PersistentPrefStore::PREF_READ_ERROR_NONE)).Times(0); RunLoop().RunUntilIdle(); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(raw_intercepting_pref_filter_->has_intercepted_prefs()); EXPECT_FALSE(pref_store->IsInitializationComplete()); EXPECT_FALSE(pref_store->GetValue(kHomePage, NULL)); } { EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1); // EXPECT_CALL(*mock_error_delegate, // OnError(PersistentPrefStore::PREF_READ_ERROR_NONE)).Times(0); raw_intercepting_pref_filter_->ReleasePrefs(); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_FALSE(raw_intercepting_pref_filter_->has_intercepted_prefs()); EXPECT_TRUE(pref_store->IsInitializationComplete()); EXPECT_TRUE(pref_store->GetValue(kHomePage, NULL)); } pref_store->RemoveObserver(&mock_observer); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, AlternateFile) { ASSERT_TRUE( base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("alternate.json"))); // Test that the alternate file is moved to the main file and read as-is from // there. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); base::FilePath alternate_input_file = temp_dir_.path().AppendASCII("alternate.json"); ASSERT_FALSE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, alternate_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); ASSERT_FALSE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs()); ASSERT_TRUE(PathExists(input_file)); ASSERT_FALSE(PathExists(alternate_input_file)); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, AlternateFileIgnoredWhenMainFileExists) { ASSERT_TRUE( base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); ASSERT_TRUE( base::CopyFile(data_dir_.AppendASCII("invalid.json"), temp_dir_.path().AppendASCII("alternate.json"))); // Test that the alternate file is ignored and that the read occurs from the // existing main file. There is no attempt at even deleting the alternate // file as this scenario should never happen in normal user-data-dirs. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); base::FilePath alternate_input_file = temp_dir_.path().AppendASCII("alternate.json"); ASSERT_TRUE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, alternate_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); ASSERT_TRUE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs()); ASSERT_TRUE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, AlternateFileDNE) { ASSERT_TRUE( base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("write.json"))); // Test that the basic read works fine when an alternate file is specified but // does not exist. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); base::FilePath alternate_input_file = temp_dir_.path().AppendASCII("alternate.json"); ASSERT_TRUE(PathExists(input_file)); ASSERT_FALSE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, alternate_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); ASSERT_TRUE(PathExists(input_file)); ASSERT_FALSE(PathExists(alternate_input_file)); ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs()); ASSERT_TRUE(PathExists(input_file)); ASSERT_FALSE(PathExists(alternate_input_file)); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } TEST_F(JsonPrefStoreTest, BasicAsyncWithAlternateFile) { ASSERT_TRUE( base::CopyFile(data_dir_.AppendASCII("read.json"), temp_dir_.path().AppendASCII("alternate.json"))); // Test that the alternate file is moved to the main file and read as-is from // there even when the read is made asynchronously. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); base::FilePath alternate_input_file = temp_dir_.path().AppendASCII("alternate.json"); ASSERT_FALSE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, alternate_input_file, message_loop_.message_loop_proxy().get(), scoped_ptr<PrefFilter>()); ASSERT_FALSE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); { MockPrefStoreObserver mock_observer; pref_store->AddObserver(&mock_observer); MockReadErrorDelegate* mock_error_delegate = new MockReadErrorDelegate; pref_store->ReadPrefsAsync(mock_error_delegate); EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1); EXPECT_CALL(*mock_error_delegate, OnError(PersistentPrefStore::PREF_READ_ERROR_NONE)).Times(0); RunLoop().RunUntilIdle(); pref_store->RemoveObserver(&mock_observer); EXPECT_FALSE(pref_store->ReadOnly()); EXPECT_TRUE(pref_store->IsInitializationComplete()); } ASSERT_TRUE(PathExists(input_file)); ASSERT_FALSE(PathExists(alternate_input_file)); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } RunBasicJsonPrefStoreTest( pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); } } // namespace base
/*************************************** OpenTptInetPPC.o compatible library This replaces Apple's OpenTptInetPPC.o file so profiling, debugging and other compiler features that are available with source level debugging become available to an application. This code is intended only for MacOS Classic PowerPC targeted applications. Copyright (c) 2002-2008 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brtypes.h" // Only build on PowerPC MacOS Classic targets. #if defined(BURGER_MACCLASSIC) && defined(BURGER_POWERPC) && !defined(DOXYGEN) #include <Files.h> #include <OpenTptInternet.h> // // Below is some of Apple's Secret Sauce. // These are the prototypes to the code in ROM on a PowerPC macintosh // #ifdef __cplusplus extern "C" { #endif typedef struct OTClientContext_t OTClientContext_t; // Pointer to an application network state extern OTClientContext_t __gOTClientRecord; extern pascal OSStatus OTAsyncOpenInternetServicesPriv(OTConfigurationRef cfig, OTOpenFlags oflag, OTNotifyProcPtr proc, void* contextPtr, OTClientContext_t* pClientContext); extern pascal InetSvcRef OTOpenInternetServicesPriv(OTConfigurationRef cfig, OTOpenFlags oflag, OSStatus* err, OTClientContext_t* pClientContext); #ifdef __cplusplus } #endif /*************************************** Call OTAsyncOpenInternetServices ***************************************/ pascal OSStatus OTAsyncOpenInternetServices(OTConfigurationRef cfig, OTOpenFlags oflag, OTNotifyProcPtr proc, void* contextPtr) { return OTAsyncOpenInternetServicesPriv( cfig, oflag, proc, contextPtr, &__gOTClientRecord); } /*************************************** Call OTOpenInternetServices ***************************************/ pascal InetSvcRef OTOpenInternetServices( OTConfigurationRef cfig, OTOpenFlags oflag, OSStatus* err) { return OTOpenInternetServicesPriv(cfig, oflag, err, &__gOTClientRecord); } #endif
typedef struct st_STRAN_SCENE; typedef struct st_PACKER_READ_DATA; typedef struct st_PACKER_ASSETTYPE; typedef struct st_STRAN_DATA; typedef struct st_PKR_ASSET_TOCINFO; typedef struct st_PACKER_READ_FUNCS; typedef enum en_LAYER_TYPE; typedef uint32(*type_0)(st_PACKER_READ_DATA*, uint32); typedef void(*type_1)(void*, uint32, void*); typedef void*(*type_2)(st_PACKER_READ_DATA*, uint32, int8*, void*); typedef void*(*type_4)(st_PACKER_READ_DATA*, uint32, int32, uint32*); typedef void*(*type_5)(void*, uint32, void*, uint32, uint32*); typedef void*(*type_6)(void*, uint32, void*, void*, uint32, uint32*); typedef int32(*type_7)(st_PACKER_READ_DATA*, uint32); typedef int32(*type_8)(void*, uint32, void*, int32); typedef void*(*type_9)(void*, uint32, void*, int32*, int32*); typedef int32(*type_11)(st_PACKER_READ_DATA*, uint32); typedef void(*type_12)(void*, uint32); typedef void(*type_13)(void*, uint32, void*, int8*); typedef int32(*type_14)(st_PACKER_READ_DATA*, en_LAYER_TYPE); typedef int8*(*type_15)(st_PACKER_READ_DATA*, uint32); typedef uint32(*type_16)(st_PACKER_READ_DATA*); typedef int32(*type_18)(st_PACKER_READ_DATA*, uint32, st_PKR_ASSET_TOCINFO*); typedef int32(*type_19)(st_PACKER_READ_DATA*, uint32, int32, st_PKR_ASSET_TOCINFO*); typedef int32(*type_21)(st_PACKER_READ_DATA*, uint32); typedef uint32(*type_22)(st_PACKER_READ_DATA*); typedef void(*type_23)(st_PACKER_READ_DATA*); typedef int32(*type_24)(void*, float32); typedef st_PACKER_READ_DATA*(*type_26)(void*, int8*, uint32, int32*, st_PACKER_ASSETTYPE*); typedef void(*type_27)(st_PACKER_READ_DATA*); typedef int32(*type_29)(st_PACKER_READ_DATA*, en_LAYER_TYPE); typedef int8 type_3[256]; typedef st_STRAN_SCENE type_10[16]; typedef int8 type_17[2]; typedef int8 type_20[64]; typedef int8 type_25[64]; typedef int8 type_28[16]; typedef int8 type_30[16]; struct st_STRAN_SCENE { uint32 scnid; int32 lockid; st_PACKER_READ_DATA* spkg; int32 isHOP; void* userdata; int8 fnam[256]; }; struct st_PACKER_READ_DATA { }; struct st_PACKER_ASSETTYPE { uint32 typetag; uint32 tflags; int32 typalign; void*(*readXForm)(void*, uint32, void*, uint32, uint32*); void*(*writeXForm)(void*, uint32, void*, void*, uint32, uint32*); int32(*assetLoaded)(void*, uint32, void*, int32); void*(*makeData)(void*, uint32, void*, int32*, int32*); void(*cleanup)(void*, uint32, void*); void(*assetUnloaded)(void*, uint32); void(*writePeek)(void*, uint32, void*, int8*); }; struct st_STRAN_DATA { st_STRAN_SCENE hipscn[16]; uint32 loadlock; }; struct st_PKR_ASSET_TOCINFO { uint32 aid; st_PACKER_ASSETTYPE* typeref; uint32 sector; uint32 plus_offset; uint32 size; void* mempos; }; struct st_PACKER_READ_FUNCS { uint32 api_ver; st_PACKER_READ_DATA*(*Init)(void*, int8*, uint32, int32*, st_PACKER_ASSETTYPE*); void(*Done)(st_PACKER_READ_DATA*); int32(*LoadLayer)(st_PACKER_READ_DATA*, en_LAYER_TYPE); uint32(*GetAssetSize)(st_PACKER_READ_DATA*, uint32); void*(*LoadAsset)(st_PACKER_READ_DATA*, uint32, int8*, void*); void*(*AssetByType)(st_PACKER_READ_DATA*, uint32, int32, uint32*); int32(*AssetCount)(st_PACKER_READ_DATA*, uint32); int32(*IsAssetReady)(st_PACKER_READ_DATA*, uint32); int32(*SetActive)(st_PACKER_READ_DATA*, en_LAYER_TYPE); int8*(*AssetName)(st_PACKER_READ_DATA*, uint32); uint32(*GetBaseSector)(st_PACKER_READ_DATA*); int32(*GetAssetInfo)(st_PACKER_READ_DATA*, uint32, st_PKR_ASSET_TOCINFO*); int32(*GetAssetInfoByType)(st_PACKER_READ_DATA*, uint32, int32, st_PKR_ASSET_TOCINFO*); int32(*PkgHasAsset)(st_PACKER_READ_DATA*, uint32); uint32(*PkgTimeStamp)(st_PACKER_READ_DATA*); void(*PkgDisconnect)(st_PACKER_READ_DATA*); }; enum en_LAYER_TYPE { PKR_LTYPE_ALL = 0xffffffff, PKR_LTYPE_DEFAULT, PKR_LTYPE_TEXTURE, PKR_LTYPE_BSP, PKR_LTYPE_MODEL, PKR_LTYPE_ANIMATION, PKR_LTYPE_VRAM, PKR_LTYPE_SRAM, PKR_LTYPE_SNDTOC, PKR_LTYPE_CUTSCENE, PKR_LTYPE_CUTSCENETOC, PKR_LTYPE_JSPINFO, PKR_LTYPE_NOMORE }; int8 buffer[16]; int8 buffer[16]; int32 g_straninit; st_STRAN_DATA g_xstdata; st_PACKER_READ_FUNCS* g_pkrf; st_PACKER_ASSETTYPE* g_typeHandlers; st_STRAN_SCENE* XST_find_bySID(uint32 sid, int32 findTheHOP); st_STRAN_SCENE* XST_lock_next(); int8* xST_xAssetID_HIPFullPath(uint32 aid, uint32* sceneID); int8* xST_xAssetID_HIPFullPath(uint32 aid); int32 xSTGetAssetInfoByType(uint32 type, int32 idx, st_PKR_ASSET_TOCINFO* ainfo); int32 xSTGetAssetInfo(uint32 aid, st_PKR_ASSET_TOCINFO* tocainfo); void* xSTFindAssetByType(uint32 type, int32 idx, uint32* size); int32 xSTAssetCountByType(uint32 type); void* xSTFindAsset(uint32 aid, uint32* size); int8* xSTAssetName(void* raw_HIP_asset); int8* xSTAssetName(uint32 aid); int32 xSTSwitchScene(uint32 sid, void* userdata, int32(*progmon)(void*, float32)); void xSTDisconnect(uint32 sid, int32 flg_hiphop); float32 xSTLoadStep(); void xSTUnLoadScene(uint32 sid, int32 flg_hiphop); int32 xSTQueueSceneAssets(uint32 sid, int32 flg_hiphop); int32 xSTPreLoadScene(uint32 sid, void* userdata, int32 flg_hiphop); int32 xSTShutdown(); int32 xSTStartup(st_PACKER_ASSETTYPE* handlers); // XST_find_bySID__FUii // Start address: 0x20c750 st_STRAN_SCENE* XST_find_bySID(uint32 sid, int32 findTheHOP) { st_STRAN_SCENE* da_sdata; int32 i; // Line 1098, Address: 0x20c750, Func Offset: 0 // Line 1092, Address: 0x20c75c, Func Offset: 0xc // Line 1098, Address: 0x20c760, Func Offset: 0x10 // Line 1099, Address: 0x20c768, Func Offset: 0x18 // Line 1098, Address: 0x20c76c, Func Offset: 0x1c // Line 1099, Address: 0x20c770, Func Offset: 0x20 // Line 1102, Address: 0x20c780, Func Offset: 0x30 // Line 1103, Address: 0x20c78c, Func Offset: 0x3c // Line 1104, Address: 0x20c7a0, Func Offset: 0x50 // Line 1108, Address: 0x20c7b8, Func Offset: 0x68 // Line 1109, Address: 0x20c7c0, Func Offset: 0x70 // Line 1113, Address: 0x20c7d0, Func Offset: 0x80 // Func End, Address: 0x20c7d8, Func Offset: 0x88 } // XST_lock_next__Fv // Start address: 0x20c7e0 st_STRAN_SCENE* XST_lock_next() { st_STRAN_SCENE* sdata; int32 i; int32 uselock; // Line 983, Address: 0x20c7e0, Func Offset: 0 // Line 989, Address: 0x20c7e4, Func Offset: 0x4 // Line 983, Address: 0x20c7e8, Func Offset: 0x8 // Line 986, Address: 0x20c7ec, Func Offset: 0xc // Line 983, Address: 0x20c7f0, Func Offset: 0x10 // Line 984, Address: 0x20c7f8, Func Offset: 0x18 // Line 989, Address: 0x20c7fc, Func Offset: 0x1c // Line 990, Address: 0x20c80c, Func Offset: 0x2c // Line 992, Address: 0x20c818, Func Offset: 0x38 // Line 991, Address: 0x20c81c, Func Offset: 0x3c // Line 992, Address: 0x20c820, Func Offset: 0x40 // Line 994, Address: 0x20c838, Func Offset: 0x58 // Line 992, Address: 0x20c83c, Func Offset: 0x5c // Line 994, Address: 0x20c840, Func Offset: 0x60 // Line 991, Address: 0x20c844, Func Offset: 0x64 // Line 994, Address: 0x20c84c, Func Offset: 0x6c // Line 996, Address: 0x20c858, Func Offset: 0x78 // Line 998, Address: 0x20c860, Func Offset: 0x80 // Line 1004, Address: 0x20c870, Func Offset: 0x90 // Line 1006, Address: 0x20c880, Func Offset: 0xa0 // Line 1007, Address: 0x20c884, Func Offset: 0xa4 // Func End, Address: 0x20c898, Func Offset: 0xb8 } // xST_xAssetID_HIPFullPath__FUiPUi // Start address: 0x20c8a0 int8* xST_xAssetID_HIPFullPath(uint32 aid, uint32* sceneID) { int8* da_hipname; int32 rc; int32 i; // Line 786, Address: 0x20c8a0, Func Offset: 0 // Line 793, Address: 0x20c8a4, Func Offset: 0x4 // Line 786, Address: 0x20c8a8, Func Offset: 0x8 // Line 787, Address: 0x20c8c4, Func Offset: 0x24 // Line 786, Address: 0x20c8c8, Func Offset: 0x28 // Line 793, Address: 0x20c8cc, Func Offset: 0x2c // Line 786, Address: 0x20c8d0, Func Offset: 0x30 // Line 793, Address: 0x20c8d4, Func Offset: 0x34 // Line 794, Address: 0x20c908, Func Offset: 0x68 // Line 795, Address: 0x20c910, Func Offset: 0x70 // Line 799, Address: 0x20c980, Func Offset: 0xe0 // Line 800, Address: 0x20c994, Func Offset: 0xf4 // Line 802, Address: 0x20c99c, Func Offset: 0xfc // Line 803, Address: 0x20c9a8, Func Offset: 0x108 // Line 806, Address: 0x20c9b0, Func Offset: 0x110 // Line 808, Address: 0x20c9c0, Func Offset: 0x120 // Line 809, Address: 0x20c9c4, Func Offset: 0x124 // Func End, Address: 0x20c9e8, Func Offset: 0x148 } // xST_xAssetID_HIPFullPath__FUi // Start address: 0x20c9f0 int8* xST_xAssetID_HIPFullPath(uint32 aid) { // Line 782, Address: 0x20c9f0, Func Offset: 0 // Func End, Address: 0x20c9f8, Func Offset: 0x8 } // xSTGetAssetInfoByType__FUiiP20st_PKR_ASSET_TOCINFO // Start address: 0x20ca00 int32 xSTGetAssetInfoByType(uint32 type, int32 idx, st_PKR_ASSET_TOCINFO* ainfo) { int32 found; st_PKR_ASSET_TOCINFO tocinfo; int32 rc; int32 i; int32 sum; int32 cnt; // Line 678, Address: 0x20ca00, Func Offset: 0 // Line 681, Address: 0x20ca04, Func Offset: 0x4 // Line 678, Address: 0x20ca08, Func Offset: 0x8 // Line 681, Address: 0x20ca0c, Func Offset: 0xc // Line 678, Address: 0x20ca10, Func Offset: 0x10 // Line 679, Address: 0x20ca20, Func Offset: 0x20 // Line 678, Address: 0x20ca24, Func Offset: 0x24 // Line 681, Address: 0x20ca40, Func Offset: 0x40 // Line 691, Address: 0x20ca60, Func Offset: 0x60 // Line 694, Address: 0x20ca74, Func Offset: 0x74 // Line 695, Address: 0x20cab0, Func Offset: 0xb0 // Line 696, Address: 0x20cab8, Func Offset: 0xb8 // Line 700, Address: 0x20cb28, Func Offset: 0x128 // Line 703, Address: 0x20cb40, Func Offset: 0x140 // Line 705, Address: 0x20cb5c, Func Offset: 0x15c // Line 707, Address: 0x20cb6c, Func Offset: 0x16c // Line 709, Address: 0x20cb88, Func Offset: 0x188 // Line 711, Address: 0x20cb90, Func Offset: 0x190 // Line 720, Address: 0x20cb94, Func Offset: 0x194 // Line 711, Address: 0x20cb98, Func Offset: 0x198 // Line 712, Address: 0x20cb9c, Func Offset: 0x19c // Line 713, Address: 0x20cba4, Func Offset: 0x1a4 // Line 714, Address: 0x20cbac, Func Offset: 0x1ac // Line 715, Address: 0x20cbb4, Func Offset: 0x1b4 // Line 721, Address: 0x20cbb8, Func Offset: 0x1b8 // Line 728, Address: 0x20cbc0, Func Offset: 0x1c0 // Line 730, Address: 0x20cbd0, Func Offset: 0x1d0 // Line 731, Address: 0x20cbd4, Func Offset: 0x1d4 // Func End, Address: 0x20cc04, Func Offset: 0x204 } // xSTGetAssetInfo__FUiP20st_PKR_ASSET_TOCINFO // Start address: 0x20cc10 int32 xSTGetAssetInfo(uint32 aid, st_PKR_ASSET_TOCINFO* tocainfo) { int32 found; st_PKR_ASSET_TOCINFO tocinfo; int32 rc; int32 scncnt; int32 i; // Line 638, Address: 0x20cc10, Func Offset: 0 // Line 641, Address: 0x20cc14, Func Offset: 0x4 // Line 638, Address: 0x20cc18, Func Offset: 0x8 // Line 641, Address: 0x20cc1c, Func Offset: 0xc // Line 638, Address: 0x20cc20, Func Offset: 0x10 // Line 639, Address: 0x20cc28, Func Offset: 0x18 // Line 638, Address: 0x20cc2c, Func Offset: 0x1c // Line 641, Address: 0x20cc40, Func Offset: 0x30 // Line 652, Address: 0x20cc60, Func Offset: 0x50 // Line 653, Address: 0x20cca0, Func Offset: 0x90 // Line 654, Address: 0x20cca8, Func Offset: 0x98 // Line 658, Address: 0x20cd18, Func Offset: 0x108 // Line 659, Address: 0x20cd2c, Func Offset: 0x11c // Line 662, Address: 0x20cd34, Func Offset: 0x124 // Line 664, Address: 0x20cd44, Func Offset: 0x134 // Line 665, Address: 0x20cd5c, Func Offset: 0x14c // Line 668, Address: 0x20cd64, Func Offset: 0x154 // Line 670, Address: 0x20cd6c, Func Offset: 0x15c // Line 672, Address: 0x20cd80, Func Offset: 0x170 // Line 673, Address: 0x20cd84, Func Offset: 0x174 // Func End, Address: 0x20cda8, Func Offset: 0x198 } // xSTFindAssetByType__FUiiPUi // Start address: 0x20cdb0 void* xSTFindAssetByType(uint32 type, int32 idx, uint32* size) { void* memptr; int32 scncnt; int32 i; int32 sum; int32 cnt; // Line 607, Address: 0x20cdb0, Func Offset: 0 // Line 615, Address: 0x20cdb4, Func Offset: 0x4 // Line 607, Address: 0x20cdb8, Func Offset: 0x8 // Line 609, Address: 0x20cdcc, Func Offset: 0x1c // Line 607, Address: 0x20cdd0, Func Offset: 0x20 // Line 615, Address: 0x20cdd4, Func Offset: 0x24 // Line 607, Address: 0x20cdd8, Func Offset: 0x28 // Line 612, Address: 0x20cde0, Func Offset: 0x30 // Line 607, Address: 0x20cde4, Func Offset: 0x34 // Line 615, Address: 0x20cdf0, Func Offset: 0x40 // Line 616, Address: 0x20ce28, Func Offset: 0x78 // Line 617, Address: 0x20ce30, Func Offset: 0x80 // Line 620, Address: 0x20cea0, Func Offset: 0xf0 // Line 621, Address: 0x20ceb4, Func Offset: 0x104 // Line 624, Address: 0x20cecc, Func Offset: 0x11c // Line 626, Address: 0x20cee8, Func Offset: 0x138 // Line 628, Address: 0x20cef0, Func Offset: 0x140 // Line 629, Address: 0x20cef4, Func Offset: 0x144 // Line 631, Address: 0x20cf08, Func Offset: 0x158 // Line 632, Address: 0x20cf0c, Func Offset: 0x15c // Func End, Address: 0x20cf38, Func Offset: 0x188 } // xSTAssetCountByType__FUi // Start address: 0x20cf40 int32 xSTAssetCountByType(uint32 type) { int32 sum; int32 cnt; int32 scncnt; int32 i; // Line 571, Address: 0x20cf40, Func Offset: 0 // Line 578, Address: 0x20cf44, Func Offset: 0x4 // Line 571, Address: 0x20cf48, Func Offset: 0x8 // Line 578, Address: 0x20cf4c, Func Offset: 0xc // Line 571, Address: 0x20cf50, Func Offset: 0x10 // Line 572, Address: 0x20cf60, Func Offset: 0x20 // Line 571, Address: 0x20cf64, Func Offset: 0x24 // Line 578, Address: 0x20cf68, Func Offset: 0x28 // Line 579, Address: 0x20cfa0, Func Offset: 0x60 // Line 580, Address: 0x20cfa8, Func Offset: 0x68 // Line 583, Address: 0x20d018, Func Offset: 0xd8 // Line 584, Address: 0x20d02c, Func Offset: 0xec // Line 585, Address: 0x20d030, Func Offset: 0xf0 // Line 587, Address: 0x20d040, Func Offset: 0x100 // Line 588, Address: 0x20d044, Func Offset: 0x104 // Func End, Address: 0x20d060, Func Offset: 0x120 } // xSTFindAsset__FUiPUi // Start address: 0x20d060 void* xSTFindAsset(uint32 aid, uint32* size) { void* memloc; int32 ready; int32 scncnt; int32 i; int32 rc; // Line 505, Address: 0x20d060, Func Offset: 0 // Line 509, Address: 0x20d080, Func Offset: 0x20 // Line 505, Address: 0x20d084, Func Offset: 0x24 // Line 517, Address: 0x20d088, Func Offset: 0x28 // Line 534, Address: 0x20d098, Func Offset: 0x38 // Line 535, Address: 0x20d0d8, Func Offset: 0x78 // Line 536, Address: 0x20d0e0, Func Offset: 0x80 // Line 539, Address: 0x20d150, Func Offset: 0xf0 // Line 540, Address: 0x20d164, Func Offset: 0x104 // Line 543, Address: 0x20d16c, Func Offset: 0x10c // Line 546, Address: 0x20d18c, Func Offset: 0x12c // Line 547, Address: 0x20d1a0, Func Offset: 0x140 // Line 550, Address: 0x20d1a8, Func Offset: 0x148 // Line 552, Address: 0x20d1b0, Func Offset: 0x150 // Line 555, Address: 0x20d1b8, Func Offset: 0x158 // Line 556, Address: 0x20d1c0, Func Offset: 0x160 // Line 560, Address: 0x20d1d4, Func Offset: 0x174 // Line 562, Address: 0x20d1dc, Func Offset: 0x17c // Line 564, Address: 0x20d1f0, Func Offset: 0x190 // Line 565, Address: 0x20d1f8, Func Offset: 0x198 // Func End, Address: 0x20d21c, Func Offset: 0x1bc } // xSTAssetName__FPv // Start address: 0x20d220 int8* xSTAssetName(void* raw_HIP_asset) { int8* aname; uint32 aid; int32 i; // Line 472, Address: 0x20d220, Func Offset: 0 // Line 479, Address: 0x20d224, Func Offset: 0x4 // Line 472, Address: 0x20d228, Func Offset: 0x8 // Line 473, Address: 0x20d22c, Func Offset: 0xc // Line 472, Address: 0x20d230, Func Offset: 0x10 // Line 479, Address: 0x20d234, Func Offset: 0x14 // Line 472, Address: 0x20d238, Func Offset: 0x18 // Line 479, Address: 0x20d248, Func Offset: 0x28 // Line 480, Address: 0x20d280, Func Offset: 0x60 // Line 481, Address: 0x20d288, Func Offset: 0x68 // Line 484, Address: 0x20d2f8, Func Offset: 0xd8 // Line 485, Address: 0x20d300, Func Offset: 0xe0 // Line 486, Address: 0x20d314, Func Offset: 0xf4 // Line 487, Address: 0x20d31c, Func Offset: 0xfc // Line 490, Address: 0x20d330, Func Offset: 0x110 // Func End, Address: 0x20d34c, Func Offset: 0x12c } // xSTAssetName__FUi // Start address: 0x20d350 int8* xSTAssetName(uint32 aid) { int8* aname; int32 i; // Line 450, Address: 0x20d350, Func Offset: 0 // Line 456, Address: 0x20d354, Func Offset: 0x4 // Line 450, Address: 0x20d358, Func Offset: 0x8 // Line 451, Address: 0x20d35c, Func Offset: 0xc // Line 450, Address: 0x20d360, Func Offset: 0x10 // Line 456, Address: 0x20d364, Func Offset: 0x14 // Line 450, Address: 0x20d368, Func Offset: 0x18 // Line 456, Address: 0x20d374, Func Offset: 0x24 // Line 457, Address: 0x20d3a8, Func Offset: 0x58 // Line 458, Address: 0x20d3b0, Func Offset: 0x60 // Line 460, Address: 0x20d424, Func Offset: 0xd4 // Line 461, Address: 0x20d42c, Func Offset: 0xdc // Line 462, Address: 0x20d43c, Func Offset: 0xec // Line 465, Address: 0x20d444, Func Offset: 0xf4 // Line 468, Address: 0x20d458, Func Offset: 0x108 // Func End, Address: 0x20d470, Func Offset: 0x120 } // xSTSwitchScene__FUiPvPFPvf_i // Start address: 0x20d470 int32 xSTSwitchScene(uint32 sid, void* userdata, int32(*progmon)(void*, float32)) { st_STRAN_SCENE* sdata; int32 rc; int32 i; // Line 419, Address: 0x20d470, Func Offset: 0 // Line 421, Address: 0x20d484, Func Offset: 0x14 // Line 419, Address: 0x20d488, Func Offset: 0x18 // Line 428, Address: 0x20d4a0, Func Offset: 0x30 // Line 429, Address: 0x20d4a8, Func Offset: 0x38 // Line 430, Address: 0x20d4b8, Func Offset: 0x48 // Line 432, Address: 0x20d4c0, Func Offset: 0x50 // Line 435, Address: 0x20d4d8, Func Offset: 0x68 // Line 439, Address: 0x20d4ec, Func Offset: 0x7c // Line 440, Address: 0x20d504, Func Offset: 0x94 // Line 445, Address: 0x20d514, Func Offset: 0xa4 // Func End, Address: 0x20d538, Func Offset: 0xc8 } // xSTDisconnect__FUii // Start address: 0x20d540 void xSTDisconnect(uint32 sid, int32 flg_hiphop) { st_STRAN_SCENE* sdata; // Line 388, Address: 0x20d540, Func Offset: 0 // Line 381, Address: 0x20d544, Func Offset: 0x4 // Line 388, Address: 0x20d548, Func Offset: 0x8 // Line 381, Address: 0x20d54c, Func Offset: 0xc // Line 388, Address: 0x20d550, Func Offset: 0x10 // Line 392, Address: 0x20d558, Func Offset: 0x18 // Line 393, Address: 0x20d560, Func Offset: 0x20 // Line 394, Address: 0x20d574, Func Offset: 0x34 // Line 397, Address: 0x20d578, Func Offset: 0x38 // Func End, Address: 0x20d584, Func Offset: 0x44 } // xSTLoadStep__FUi // Start address: 0x20d590 float32 xSTLoadStep() { float32 pct; int32 rc; // Line 352, Address: 0x20d590, Func Offset: 0 // Line 360, Address: 0x20d594, Func Offset: 0x4 // Line 352, Address: 0x20d598, Func Offset: 0x8 // Line 360, Address: 0x20d59c, Func Offset: 0xc // Line 362, Address: 0x20d5a4, Func Offset: 0x14 // Line 373, Address: 0x20d5c4, Func Offset: 0x34 // Line 376, Address: 0x20d5cc, Func Offset: 0x3c // Line 377, Address: 0x20d5d0, Func Offset: 0x40 // Func End, Address: 0x20d5e0, Func Offset: 0x50 } // xSTUnLoadScene__FUii // Start address: 0x20d5e0 void xSTUnLoadScene(uint32 sid, int32 flg_hiphop) { st_STRAN_SCENE* sdata; int32 cnt; int32 i; // Line 299, Address: 0x20d5e0, Func Offset: 0 // Line 305, Address: 0x20d5f0, Func Offset: 0x10 // Line 308, Address: 0x20d5f8, Func Offset: 0x18 // Line 311, Address: 0x20d638, Func Offset: 0x58 // Line 312, Address: 0x20d640, Func Offset: 0x60 // Line 315, Address: 0x20d6b4, Func Offset: 0xd4 // Line 317, Address: 0x20d6d0, Func Offset: 0xf0 // Line 320, Address: 0x20d6e0, Func Offset: 0x100 // Line 321, Address: 0x20d760, Func Offset: 0x180 // Line 328, Address: 0x20d768, Func Offset: 0x188 // Line 330, Address: 0x20d77c, Func Offset: 0x19c // Line 331, Address: 0x20d788, Func Offset: 0x1a8 // Line 332, Address: 0x20d7a0, Func Offset: 0x1c0 // Line 333, Address: 0x20d7a4, Func Offset: 0x1c4 // Line 334, Address: 0x20d7a8, Func Offset: 0x1c8 // Line 335, Address: 0x20d7ec, Func Offset: 0x20c // Line 338, Address: 0x20d7f0, Func Offset: 0x210 // Func End, Address: 0x20d808, Func Offset: 0x228 } // xSTQueueSceneAssets__FUii // Start address: 0x20d810 int32 xSTQueueSceneAssets(uint32 sid, int32 flg_hiphop) { int32 result; st_STRAN_SCENE* sdata; // Line 271, Address: 0x20d810, Func Offset: 0 // Line 282, Address: 0x20d814, Func Offset: 0x4 // Line 271, Address: 0x20d818, Func Offset: 0x8 // Line 282, Address: 0x20d81c, Func Offset: 0xc // Line 271, Address: 0x20d820, Func Offset: 0x10 // Line 282, Address: 0x20d824, Func Offset: 0x14 // Line 284, Address: 0x20d830, Func Offset: 0x20 // Line 287, Address: 0x20d844, Func Offset: 0x34 // Line 289, Address: 0x20d84c, Func Offset: 0x3c // Line 291, Address: 0x20d85c, Func Offset: 0x4c // Line 293, Address: 0x20d860, Func Offset: 0x50 // Line 294, Address: 0x20d864, Func Offset: 0x54 // Func End, Address: 0x20d874, Func Offset: 0x64 } // xSTPreLoadScene__FUiPvi // Start address: 0x20d880 int32 xSTPreLoadScene(uint32 sid, void* userdata, int32 flg_hiphop) { int32 result; st_STRAN_SCENE* sdata; int32 cltver; // Line 138, Address: 0x20d880, Func Offset: 0 // Line 149, Address: 0x20d884, Func Offset: 0x4 // Line 138, Address: 0x20d888, Func Offset: 0x8 // Line 149, Address: 0x20d88c, Func Offset: 0xc // Line 138, Address: 0x20d890, Func Offset: 0x10 // Line 143, Address: 0x20d8a8, Func Offset: 0x28 // Line 138, Address: 0x20d8ac, Func Offset: 0x2c // Line 149, Address: 0x20d8b0, Func Offset: 0x30 // Line 158, Address: 0x20d8b8, Func Offset: 0x38 // Line 161, Address: 0x20d8c0, Func Offset: 0x40 // Line 163, Address: 0x20d8c4, Func Offset: 0x44 // Line 162, Address: 0x20d8c8, Func Offset: 0x48 // Line 158, Address: 0x20d8cc, Func Offset: 0x4c // Line 163, Address: 0x20d8d0, Func Offset: 0x50 // Line 167, Address: 0x20d8d4, Func Offset: 0x54 // Line 168, Address: 0x20d940, Func Offset: 0xc0 // Line 169, Address: 0x20d948, Func Offset: 0xc8 // Line 171, Address: 0x20d950, Func Offset: 0xd0 // Line 172, Address: 0x20d98c, Func Offset: 0x10c // Line 174, Address: 0x20d990, Func Offset: 0x110 // Line 176, Address: 0x20d998, Func Offset: 0x118 // Line 177, Address: 0x20d9c8, Func Offset: 0x148 // Line 178, Address: 0x20d9d0, Func Offset: 0x150 // Line 179, Address: 0x20d9d8, Func Offset: 0x158 // Line 181, Address: 0x20da14, Func Offset: 0x194 // Line 184, Address: 0x20da18, Func Offset: 0x198 // Line 187, Address: 0x20da20, Func Offset: 0x1a0 // Line 194, Address: 0x20da60, Func Offset: 0x1e0 // Line 197, Address: 0x20da68, Func Offset: 0x1e8 // Line 208, Address: 0x20da70, Func Offset: 0x1f0 // Line 211, Address: 0x20da78, Func Offset: 0x1f8 // Line 208, Address: 0x20da7c, Func Offset: 0x1fc // Line 212, Address: 0x20da80, Func Offset: 0x200 // Line 216, Address: 0x20da84, Func Offset: 0x204 // Line 213, Address: 0x20da88, Func Offset: 0x208 // Line 216, Address: 0x20da8c, Func Offset: 0x20c // Line 223, Address: 0x20daa8, Func Offset: 0x228 // Line 224, Address: 0x20db14, Func Offset: 0x294 // Line 225, Address: 0x20db1c, Func Offset: 0x29c // Line 227, Address: 0x20db24, Func Offset: 0x2a4 // Line 231, Address: 0x20db60, Func Offset: 0x2e0 // Line 233, Address: 0x20db68, Func Offset: 0x2e8 // Line 234, Address: 0x20db98, Func Offset: 0x318 // Line 235, Address: 0x20dba0, Func Offset: 0x320 // Line 236, Address: 0x20dba8, Func Offset: 0x328 // Line 238, Address: 0x20dbe4, Func Offset: 0x364 // Line 245, Address: 0x20dbe8, Func Offset: 0x368 // Line 248, Address: 0x20dbf0, Func Offset: 0x370 // Line 259, Address: 0x20dc30, Func Offset: 0x3b0 // Line 260, Address: 0x20dc38, Func Offset: 0x3b8 // Line 262, Address: 0x20dc3c, Func Offset: 0x3bc // Line 267, Address: 0x20dc48, Func Offset: 0x3c8 // Func End, Address: 0x20dc6c, Func Offset: 0x3ec } // xSTShutdown__Fv // Start address: 0x20dc70 int32 xSTShutdown() { // Line 102, Address: 0x20dc70, Func Offset: 0 // Line 105, Address: 0x20dc80, Func Offset: 0x10 // Line 112, Address: 0x20dc90, Func Offset: 0x20 // Line 115, Address: 0x20dd18, Func Offset: 0xa8 // Line 121, Address: 0x20dd20, Func Offset: 0xb0 // Line 120, Address: 0x20dd2c, Func Offset: 0xbc // Line 121, Address: 0x20dd30, Func Offset: 0xc0 // Func End, Address: 0x20dd38, Func Offset: 0xc8 } // xSTStartup__FP19st_PACKER_ASSETTYPE // Start address: 0x20dd40 int32 xSTStartup(st_PACKER_ASSETTYPE* handlers) { // Line 64, Address: 0x20dd40, Func Offset: 0 // Line 66, Address: 0x20dd48, Func Offset: 0x8 // Line 72, Address: 0x20dd58, Func Offset: 0x18 // Line 78, Address: 0x20dd5c, Func Offset: 0x1c // Line 81, Address: 0x20dd70, Func Offset: 0x30 // Line 84, Address: 0x20dd78, Func Offset: 0x38 // Line 91, Address: 0x20dd84, Func Offset: 0x44 // Line 94, Address: 0x20dd88, Func Offset: 0x48 // Line 93, Address: 0x20dd8c, Func Offset: 0x4c // Line 94, Address: 0x20dd90, Func Offset: 0x50 // Func End, Address: 0x20dd98, Func Offset: 0x58 }
/**_________________________________________________________________ class: BeamSpotOnlineProducer.h package: RecoVertex/BeamSpotProducer author: Francisco Yumiceva, Fermilab (yumiceva@fnal.gov) modified by: Simone Gennai, INFN MIB ________________________________________________________________**/ #include "CondFormats/BeamSpotObjects/interface/BeamSpotObjects.h" #include "CondFormats/DataRecord/interface/BeamSpotObjectsRcd.h" #include "CondFormats/DataRecord/interface/BeamSpotTransientObjectsRcd.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerEvmReadoutRecord.h" #include "DataFormats/Scalers/interface/BeamSpotOnline.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/Utilities/interface/ESGetToken.h" class BeamSpotOnlineProducer : public edm::stream::EDProducer<> { public: /// constructor explicit BeamSpotOnlineProducer(const edm::ParameterSet& iConf); /// produce a beam spot class void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override; ///Fill descriptor static void fillDescriptions(edm::ConfigurationDescriptions& iDesc); private: const bool changeFrame_; const double theMaxZ, theSetSigmaZ; double theMaxR2; const bool useTransientRecord_; const edm::EDGetTokenT<BeamSpotOnlineCollection> scalerToken_; const edm::EDGetTokenT<L1GlobalTriggerEvmReadoutRecord> l1GtEvmReadoutRecordToken_; const edm::ESGetToken<BeamSpotObjects, BeamSpotObjectsRcd> beamToken_; const edm::ESGetToken<BeamSpotObjects, BeamSpotTransientObjectsRcd> beamTransientToken_; // watch IOV transition to emit warnings edm::ESWatcher<BeamSpotTransientObjectsRcd> beamTransientRcdESWatcher_; const unsigned int theBeamShoutMode; }; using namespace edm; BeamSpotOnlineProducer::BeamSpotOnlineProducer(const ParameterSet& iconf) : changeFrame_(iconf.getParameter<bool>("changeToCMSCoordinates")), theMaxZ(iconf.getParameter<double>("maxZ")), theSetSigmaZ(iconf.getParameter<double>("setSigmaZ")), useTransientRecord_(iconf.getParameter<bool>("useTransientRecord")), scalerToken_(consumes<BeamSpotOnlineCollection>(iconf.getParameter<InputTag>("src"))), l1GtEvmReadoutRecordToken_(consumes<L1GlobalTriggerEvmReadoutRecord>(iconf.getParameter<InputTag>("gtEvmLabel"))), beamToken_(esConsumes<BeamSpotObjects, BeamSpotObjectsRcd>()), beamTransientToken_(esConsumes<BeamSpotObjects, BeamSpotTransientObjectsRcd>()), theBeamShoutMode(iconf.getUntrackedParameter<unsigned int>("beamMode", 11)) { theMaxR2 = iconf.getParameter<double>("maxRadius"); theMaxR2 *= theMaxR2; produces<reco::BeamSpot>(); } void BeamSpotOnlineProducer::fillDescriptions(edm::ConfigurationDescriptions& iDesc) { edm::ParameterSetDescription ps; ps.add<bool>("changeToCMSCoordinates", false); ps.add<double>("maxZ", 40.); ps.add<double>("setSigmaZ", -1.); ps.addUntracked<unsigned int>("beamMode", 11); ps.add<InputTag>("src", InputTag("hltScalersRawToDigi")); ps.add<InputTag>("gtEvmLabel", InputTag("")); ps.add<double>("maxRadius", 2.0); ps.add<bool>("useTransientRecord", false); iDesc.addWithDefaultLabel(ps); } void BeamSpotOnlineProducer::produce(Event& iEvent, const EventSetup& iSetup) { // product is a reco::BeamSpot object auto result = std::make_unique<reco::BeamSpot>(); reco::BeamSpot aSpot; //shout MODE only in stable beam bool shoutMODE = false; edm::Handle<L1GlobalTriggerEvmReadoutRecord> gtEvmReadoutRecord; if (iEvent.getByToken(l1GtEvmReadoutRecordToken_, gtEvmReadoutRecord)) { if (gtEvmReadoutRecord->gtfeWord().beamMode() == theBeamShoutMode) shoutMODE = true; } else { shoutMODE = true; } bool fallBackToDB = false; if (useTransientRecord_) { auto const& spotDB = iSetup.getData(beamTransientToken_); if (spotDB.GetBeamType() != 2) { if (shoutMODE && beamTransientRcdESWatcher_.check(iSetup)) { edm::LogWarning("BeamSpotFromDB") << "Online Beam Spot producer falls back to DB value because the ESProducer returned a fake beamspot "; } fallBackToDB = true; } else { // translate from BeamSpotObjects to reco::BeamSpot // in case we need to switch to LHC reference frame // ignore for the moment rotations, and translations double f = 1.; if (changeFrame_) f = -1.; reco::BeamSpot::Point apoint(f * spotDB.GetX(), f * spotDB.GetY(), f * spotDB.GetZ()); reco::BeamSpot::CovarianceMatrix matrix; for (int i = 0; i < 7; ++i) { for (int j = 0; j < 7; ++j) { matrix(i, j) = spotDB.GetCovariance(i, j); } } double sigmaZ = spotDB.GetSigmaZ(); if (theSetSigmaZ > 0) sigmaZ = theSetSigmaZ; // this assume beam width same in x and y aSpot = reco::BeamSpot(apoint, sigmaZ, spotDB.Getdxdz(), spotDB.Getdydz(), spotDB.GetBeamWidthX(), matrix); aSpot.setBeamWidthY(spotDB.GetBeamWidthY()); aSpot.setEmittanceX(spotDB.GetEmittanceX()); aSpot.setEmittanceY(spotDB.GetEmittanceY()); aSpot.setbetaStar(spotDB.GetBetaStar()); aSpot.setType(reco::BeamSpot::Tracker); } } else { // get scalar collection Handle<BeamSpotOnlineCollection> handleScaler; iEvent.getByToken(scalerToken_, handleScaler); // beam spot scalar object BeamSpotOnline spotOnline; // product is a reco::BeamSpot object auto result = std::make_unique<reco::BeamSpot>(); if (!handleScaler->empty()) { // get one element spotOnline = *(handleScaler->begin()); // in case we need to switch to LHC reference frame // ignore for the moment rotations, and translations double f = 1.; if (changeFrame_) f = -1.; reco::BeamSpot::Point apoint(f * spotOnline.x(), spotOnline.y(), f * spotOnline.z()); reco::BeamSpot::CovarianceMatrix matrix; matrix(0, 0) = spotOnline.err_x() * spotOnline.err_x(); matrix(1, 1) = spotOnline.err_y() * spotOnline.err_y(); matrix(2, 2) = spotOnline.err_z() * spotOnline.err_z(); matrix(3, 3) = spotOnline.err_sigma_z() * spotOnline.err_sigma_z(); double sigmaZ = spotOnline.sigma_z(); if (theSetSigmaZ > 0) sigmaZ = theSetSigmaZ; aSpot = reco::BeamSpot(apoint, sigmaZ, spotOnline.dxdz(), f * spotOnline.dydz(), spotOnline.width_x(), matrix); aSpot.setBeamWidthY(spotOnline.width_y()); aSpot.setEmittanceX(0.); aSpot.setEmittanceY(0.); aSpot.setbetaStar(0.); aSpot.setType(reco::BeamSpot::LHC); // flag value from scalars // check if we have a valid beam spot fit result from online DQM if (spotOnline.x() == 0 && spotOnline.y() == 0 && spotOnline.z() == 0 && spotOnline.width_x() == 0 && spotOnline.width_y() == 0) { if (shoutMODE) { edm::LogWarning("BeamSpotFromDB") << "Online Beam Spot producer falls back to DB value because the scaler values are zero "; } fallBackToDB = true; } double r2 = spotOnline.x() * spotOnline.x() + spotOnline.y() * spotOnline.y(); if (std::abs(spotOnline.z()) >= theMaxZ || r2 >= theMaxR2) { if (shoutMODE) { edm::LogError("BeamSpotFromDB") << "Online Beam Spot producer falls back to DB value because the scaler values are too big to be true :" << spotOnline.x() << " " << spotOnline.y() << " " << spotOnline.z(); } fallBackToDB = true; } } else { //empty online beamspot collection: FED data was empty //the error should probably have been send at unpacker level fallBackToDB = true; } } if (fallBackToDB) { edm::ESHandle<BeamSpotObjects> beamhandle = iSetup.getHandle(beamToken_); const BeamSpotObjects* spotDB = beamhandle.product(); // translate from BeamSpotObjects to reco::BeamSpot reco::BeamSpot::Point apoint(spotDB->GetX(), spotDB->GetY(), spotDB->GetZ()); reco::BeamSpot::CovarianceMatrix matrix; for (int i = 0; i < 7; ++i) { for (int j = 0; j < 7; ++j) { matrix(i, j) = spotDB->GetCovariance(i, j); } } // this assume beam width same in x and y aSpot = reco::BeamSpot( apoint, spotDB->GetSigmaZ(), spotDB->Getdxdz(), spotDB->Getdydz(), spotDB->GetBeamWidthX(), matrix); aSpot.setBeamWidthY(spotDB->GetBeamWidthY()); aSpot.setEmittanceX(spotDB->GetEmittanceX()); aSpot.setEmittanceY(spotDB->GetEmittanceY()); aSpot.setbetaStar(spotDB->GetBetaStar()); aSpot.setType(reco::BeamSpot::Tracker); } *result = aSpot; iEvent.put(std::move(result)); } #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(BeamSpotOnlineProducer);
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTestExt/MockNamedValue.h" #include "CppUTest/PlatformSpecificFunctions.h" MockNamedValueComparatorsAndCopiersRepository* MockNamedValue::defaultRepository_ = NULLPTR; const double MockNamedValue::defaultDoubleTolerance = 0.005; void MockNamedValue::setDefaultComparatorsAndCopiersRepository(MockNamedValueComparatorsAndCopiersRepository* repository) { defaultRepository_ = repository; } MockNamedValue::MockNamedValue(const SimpleString& name) : name_(name), type_("int"), size_(0), comparator_(NULLPTR), copier_(NULLPTR) { value_.intValue_ = 0; } MockNamedValue::~MockNamedValue() { } void MockNamedValue::setValue(bool value) { type_ = "bool"; value_.boolValue_ = value; } void MockNamedValue::setValue(unsigned int value) { type_ = "unsigned int"; value_.unsignedIntValue_ = value; } void MockNamedValue::setValue(int value) { type_ = "int"; value_.intValue_ = value; } void MockNamedValue::setValue(long int value) { type_ = "long int"; value_.longIntValue_ = value; } void MockNamedValue::setValue(unsigned long int value) { type_ = "unsigned long int"; value_.unsignedLongIntValue_ = value; } #ifdef CPPUTEST_USE_LONG_LONG void MockNamedValue::setValue(cpputest_longlong value) { type_ = "long long int"; value_.longLongIntValue_ = value; } void MockNamedValue::setValue(cpputest_ulonglong value) { type_ = "unsigned long long int"; value_.unsignedLongLongIntValue_ = value; } #else void MockNamedValue::setValue(cpputest_longlong) { FAIL("Long Long type is not supported"); } void MockNamedValue::setValue(cpputest_ulonglong) { FAIL("Unsigned Long Long type is not supported"); } #endif void MockNamedValue::setValue(double value) { setValue(value, defaultDoubleTolerance); } void MockNamedValue::setValue(double value, double tolerance) { type_ = "double"; value_.doubleValue_.value = value; value_.doubleValue_.tolerance = tolerance; } void MockNamedValue::setValue(void* value) { type_ = "void*"; value_.pointerValue_ = value; } void MockNamedValue::setValue(const void* value) { type_ = "const void*"; value_.constPointerValue_ = value; } void MockNamedValue::setValue(void (*value)()) { type_ = "void (*)()"; value_.functionPointerValue_ = value; } void MockNamedValue::setValue(const char* value) { type_ = "const char*"; value_.stringValue_ = value; } void MockNamedValue::setMemoryBuffer(const unsigned char* value, size_t size) { type_ = "const unsigned char*"; value_.memoryBufferValue_ = value; size_ = size; } void MockNamedValue::setConstObjectPointer(const SimpleString& type, const void* objectPtr) { type_ = type; value_.constObjectPointerValue_ = objectPtr; if (defaultRepository_) { comparator_ = defaultRepository_->getComparatorForType(type); copier_ = defaultRepository_->getCopierForType(type); } } void MockNamedValue::setObjectPointer(const SimpleString& type, void* objectPtr) { type_ = type; value_.objectPointerValue_ = objectPtr; if (defaultRepository_) { comparator_ = defaultRepository_->getComparatorForType(type); copier_ = defaultRepository_->getCopierForType(type); } } void MockNamedValue::setSize(size_t size) { size_ = size; } void MockNamedValue::setName(const char* name) { name_ = name; } SimpleString MockNamedValue::getName() const { return name_; } SimpleString MockNamedValue::getType() const { return type_; } bool MockNamedValue::getBoolValue() const { STRCMP_EQUAL("bool", type_.asCharString()); return value_.boolValue_; } unsigned int MockNamedValue::getUnsignedIntValue() const { if(type_ == "int" && value_.intValue_ >= 0) return (unsigned int)value_.intValue_; else { STRCMP_EQUAL("unsigned int", type_.asCharString()); return value_.unsignedIntValue_; } } int MockNamedValue::getIntValue() const { STRCMP_EQUAL("int", type_.asCharString()); return value_.intValue_; } long int MockNamedValue::getLongIntValue() const { if(type_ == "int") return value_.intValue_; else if(type_ == "unsigned int") return (long int)value_.unsignedIntValue_; else { STRCMP_EQUAL("long int", type_.asCharString()); return value_.longIntValue_; } } unsigned long int MockNamedValue::getUnsignedLongIntValue() const { if(type_ == "unsigned int") return value_.unsignedIntValue_; else if(type_ == "int" && value_.intValue_ >= 0) return (unsigned long int)value_.intValue_; else if(type_ == "long int" && value_.longIntValue_ >= 0) return (unsigned long int)value_.longIntValue_; else { STRCMP_EQUAL("unsigned long int", type_.asCharString()); return value_.unsignedLongIntValue_; } } #ifdef CPPUTEST_USE_LONG_LONG cpputest_longlong MockNamedValue::getLongLongIntValue() const { if(type_ == "int") return value_.intValue_; else if(type_ == "unsigned int") return (long long int)value_.unsignedIntValue_; else if(type_ == "long int") return value_.longIntValue_; else if(type_ == "unsigned long int") return (long long int)value_.unsignedLongIntValue_; else { STRCMP_EQUAL("long long int", type_.asCharString()); return value_.longLongIntValue_; } } cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const { if(type_ == "unsigned int") return value_.unsignedIntValue_; else if(type_ == "int" && value_.intValue_ >= 0) return (unsigned long long int)value_.intValue_; else if(type_ == "long int" && value_.longIntValue_ >= 0) return (unsigned long long int)value_.longIntValue_; else if(type_ == "unsigned long int") return value_.unsignedLongIntValue_; else if(type_ == "long long int" && value_.longLongIntValue_ >= 0) return (unsigned long long int)value_.longLongIntValue_; else { STRCMP_EQUAL("unsigned long long int", type_.asCharString()); return value_.unsignedLongLongIntValue_; } } #else cpputest_longlong MockNamedValue::getLongLongIntValue() const { FAIL("Long Long type is not supported"); return cpputest_longlong(0); } cpputest_ulonglong MockNamedValue::getUnsignedLongLongIntValue() const { FAIL("Unsigned Long Long type is not supported"); return cpputest_ulonglong(0); } #endif double MockNamedValue::getDoubleValue() const { STRCMP_EQUAL("double", type_.asCharString()); return value_.doubleValue_.value; } double MockNamedValue::getDoubleTolerance() const { STRCMP_EQUAL("double", type_.asCharString()); return value_.doubleValue_.tolerance; } const char* MockNamedValue::getStringValue() const { STRCMP_EQUAL("const char*", type_.asCharString()); return value_.stringValue_; } void* MockNamedValue::getPointerValue() const { STRCMP_EQUAL("void*", type_.asCharString()); return value_.pointerValue_; } const void* MockNamedValue::getConstPointerValue() const { STRCMP_EQUAL("const void*", type_.asCharString()); return value_.pointerValue_; } void (*MockNamedValue::getFunctionPointerValue() const)() { STRCMP_EQUAL("void (*)()", type_.asCharString()); return value_.functionPointerValue_; } const unsigned char* MockNamedValue::getMemoryBuffer() const { STRCMP_EQUAL("const unsigned char*", type_.asCharString()); return value_.memoryBufferValue_; } const void* MockNamedValue::getConstObjectPointer() const { return value_.constObjectPointerValue_; } void* MockNamedValue::getObjectPointer() const { return value_.objectPointerValue_; } size_t MockNamedValue::getSize() const { return size_; } MockNamedValueComparator* MockNamedValue::getComparator() const { return comparator_; } MockNamedValueCopier* MockNamedValue::getCopier() const { return copier_; } bool MockNamedValue::equals(const MockNamedValue& p) const { if((type_ == "long int") && (p.type_ == "int")) return value_.longIntValue_ == p.value_.intValue_; else if((type_ == "int") && (p.type_ == "long int")) return value_.intValue_ == p.value_.longIntValue_; else if((type_ == "unsigned int") && (p.type_ == "int")) return (p.value_.intValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned int)p.value_.intValue_); else if((type_ == "int") && (p.type_ == "unsigned int")) return (value_.intValue_ >= 0) && ((unsigned int)value_.intValue_ == p.value_.unsignedIntValue_); else if((type_ == "unsigned long int") && (p.type_ == "int")) return (p.value_.intValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long)p.value_.intValue_); else if((type_ == "int") && (p.type_ == "unsigned long int")) return (value_.intValue_ >= 0) && ((unsigned long)value_.intValue_ == p.value_.unsignedLongIntValue_); else if((type_ == "unsigned int") && (p.type_ == "long int")) return (p.value_.longIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long)p.value_.longIntValue_); else if((type_ == "long int") && (p.type_ == "unsigned int")) return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedIntValue_); else if((type_ == "unsigned int") && (p.type_ == "unsigned long int")) return value_.unsignedIntValue_ == p.value_.unsignedLongIntValue_; else if((type_ == "unsigned long int") && (p.type_ == "unsigned int")) return value_.unsignedLongIntValue_ == p.value_.unsignedIntValue_; else if((type_ == "long int") && (p.type_ == "unsigned long int")) return (value_.longIntValue_ >= 0) && ((unsigned long)value_.longIntValue_ == p.value_.unsignedLongIntValue_); else if((type_ == "unsigned long int") && (p.type_ == "long int")) return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long) p.value_.longIntValue_); #ifdef CPPUTEST_USE_LONG_LONG else if ((type_ == "long long int") && (p.type_ == "int")) return value_.longLongIntValue_ == p.value_.intValue_; else if ((type_ == "int") && (p.type_ == "long long int")) return value_.intValue_ == p.value_.longLongIntValue_; else if ((type_ == "long long int") && (p.type_ == "long int")) return value_.longLongIntValue_ == p.value_.longIntValue_; else if ((type_ == "long int") && (p.type_ == "long long int")) return value_.longIntValue_ == p.value_.longLongIntValue_; else if ((type_ == "long long int") && (p.type_ == "unsigned int")) return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedIntValue_); else if ((type_ == "unsigned int") && (p.type_ == "long long int")) return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedIntValue_ == (unsigned long long)p.value_.longLongIntValue_); else if ((type_ == "long long int") && (p.type_ == "unsigned long int")) return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongIntValue_); else if ((type_ == "unsigned long int") && (p.type_ == "long long int")) return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_); else if ((type_ == "long long int") && (p.type_ == "unsigned long long int")) return (value_.longLongIntValue_ >= 0) && ((unsigned long long)value_.longLongIntValue_ == p.value_.unsignedLongLongIntValue_); else if ((type_ == "unsigned long long int") && (p.type_ == "long long int")) return (p.value_.longLongIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longLongIntValue_); else if ((type_ == "unsigned long long int") && (p.type_ == "int")) return (p.value_.intValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.intValue_); else if ((type_ == "int") && (p.type_ == "unsigned long long int")) return (value_.intValue_ >= 0) && ((unsigned long long)value_.intValue_ == p.value_.unsignedLongLongIntValue_); else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned int")) return value_.unsignedLongLongIntValue_ == p.value_.unsignedIntValue_; else if ((type_ == "unsigned int") && (p.type_ == "unsigned long long int")) return value_.unsignedIntValue_ == p.value_.unsignedLongLongIntValue_; else if ((type_ == "unsigned long long int") && (p.type_ == "long int")) return (p.value_.longIntValue_ >= 0) && (value_.unsignedLongLongIntValue_ == (unsigned long long)p.value_.longIntValue_); else if ((type_ == "long int") && (p.type_ == "unsigned long long int")) return (value_.longIntValue_ >= 0) && ((unsigned long long)value_.longIntValue_ == p.value_.unsignedLongLongIntValue_); else if ((type_ == "unsigned long long int") && (p.type_ == "unsigned long int")) return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongIntValue_; else if ((type_ == "unsigned long int") && (p.type_ == "unsigned long long int")) return value_.unsignedLongIntValue_ == p.value_.unsignedLongLongIntValue_; #endif if (type_ != p.type_) return false; if (type_ == "bool") return value_.boolValue_ == p.value_.boolValue_; else if (type_ == "int") return value_.intValue_ == p.value_.intValue_; else if (type_ == "unsigned int") return value_.unsignedIntValue_ == p.value_.unsignedIntValue_; else if (type_ == "long int") return value_.longIntValue_ == p.value_.longIntValue_; else if (type_ == "unsigned long int") return value_.unsignedLongIntValue_ == p.value_.unsignedLongIntValue_; #ifdef CPPUTEST_USE_LONG_LONG else if (type_ == "long long int") return value_.longLongIntValue_ == p.value_.longLongIntValue_; else if (type_ == "unsigned long long int") return value_.unsignedLongLongIntValue_ == p.value_.unsignedLongLongIntValue_; #endif else if (type_ == "const char*") return SimpleString(value_.stringValue_) == SimpleString(p.value_.stringValue_); else if (type_ == "void*") return value_.pointerValue_ == p.value_.pointerValue_; else if (type_ == "const void*") return value_.constPointerValue_ == p.value_.constPointerValue_; else if (type_ == "void (*)()") return value_.functionPointerValue_ == p.value_.functionPointerValue_; else if (type_ == "double") return (doubles_equal(value_.doubleValue_.value, p.value_.doubleValue_.value, value_.doubleValue_.tolerance)); else if (type_ == "const unsigned char*") { if (size_ != p.size_) { return false; } return SimpleString::MemCmp(value_.memoryBufferValue_, p.value_.memoryBufferValue_, size_) == 0; } if (comparator_) return comparator_->isEqual(value_.constObjectPointerValue_, p.value_.constObjectPointerValue_); return false; } bool MockNamedValue::compatibleForCopying(const MockNamedValue& p) const { if (type_ == p.type_) return true; if ((type_ == "const void*") && (p.type_ == "void*")) return true; return false; } SimpleString MockNamedValue::toString() const { if (type_ == "bool") return StringFrom(value_.boolValue_); else if (type_ == "int") return StringFrom(value_.intValue_) + " " + BracketsFormattedHexStringFrom(value_.intValue_); else if (type_ == "unsigned int") return StringFrom(value_.unsignedIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedIntValue_); else if (type_ == "long int") return StringFrom(value_.longIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longIntValue_); else if (type_ == "unsigned long int") return StringFrom(value_.unsignedLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongIntValue_); #ifdef CPPUTEST_USE_LONG_LONG else if (type_ == "long long int") return StringFrom(value_.longLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.longLongIntValue_); else if (type_ == "unsigned long long int") return StringFrom(value_.unsignedLongLongIntValue_) + " " + BracketsFormattedHexStringFrom(value_.unsignedLongLongIntValue_); #endif else if (type_ == "const char*") return value_.stringValue_; else if (type_ == "void*") return StringFrom(value_.pointerValue_); else if (type_ == "void (*)()") return StringFrom(value_.functionPointerValue_); else if (type_ == "const void*") return StringFrom(value_.constPointerValue_); else if (type_ == "double") return StringFrom(value_.doubleValue_.value); else if (type_ == "const unsigned char*") return StringFromBinaryWithSizeOrNull(value_.memoryBufferValue_, size_); if (comparator_) return comparator_->valueToString(value_.constObjectPointerValue_); return StringFromFormat("No comparator found for type: \"%s\"", type_.asCharString()); } void MockNamedValueListNode::setNext(MockNamedValueListNode* node) { next_ = node; } MockNamedValueListNode* MockNamedValueListNode::next() { return next_; } MockNamedValue* MockNamedValueListNode::item() { return data_; } void MockNamedValueListNode::destroy() { delete data_; } MockNamedValueListNode::MockNamedValueListNode(MockNamedValue* newValue) : data_(newValue), next_(NULLPTR) { } SimpleString MockNamedValueListNode::getName() const { return data_->getName(); } SimpleString MockNamedValueListNode::getType() const { return data_->getType(); } MockNamedValueList::MockNamedValueList() : head_(NULLPTR) { } void MockNamedValueList::clear() { while (head_) { MockNamedValueListNode* n = head_->next(); head_->destroy(); delete head_; head_ = n; } } void MockNamedValueList::add(MockNamedValue* newValue) { MockNamedValueListNode* newNode = new MockNamedValueListNode(newValue); if (head_ == NULLPTR) head_ = newNode; else { MockNamedValueListNode* lastNode = head_; while (lastNode->next()) lastNode = lastNode->next(); lastNode->setNext(newNode); } } MockNamedValue* MockNamedValueList::getValueByName(const SimpleString& name) { for (MockNamedValueListNode * p = head_; p; p = p->next()) if (p->getName() == name) return p->item(); return NULLPTR; } MockNamedValueListNode* MockNamedValueList::begin() { return head_; } struct MockNamedValueComparatorsAndCopiersRepositoryNode { MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueComparatorsAndCopiersRepositoryNode* next) : name_(name), comparator_(comparator), copier_(NULLPTR), next_(next) {} MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next) : name_(name), comparator_(NULLPTR), copier_(copier), next_(next) {} MockNamedValueComparatorsAndCopiersRepositoryNode(const SimpleString& name, MockNamedValueComparator* comparator, MockNamedValueCopier* copier, MockNamedValueComparatorsAndCopiersRepositoryNode* next) : name_(name), comparator_(comparator), copier_(copier), next_(next) {} SimpleString name_; MockNamedValueComparator* comparator_; MockNamedValueCopier* copier_; MockNamedValueComparatorsAndCopiersRepositoryNode* next_; }; MockNamedValueComparatorsAndCopiersRepository::MockNamedValueComparatorsAndCopiersRepository() : head_(NULLPTR) { } MockNamedValueComparatorsAndCopiersRepository::~MockNamedValueComparatorsAndCopiersRepository() { clear(); } void MockNamedValueComparatorsAndCopiersRepository::clear() { while (head_) { MockNamedValueComparatorsAndCopiersRepositoryNode* next = head_->next_; delete head_; head_ = next; } } void MockNamedValueComparatorsAndCopiersRepository::installComparator(const SimpleString& name, MockNamedValueComparator& comparator) { head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(name, &comparator, head_); } void MockNamedValueComparatorsAndCopiersRepository::installCopier(const SimpleString& name, MockNamedValueCopier& copier) { head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(name, &copier, head_); } MockNamedValueComparator* MockNamedValueComparatorsAndCopiersRepository::getComparatorForType(const SimpleString& name) { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name && p->comparator_) return p->comparator_; return NULLPTR; } MockNamedValueCopier* MockNamedValueComparatorsAndCopiersRepository::getCopierForType(const SimpleString& name) { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = head_; p; p = p->next_) if (p->name_ == name && p->copier_) return p->copier_; return NULLPTR; } void MockNamedValueComparatorsAndCopiersRepository::installComparatorsAndCopiers(const MockNamedValueComparatorsAndCopiersRepository& repository) { for (MockNamedValueComparatorsAndCopiersRepositoryNode* p = repository.head_; p; p = p->next_) head_ = new MockNamedValueComparatorsAndCopiersRepositoryNode(p->name_, p->comparator_, p->copier_, head_); }
/*************************************************************************/ /* gltf_spec_gloss.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gltf_spec_gloss.h" void GLTFSpecGloss::_bind_methods() { ClassDB::bind_method(D_METHOD("get_diffuse_img"), &GLTFSpecGloss::get_diffuse_img); ClassDB::bind_method(D_METHOD("set_diffuse_img", "diffuse_img"), &GLTFSpecGloss::set_diffuse_img); ClassDB::bind_method(D_METHOD("get_diffuse_factor"), &GLTFSpecGloss::get_diffuse_factor); ClassDB::bind_method(D_METHOD("set_diffuse_factor", "diffuse_factor"), &GLTFSpecGloss::set_diffuse_factor); ClassDB::bind_method(D_METHOD("get_gloss_factor"), &GLTFSpecGloss::get_gloss_factor); ClassDB::bind_method(D_METHOD("set_gloss_factor", "gloss_factor"), &GLTFSpecGloss::set_gloss_factor); ClassDB::bind_method(D_METHOD("get_specular_factor"), &GLTFSpecGloss::get_specular_factor); ClassDB::bind_method(D_METHOD("set_specular_factor", "specular_factor"), &GLTFSpecGloss::set_specular_factor); ClassDB::bind_method(D_METHOD("get_spec_gloss_img"), &GLTFSpecGloss::get_spec_gloss_img); ClassDB::bind_method(D_METHOD("set_spec_gloss_img", "spec_gloss_img"), &GLTFSpecGloss::set_spec_gloss_img); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "diffuse_img"), "set_diffuse_img", "get_diffuse_img"); // Ref<Image> ADD_PROPERTY(PropertyInfo(Variant::COLOR, "diffuse_factor"), "set_diffuse_factor", "get_diffuse_factor"); // Color ADD_PROPERTY(PropertyInfo(Variant::REAL, "gloss_factor"), "set_gloss_factor", "get_gloss_factor"); // float ADD_PROPERTY(PropertyInfo(Variant::COLOR, "specular_factor"), "set_specular_factor", "get_specular_factor"); // Color ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "spec_gloss_img"), "set_spec_gloss_img", "get_spec_gloss_img"); // Ref<Image> } Ref<Image> GLTFSpecGloss::get_diffuse_img() { return diffuse_img; } void GLTFSpecGloss::set_diffuse_img(Ref<Image> p_diffuse_img) { diffuse_img = p_diffuse_img; } Color GLTFSpecGloss::get_diffuse_factor() { return diffuse_factor; } void GLTFSpecGloss::set_diffuse_factor(Color p_diffuse_factor) { diffuse_factor = p_diffuse_factor; } float GLTFSpecGloss::get_gloss_factor() { return gloss_factor; } void GLTFSpecGloss::set_gloss_factor(float p_gloss_factor) { gloss_factor = p_gloss_factor; } Color GLTFSpecGloss::get_specular_factor() { return specular_factor; } void GLTFSpecGloss::set_specular_factor(Color p_specular_factor) { specular_factor = p_specular_factor; } Ref<Image> GLTFSpecGloss::get_spec_gloss_img() { return spec_gloss_img; } void GLTFSpecGloss::set_spec_gloss_img(Ref<Image> p_spec_gloss_img) { spec_gloss_img = p_spec_gloss_img; }
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/prediction_map.h" #include <algorithm> #include <limits> #include <unordered_set> #include <utility> #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; using apollo::hdmap::HDMapUtil; using apollo::hdmap::JunctionInfo; using apollo::hdmap::LaneInfo; using apollo::hdmap::MapPathPoint; using apollo::hdmap::OverlapInfo; using apollo::hdmap::PNCJunctionInfo; bool PredictionMap::Ready() { return HDMapUtil::BaseMapPtr() != nullptr; } Eigen::Vector2d PredictionMap::PositionOnLane( const std::shared_ptr<const LaneInfo> lane_info, const double s) { common::PointENU point = lane_info->GetSmoothPoint(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane( const std::shared_ptr<const LaneInfo> lane_info, const double s) { return lane_info->Heading(s); } double PredictionMap::CurvatureOnLane(const std::string& lane_id, const double s) { std::shared_ptr<const hdmap::LaneInfo> lane_info = LaneById(lane_id); if (lane_info == nullptr) { AERROR << "Null lane_info ptr found"; return 0.0; } return lane_info->Curvature(s); } double PredictionMap::LaneTotalWidth( const std::shared_ptr<const hdmap::LaneInfo> lane_info, const double s) { double left = 0.0; double right = 0.0; lane_info->GetWidth(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { return HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(str_id)); } std::shared_ptr<const JunctionInfo> PredictionMap::JunctionById( const std::string& str_id) { return HDMapUtil::BaseMap().GetJunctionById(hdmap::MakeMapId(str_id)); } std::shared_ptr<const OverlapInfo> PredictionMap::OverlapById( const std::string& str_id) { return HDMapUtil::BaseMap().GetOverlapById(hdmap::MakeMapId(str_id)); } bool PredictionMap::GetProjection( const Eigen::Vector2d& pos, const std::shared_ptr<const LaneInfo> lane_info, double* s, double* l) { if (lane_info == nullptr) { return false; } return lane_info->GetProjection({pos.x(), pos.y()}, s, l); } bool PredictionMap::HasNearbyLane(const double x, const double y, const double radius) { common::PointENU point_enu; point_enu.set_x(x); point_enu.set_y(y); std::vector<std::shared_ptr<const LaneInfo>> lanes; HDMapUtil::BaseMap().GetLanes(point_enu, radius, &lanes); return (!lanes.empty()); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info, const double s, MapPathPoint* path_point) { if (lane_info == nullptr) { return false; } const common::PointENU point = lane_info->GetSmoothPoint(s); const double heading = HeadingOnLane(lane_info, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } bool PredictionMap::IsVirtualLane(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane_info = HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id)); if (lane_info == nullptr) { return false; } const hdmap::Lane& lane = lane_info->lane(); bool left_virtual = lane.has_left_boundary() && lane.left_boundary().has_virtual_() && lane.left_boundary().virtual_(); bool right_virtual = lane.has_right_boundary() && lane.right_boundary().has_virtual_() && lane.right_boundary().virtual_(); return left_virtual && right_virtual; } bool PredictionMap::OnVirtualLane(const Eigen::Vector2d& point, const double radius) { std::vector<std::shared_ptr<const LaneInfo>> lanes; common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); HDMapUtil::BaseMap().GetLanes(hdmap_point, radius, &lanes); for (const auto& lane : lanes) { if (IsVirtualLane(lane->id().id())) { return true; } } return false; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, const bool on_lane, const int max_num_lane, const double max_lane_angle_diff, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); if (HDMapUtil::BaseMap().GetLanesWithHeading(hdmap_point, radius, heading, max_lane_angle_diff, &candidate_lanes) != 0) { return; } std::vector<std::pair<std::shared_ptr<const LaneInfo>, double>> lane_pairs; for (const auto& candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } if (on_lane && !candidate_lane->IsOnLane({point.x(), point.y()})) { continue; } if (!FLAGS_use_navigation_mode && !IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } double distance = 0.0; common::PointENU nearest_point = candidate_lane->GetNearestPoint({point.x(), point.y()}, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double diff = std::fabs(common::math::AngleDiff(heading, nearest_point_heading)); if (diff <= max_lane_angle_diff) { lane_pairs.emplace_back(candidate_lane, diff); } } if (lane_pairs.empty()) { return; } std::sort(lane_pairs.begin(), lane_pairs.end(), [](const std::pair<std::shared_ptr<const LaneInfo>, double>& p1, const std::pair<std::shared_ptr<const LaneInfo>, double>& p2) { return p1.second < p2.second; }); int count = 0; for (const auto& lane_pair : lane_pairs) { lanes->push_back(lane_pair.first); ++count; if (count >= max_num_lane) { break; } } } std::shared_ptr<const LaneInfo> PredictionMap::GetMostLikelyCurrentLane( const common::PointENU& position, const double radius, const double heading, const double angle_diff_threshold) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; if (HDMapUtil::BaseMap().GetLanesWithHeading(position, radius, heading, angle_diff_threshold, &candidate_lanes) != 0) { return nullptr; } double min_angle_diff = 2.0 * M_PI; std::shared_ptr<const LaneInfo> curr_lane_ptr = nullptr; for (auto candidate_lane : candidate_lanes) { if (!candidate_lane->IsOnLane({position.x(), position.y()})) { continue; } double distance = 0.0; common::PointENU nearest_point = candidate_lane->GetNearestPoint( {position.x(), position.y()}, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double angle_diff = std::fabs(common::math::AngleDiff(heading, nearest_point_heading)); if (angle_diff < min_angle_diff) { min_angle_diff = angle_diff; curr_lane_ptr = candidate_lane; } } return curr_lane_ptr; } bool PredictionMap::IsProjectionApproximateWithinLane( const Eigen::Vector2d& ego_position, const std::string& lane_id) { auto ptr_lane = LaneById(lane_id); const auto& lane_points = ptr_lane->points(); if (lane_points.size() < 2) { return false; } const auto& start_point = lane_points.front(); const auto& end_point = lane_points.back(); auto lane_vec = end_point - start_point; auto approx_lane_length = lane_vec.Length(); if (approx_lane_length < 1.0e-3) { return false; } auto dist_vec = common::math::Vec2d(ego_position.x(), ego_position.y()) - start_point; auto projection_length = dist_vec.InnerProd(lane_vec) / approx_lane_length; if (projection_length < 0.0 || projection_length > approx_lane_length) { return false; } return true; } bool PredictionMap::NearJunction(const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const JunctionInfo>> junctions; HDMapUtil::BaseMap().GetJunctions(hdmap_point, radius, &junctions); return junctions.size() > 0; } bool PredictionMap::IsPointInJunction( const double x, const double y, const std::shared_ptr<const JunctionInfo> junction_info_ptr) { const Polygon2d& polygon = junction_info_ptr->polygon(); return polygon.IsPointIn({x, y}); } std::vector<std::shared_ptr<const JunctionInfo>> PredictionMap::GetJunctions( const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const JunctionInfo>> junctions; HDMapUtil::BaseMap().GetJunctions(hdmap_point, radius, &junctions); return junctions; } std::vector<std::shared_ptr<const PNCJunctionInfo>> PredictionMap::GetPNCJunctions(const Eigen::Vector2d& point, const double radius) { common::PointENU hdmap_point; hdmap_point.set_x(point.x()); hdmap_point.set_y(point.y()); std::vector<std::shared_ptr<const PNCJunctionInfo>> junctions; HDMapUtil::BaseMap().GetPNCJunctions(hdmap_point, radius, &junctions); return junctions; } bool PredictionMap::InJunction(const Eigen::Vector2d& point, const double radius) { auto junction_infos = GetJunctions(point, radius); if (junction_infos.empty()) { return false; } for (const auto junction_info : junction_infos) { if (junction_info == nullptr || !junction_info->junction().has_polygon()) { continue; } std::vector<Vec2d> vertices; for (const auto& point : junction_info->junction().polygon().point()) { vertices.emplace_back(point.x(), point.y()); } if (vertices.size() < 3) { continue; } Polygon2d junction_polygon{vertices}; if (junction_polygon.IsPointIn({point.x(), point.y()})) { return true; } } return false; } bool PredictionMap::IsLaneInJunction( const std::shared_ptr<const LaneInfo> lane_info, const std::string& junction_id) { if (lane_info == nullptr) { return false; } // first, check whether the lane is virtual if (!PredictionMap::IsVirtualLane(lane_info->lane().id().id())) { return false; } // second, use junction from lane if (lane_info->lane().has_junction_id() && lane_info->lane().junction_id().id() == junction_id) { return true; } // third, use junction from road auto ptr_road_info = HDMapUtil::BaseMap().GetRoadById(lane_info->road_id()); if (ptr_road_info->has_junction_id() && ptr_road_info->junction_id().id() == junction_id) { return true; } return false; } double PredictionMap::PathHeading(std::shared_ptr<const LaneInfo> lane_info, const common::PointENU& point) { double s = 0.0; double l = 0.0; if (lane_info->GetProjection({point.x(), point.y()}, &s, &l)) { return HeadingOnLane(lane_info, s); } else { return M_PI; } } bool PredictionMap::SmoothPointFromLane(const std::string& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { if (point == nullptr || heading == nullptr) { return false; } std::shared_ptr<const LaneInfo> lane = LaneById(id); common::PointENU hdmap_point = lane->GetSmoothPoint(s); *heading = PathHeading(lane, hdmap_point); point->x() = hdmap_point.x() - std::sin(*heading) * l; point->y() = hdmap_point.y() + std::cos(*heading) * l; return true; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, const double heading, const double radius, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, const int max_num_lane, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { if (lanes.empty()) { std::vector<std::shared_ptr<const LaneInfo>> prev_lanes; OnLane(prev_lanes, point, heading, radius, false, max_num_lane, FLAGS_max_lane_angle_diff, nearby_lanes); } else { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (s < 0.0 || s >= nearby_lane->total_length() || std::fabs(l) > radius) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (s < 0.0 || s >= nearby_lane->total_length() || std::fabs(l) > radius) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } } } } std::shared_ptr<const LaneInfo> PredictionMap::GetLeftNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold) { std::vector<std::string> neighbor_ids; for (const auto& lane_id : ptr_ego_lane->lane().left_neighbor_forward_lane_id()) { neighbor_ids.push_back(lane_id.id()); } return GetNeighborLane(ptr_ego_lane, ego_position, neighbor_ids, threshold); } std::shared_ptr<const LaneInfo> PredictionMap::GetRightNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const double threshold) { std::vector<std::string> neighbor_ids; for (const auto& lane_id : ptr_ego_lane->lane().right_neighbor_forward_lane_id()) { neighbor_ids.push_back(lane_id.id()); } return GetNeighborLane(ptr_ego_lane, ego_position, neighbor_ids, threshold); } std::shared_ptr<const LaneInfo> PredictionMap::GetNeighborLane( const std::shared_ptr<const LaneInfo>& ptr_ego_lane, const Eigen::Vector2d& ego_position, const std::vector<std::string>& neighbor_lane_ids, const double threshold) { double ego_s = 0.0; double ego_l = 0.0; GetProjection(ego_position, ptr_ego_lane, &ego_s, &ego_l); double s_diff_min = std::numeric_limits<double>::max(); std::shared_ptr<const LaneInfo> ptr_lane_min = nullptr; for (auto& lane_id : neighbor_lane_ids) { std::shared_ptr<const LaneInfo> ptr_lane = LaneById(lane_id); double s = -1.0; double l = 0.0; GetProjection(ego_position, ptr_lane, &s, &l); double s_diff = std::fabs(s - ego_s); if (s_diff < s_diff_min) { s_diff_min = s_diff; ptr_lane_min = ptr_lane; } } if (s_diff_min > threshold) { return nullptr; } return ptr_lane_min; } std::vector<std::string> PredictionMap::NearbyLaneIds( const Eigen::Vector2d& point, const double radius) { std::vector<std::string> lane_ids; std::vector<std::shared_ptr<const LaneInfo>> lanes; common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); HDMapUtil::BaseMap().GetLanes(hdmap_point, radius, &lanes); for (const auto& lane : lanes) { lane_ids.push_back(lane->id().id()); } return lane_ids; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (target_lane->id().id() == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (target_lane->id().id() == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (const auto& lane : lanes) { if (IsRightNeighborLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane(std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& successor_lane_id : curr_lane->lane().successor_id()) { if (target_lane->id().id() == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> target_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (target_lane == nullptr) { return false; } for (const auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (target_lane->id().id() == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> target_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(target_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane(std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return true; } return other_lane->id().id() == curr_lane->id().id(); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.empty()) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane = LaneById(lane_id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } std::vector<std::shared_ptr<const LaneInfo>> PredictionMap::GetNearbyLanes( const common::PointENU& position, const double nearby_radius) { CHECK(position.has_x() && position.has_y() && position.has_z()); CHECK(nearby_radius > 0.0); std::vector<std::shared_ptr<const LaneInfo>> nearby_lanes; HDMapUtil::BaseMap().GetLanes(position, nearby_radius, &nearby_lanes); return nearby_lanes; } } // namespace prediction } // namespace apollo
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdSkel/tokens.h" PXR_NAMESPACE_OPEN_SCOPE UsdSkelTokensType::UsdSkelTokensType() : joints("joints", TfToken::Immortal), primvarsSkelGeomBindTransform("primvars:skel:geomBindTransform", TfToken::Immortal), primvarsSkelJointIndices("primvars:skel:jointIndices", TfToken::Immortal), primvarsSkelJointWeights("primvars:skel:jointWeights", TfToken::Immortal), restTransforms("restTransforms", TfToken::Immortal), rotations("rotations", TfToken::Immortal), scales("scales", TfToken::Immortal), skelAnimationSource("skel:animationSource", TfToken::Immortal), skelJoints("skel:joints", TfToken::Immortal), skelSkeleton("skel:skeleton", TfToken::Immortal), translations("translations", TfToken::Immortal), allTokens({ joints, primvarsSkelGeomBindTransform, primvarsSkelJointIndices, primvarsSkelJointWeights, restTransforms, rotations, scales, skelAnimationSource, skelJoints, skelSkeleton, translations }) { } TfStaticData<UsdSkelTokensType> UsdSkelTokens; PXR_NAMESPACE_CLOSE_SCOPE
/*! @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause */ #include <pyclustering/utils/metric.hpp> #include <algorithm> namespace pyclustering { namespace utils { namespace metric { double average_neighbor_distance(const std::vector<std::vector<double> > * points, const std::size_t num_neigh) { std::vector<std::vector<double> > dist_matrix( points->size(), std::vector<double>(points->size(), 0.0) ); for (std::size_t i = 0; i < points->size(); i++) { for (std::size_t j = i + 1; j < points->size(); j++) { double distance = euclidean_distance( (*points)[i], (*points)[j] ); dist_matrix[i][j] = distance; dist_matrix[j][i] = distance; } std::sort(dist_matrix[i].begin(), dist_matrix[i].end()); } double total_distance = 0.0; for (std::size_t i = 0; i < points->size(); i++) { for (std::size_t j = 0; j < num_neigh; j++) { total_distance += dist_matrix[i][j + 1]; } } return total_distance / ( (double) num_neigh * (double) points->size() ); } } } }
#include "sjdbInsertJunctions.h" #include "sjdbLoadFromStream.h" #include "sjdbLoadFromFiles.h" #include "sjdbPrepare.h" #include "ErrorWarning.h" #include "loadGTF.h" #include "sjdbBuildIndex.h" #include "streamFuns.h" #include "genomeParametersWrite.h" void sjdbInsertJunctions(Parameters & P, Genome & mapGen, Genome & mapGen1, SjdbClass & sjdbLoci) { time_t rawtime; if (mapGen.sjdbN>0 && sjdbLoci.chr.size()==0) {//load from the saved genome, only if the loading did not happen already (if sjdb insertion happens at the 1st pass, sjdbLoci will be populated ifstream & sjdbStreamIn = ifstrOpen(P.pGe.gDir+"/sjdbList.out.tab", ERROR_OUT, "SOLUTION: re-generate the genome in pGe.gDir=" + P.pGe.gDir, P); sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),30); time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the generated genome " << P.pGe.gDir+"/sjdbList.out.tab" <<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; if (P.twoPass.pass2) {//load 1st pass new junctions //sjdbLoci already contains the junctions from before 1st pass ifstream sjdbStreamIn ( P.twoPass.pass1sjFile.c_str() ); if (sjdbStreamIn.fail()) { ostringstream errOut; errOut << "FATAL INPUT error, could not open input file with junctions from the 1st pass=" << P.twoPass.pass1sjFile <<"\n"; exitWithError(errOut.str(),std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P); }; sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),0); time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the 1st pass file: " << P.twoPass.pass1sjFile <<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; } else {//loading junctions from GTF or tab or from the saved genome is only allowed at the 1st pass //at the 2nd pass these are already in the sjdbLoci if (P.pGe.sjdbFileChrStartEnd.at(0)!="-") {//load from junction files sjdbLoadFromFiles(P,sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),10); time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the pGe.sjdbFileChrStartEnd file(s), " << sjdbLoci.chr.size()<<" total junctions\n\n"; }; if (P.pGe.sjdbGTFfile!="-") {//load from GTF loadGTF(sjdbLoci, P, P.sjdbInsert.outDir, mapGen); sjdbLoci.priority.resize(sjdbLoci.chr.size(),20); time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the GTF file: " << P.pGe.sjdbGTFfile<<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; }; char *Gsj=new char [2*mapGen.sjdbLength*sjdbLoci.chr.size()*(P.var.yes ? 2:1)+1];//array to store junction sequences, will be filled in sjdbPrepare sjdbPrepare (sjdbLoci, P, mapGen.chrStart[mapGen.nChrReal], P.sjdbInsert.outDir, mapGen, Gsj);//mapGen.nGenome - change when replacing junctions time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " Finished preparing junctions" <<endl; if (mapGen.sjdbN>P.limitSjdbInsertNsj) { ostringstream errOut; errOut << "Fatal LIMIT error: the number of junctions to be inserted on the fly ="<<mapGen.sjdbN<<" is larger than the limitSjdbInsertNsj="<<P.limitSjdbInsertNsj<<"\n"; errOut << "Fatal LIMIT error: the number of junctions to be inserted on the fly ="<<mapGen.sjdbN<<" is larger than the limitSjdbInsertNsj="<<P.limitSjdbInsertNsj<<"\n"; errOut << "SOLUTION: re-run with at least --limitSjdbInsertNsj "<<mapGen.sjdbN<<"\n"; exitWithError(errOut.str(),std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P); }; //insert junctions into the genome and SA and SAi sjdbBuildIndex (P, Gsj, mapGen.G, mapGen.SA, (P.twoPass.pass2 ? mapGen.SApass2 : mapGen.SApass1), mapGen.SAi, mapGen, mapGen1); delete [] Gsj; //junction sequences have been added to G time ( &rawtime ); P.inOut->logMain << timeMonthDayTime(rawtime) << " ..... finished inserting junctions into genome" <<endl; //write an extra 0 at the end of the array, filling the last bytes that otherwise are not accessible, but will be written to disk //this is - to avoid valgrind complaints. Note that SApass1 is allocated with plenty of space to spare. mapGen.SA.writePacked(mapGen.nSA,0); if (P.pGe.sjdbInsertSave=="All") {//save and copy all genome files into sjdbInsert.outDir, except those created above if (P.pGe.gDir != P.sjdbInsert.outDir) { copyFile(P.pGe.gDir+"/chrName.txt", P.sjdbInsert.outDir+"/chrName.txt"); copyFile(P.pGe.gDir+"/chrStart.txt", P.sjdbInsert.outDir+"/chrStart.txt"); copyFile(P.pGe.gDir+"/chrNameLength.txt", P.sjdbInsert.outDir+"/chrNameLength.txt"); copyFile(P.pGe.gDir+"/chrLength.txt", P.sjdbInsert.outDir+"/chrLength.txt"); }; mapGen.pGe.gFileSizes.clear(); mapGen.pGe.gFileSizes.push_back(mapGen.nGenome); mapGen.pGe.gFileSizes.push_back(mapGen.SA.lengthByte); genomeParametersWrite(P.sjdbInsert.outDir+("/genomeParameters.txt"), P, ERROR_OUT, mapGen); ofstream & genomeOut = ofstrOpen(P.sjdbInsert.outDir+"/Genome",ERROR_OUT, P); fstreamWriteBig(genomeOut,mapGen.G,mapGen.nGenome,P.sjdbInsert.outDir+"/Genome",ERROR_OUT,P); genomeOut.close(); ofstream & saOut = ofstrOpen(P.sjdbInsert.outDir+"/SA",ERROR_OUT, P); fstreamWriteBig(saOut,(char*) mapGen.SA.charArray, (streamsize) mapGen.SA.lengthByte, P.sjdbInsert.outDir+"/SA",ERROR_OUT,P); saOut.close(); ofstream & saIndexOut = ofstrOpen(P.sjdbInsert.outDir+"/SAindex",ERROR_OUT, P); fstreamWriteBig(saIndexOut, (char*) &P.pGe.gSAindexNbases, sizeof(P.pGe.gSAindexNbases),P.sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); fstreamWriteBig(saIndexOut, (char*) mapGen.genomeSAindexStart, sizeof(mapGen.genomeSAindexStart[0])*(P.pGe.gSAindexNbases+1),P.sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); fstreamWriteBig(saIndexOut, mapGen.SAi.charArray, mapGen.SAi.lengthByte,P.sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); saIndexOut.close(); }; //re-calculate genome-related parameters P.winBinN = mapGen.nGenome/(1LLU << P.winBinNbits)+1; };
/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/audio_processing_impl.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <type_traits> #include <utility> #include "absl/types/optional.h" #include "api/array_view.h" #include "common_audio/audio_converter.h" #include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/gain_applier.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/common.h" #include "modules/audio_processing/include/audio_frame_view.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/constructor_magic.h" #include "rtc_base/logging.h" #include "rtc_base/ref_counted_object.h" #include "rtc_base/time_utils.h" #include "rtc_base/trace_event.h" #include "system_wrappers/include/field_trial.h" #include "system_wrappers/include/metrics.h" #define RETURN_ON_ERR(expr) \ do { \ int err = (expr); \ if (err != kNoError) { \ return err; \ } \ } while (0) namespace webrtc { constexpr int AudioProcessing::kNativeSampleRatesHz[]; constexpr int kRuntimeSettingQueueSize = 100; namespace { static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) { switch (layout) { case AudioProcessing::kMono: case AudioProcessing::kStereo: return false; case AudioProcessing::kMonoAndKeyboard: case AudioProcessing::kStereoAndKeyboard: return true; } RTC_NOTREACHED(); return false; } bool SampleRateSupportsMultiBand(int sample_rate_hz) { return sample_rate_hz == AudioProcessing::kSampleRate32kHz || sample_rate_hz == AudioProcessing::kSampleRate48kHz; } // Checks whether the legacy ns functionality should be enforced. bool DetectLegacyNsEnforcement() { return field_trial::IsEnabled("WebRTC-NewNoiseSuppressionKillSwitch"); } // Identify the native processing rate that best handles a sample rate. int SuitableProcessRate(int minimum_rate, int max_splitting_rate, bool band_splitting_required) { const int uppermost_native_rate = band_splitting_required ? max_splitting_rate : 48000; for (auto rate : {16000, 32000, 48000}) { if (rate >= uppermost_native_rate) { return uppermost_native_rate; } if (rate >= minimum_rate) { return rate; } } RTC_NOTREACHED(); return uppermost_native_rate; } NoiseSuppression::Level NsConfigLevelToInterfaceLevel( AudioProcessing::Config::NoiseSuppression::Level level) { using NsConfig = AudioProcessing::Config::NoiseSuppression; switch (level) { case NsConfig::kLow: return NoiseSuppression::Level::kLow; case NsConfig::kModerate: return NoiseSuppression::Level::kModerate; case NsConfig::kHigh: return NoiseSuppression::Level::kHigh; case NsConfig::kVeryHigh: return NoiseSuppression::Level::kVeryHigh; default: RTC_NOTREACHED(); } } GainControl::Mode Agc1ConfigModeToInterfaceMode( AudioProcessing::Config::GainController1::Mode mode) { using Agc1Config = AudioProcessing::Config::GainController1; switch (mode) { case Agc1Config::kAdaptiveAnalog: return GainControl::kAdaptiveAnalog; case Agc1Config::kAdaptiveDigital: return GainControl::kAdaptiveDigital; case Agc1Config::kFixedDigital: return GainControl::kFixedDigital; } } // Maximum lengths that frame of samples being passed from the render side to // the capture side can have (does not apply to AEC3). static const size_t kMaxAllowedValuesOfSamplesPerBand = 160; static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480; // Maximum number of frames to buffer in the render queue. // TODO(peah): Decrease this once we properly handle hugely unbalanced // reverse and forward call numbers. static const size_t kMaxNumFramesToBuffer = 100; } // namespace // Throughout webrtc, it's assumed that success is represented by zero. static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero"); AudioProcessingImpl::SubmoduleStates::SubmoduleStates( bool capture_post_processor_enabled, bool render_pre_processor_enabled, bool capture_analyzer_enabled) : capture_post_processor_enabled_(capture_post_processor_enabled), render_pre_processor_enabled_(render_pre_processor_enabled), capture_analyzer_enabled_(capture_analyzer_enabled) {} bool AudioProcessingImpl::SubmoduleStates::Update( bool high_pass_filter_enabled, bool echo_canceller_enabled, bool mobile_echo_controller_enabled, bool residual_echo_detector_enabled, bool noise_suppressor_enabled, bool adaptive_gain_controller_enabled, bool gain_controller2_enabled, bool pre_amplifier_enabled, bool echo_controller_enabled, bool voice_detector_enabled, bool transient_suppressor_enabled) { bool changed = false; changed |= (high_pass_filter_enabled != high_pass_filter_enabled_); changed |= (echo_canceller_enabled != echo_canceller_enabled_); changed |= (mobile_echo_controller_enabled != mobile_echo_controller_enabled_); changed |= (residual_echo_detector_enabled != residual_echo_detector_enabled_); changed |= (noise_suppressor_enabled != noise_suppressor_enabled_); changed |= (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_); changed |= (gain_controller2_enabled != gain_controller2_enabled_); changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled); changed |= (echo_controller_enabled != echo_controller_enabled_); changed |= (voice_detector_enabled != voice_detector_enabled_); changed |= (transient_suppressor_enabled != transient_suppressor_enabled_); if (changed) { high_pass_filter_enabled_ = high_pass_filter_enabled; echo_canceller_enabled_ = echo_canceller_enabled; mobile_echo_controller_enabled_ = mobile_echo_controller_enabled; residual_echo_detector_enabled_ = residual_echo_detector_enabled; noise_suppressor_enabled_ = noise_suppressor_enabled; adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled; gain_controller2_enabled_ = gain_controller2_enabled; pre_amplifier_enabled_ = pre_amplifier_enabled; echo_controller_enabled_ = echo_controller_enabled; voice_detector_enabled_ = voice_detector_enabled; transient_suppressor_enabled_ = transient_suppressor_enabled; } changed |= first_update_; first_update_ = false; return changed; } bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive() const { return CaptureMultiBandProcessingPresent() || voice_detector_enabled_; } bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent() const { // If echo controller is present, assume it performs active processing. return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true); } bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive( bool ec_processing_active) const { return high_pass_filter_enabled_ || echo_canceller_enabled_ || mobile_echo_controller_enabled_ || noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ || (echo_controller_enabled_ && ec_processing_active); } bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive() const { return gain_controller2_enabled_ || capture_post_processor_enabled_ || pre_amplifier_enabled_; } bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const { return capture_analyzer_enabled_; } bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive() const { return RenderMultiBandProcessingActive() || echo_canceller_enabled_ || mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ || echo_controller_enabled_; } bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive() const { return render_pre_processor_enabled_; } bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive() const { return false; } bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const { return high_pass_filter_enabled_ || echo_canceller_enabled_ || mobile_echo_controller_enabled_ || noise_suppressor_enabled_; } AudioProcessingBuilder::AudioProcessingBuilder() = default; AudioProcessingBuilder::~AudioProcessingBuilder() = default; AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing( std::unique_ptr<CustomProcessing> capture_post_processing) { capture_post_processing_ = std::move(capture_post_processing); return *this; } AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing( std::unique_ptr<CustomProcessing> render_pre_processing) { render_pre_processing_ = std::move(render_pre_processing); return *this; } AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer( std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) { capture_analyzer_ = std::move(capture_analyzer); return *this; } AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory( std::unique_ptr<EchoControlFactory> echo_control_factory) { echo_control_factory_ = std::move(echo_control_factory); return *this; } AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector( rtc::scoped_refptr<EchoDetector> echo_detector) { echo_detector_ = std::move(echo_detector); return *this; } AudioProcessing* AudioProcessingBuilder::Create() { webrtc::Config config; return Create(config); } AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) { AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>( config, std::move(capture_post_processing_), std::move(render_pre_processing_), std::move(echo_control_factory_), std::move(echo_detector_), std::move(capture_analyzer_)); if (apm->Initialize() != AudioProcessing::kNoError) { delete apm; apm = nullptr; } return apm; } AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config) : AudioProcessingImpl(config, /*capture_post_processor=*/nullptr, /*render_pre_processor=*/nullptr, /*echo_control_factory=*/nullptr, /*echo_detector=*/nullptr, /*capture_analyzer=*/nullptr) {} int AudioProcessingImpl::instance_count_ = 0; AudioProcessingImpl::AudioProcessingImpl( const webrtc::Config& config, std::unique_ptr<CustomProcessing> capture_post_processor, std::unique_ptr<CustomProcessing> render_pre_processor, std::unique_ptr<EchoControlFactory> echo_control_factory, rtc::scoped_refptr<EchoDetector> echo_detector, std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) : data_dumper_( new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), enforced_usage_of_legacy_ns_(DetectLegacyNsEnforcement()), capture_runtime_settings_(kRuntimeSettingQueueSize), render_runtime_settings_(kRuntimeSettingQueueSize), capture_runtime_settings_enqueuer_(&capture_runtime_settings_), render_runtime_settings_enqueuer_(&render_runtime_settings_), echo_control_factory_(std::move(echo_control_factory)), submodule_states_(!!capture_post_processor, !!render_pre_processor, !!capture_analyzer), submodules_(std::move(capture_post_processor), std::move(render_pre_processor), std::move(echo_detector), std::move(capture_analyzer)), constants_(config.Get<ExperimentalAgc>().startup_min_volume, config.Get<ExperimentalAgc>().clipped_level_min, #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) /* enabled= */ false, /* enabled_agc2_level_estimator= */ false, /* digital_adaptive_disabled= */ false, #else config.Get<ExperimentalAgc>().enabled, config.Get<ExperimentalAgc>().enabled_agc2_level_estimator, config.Get<ExperimentalAgc>().digital_adaptive_disabled, #endif !field_trial::IsEnabled( "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"), !field_trial::IsEnabled( "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")), #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) capture_(false), #else capture_(config.Get<ExperimentalNs>().enabled), #endif capture_nonlocked_() { RTC_LOG(LS_INFO) << "Injected APM submodules:" << "\nEcho control factory: " << !!echo_control_factory_ << "\nEcho detector: " << !!submodules_.echo_detector << "\nCapture analyzer: " << !!submodules_.capture_analyzer << "\nCapture post processor: " << !!submodules_.capture_post_processor << "\nRender pre processor: " << !!submodules_.render_pre_processor; // Mark Echo Controller enabled if a factory is injected. capture_nonlocked_.echo_controller_enabled = static_cast<bool>(echo_control_factory_); submodules_.gain_control.reset(new GainControlImpl()); // If no echo detector is injected, use the ResidualEchoDetector. if (!submodules_.echo_detector) { submodules_.echo_detector = new rtc::RefCountedObject<ResidualEchoDetector>(); } // TODO(alessiob): Move the injected gain controller once injection is // implemented. submodules_.gain_controller2.reset(new GainController2()); SetExtraOptions(config); } AudioProcessingImpl::~AudioProcessingImpl() = default; int AudioProcessingImpl::Initialize() { // Run in a single-threaded manner during initialization. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); return InitializeLocked(); } int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz, int capture_output_sample_rate_hz, int render_input_sample_rate_hz, ChannelLayout capture_input_layout, ChannelLayout capture_output_layout, ChannelLayout render_input_layout) { const ProcessingConfig processing_config = { {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout), LayoutHasKeyboard(capture_input_layout)}, {capture_output_sample_rate_hz, ChannelsFromLayout(capture_output_layout), LayoutHasKeyboard(capture_output_layout)}, {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout), LayoutHasKeyboard(render_input_layout)}, {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout), LayoutHasKeyboard(render_input_layout)}}}; return Initialize(processing_config); } int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) { // Run in a single-threaded manner during initialization. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); return InitializeLocked(processing_config); } int AudioProcessingImpl::MaybeInitializeRender( const ProcessingConfig& processing_config) { // Called from both threads. Thread check is therefore not possible. if (processing_config == formats_.api_format) { return kNoError; } rtc::CritScope cs_capture(&crit_capture_); return InitializeLocked(processing_config); } int AudioProcessingImpl::InitializeLocked() { UpdateActiveSubmoduleStates(); const int render_audiobuffer_sample_rate_hz = formats_.api_format.reverse_output_stream().num_frames() == 0 ? formats_.render_processing_format.sample_rate_hz() : formats_.api_format.reverse_output_stream().sample_rate_hz(); if (formats_.api_format.reverse_input_stream().num_channels() > 0) { render_.render_audio.reset(new AudioBuffer( formats_.api_format.reverse_input_stream().sample_rate_hz(), formats_.api_format.reverse_input_stream().num_channels(), formats_.render_processing_format.sample_rate_hz(), formats_.render_processing_format.num_channels(), render_audiobuffer_sample_rate_hz, formats_.render_processing_format.num_channels())); if (formats_.api_format.reverse_input_stream() != formats_.api_format.reverse_output_stream()) { render_.render_converter = AudioConverter::Create( formats_.api_format.reverse_input_stream().num_channels(), formats_.api_format.reverse_input_stream().num_frames(), formats_.api_format.reverse_output_stream().num_channels(), formats_.api_format.reverse_output_stream().num_frames()); } else { render_.render_converter.reset(nullptr); } } else { render_.render_audio.reset(nullptr); render_.render_converter.reset(nullptr); } capture_.capture_audio.reset(new AudioBuffer( formats_.api_format.input_stream().sample_rate_hz(), formats_.api_format.input_stream().num_channels(), capture_nonlocked_.capture_processing_format.sample_rate_hz(), formats_.api_format.output_stream().num_channels(), formats_.api_format.output_stream().sample_rate_hz(), formats_.api_format.output_stream().num_channels())); if (capture_nonlocked_.capture_processing_format.sample_rate_hz() < formats_.api_format.output_stream().sample_rate_hz() && formats_.api_format.output_stream().sample_rate_hz() == 48000) { capture_.capture_fullband_audio.reset( new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(), formats_.api_format.input_stream().num_channels(), formats_.api_format.output_stream().sample_rate_hz(), formats_.api_format.output_stream().num_channels(), formats_.api_format.output_stream().sample_rate_hz(), formats_.api_format.output_stream().num_channels())); } else { capture_.capture_fullband_audio.reset(); } AllocateRenderQueue(); submodules_.gain_control->Initialize(num_proc_channels(), proc_sample_rate_hz()); if (constants_.use_experimental_agc) { if (!submodules_.agc_manager.get() || submodules_.agc_manager->num_channels() != static_cast<int>(num_proc_channels()) || submodules_.agc_manager->sample_rate_hz() != capture_nonlocked_.split_rate) { submodules_.agc_manager.reset(new AgcManagerDirect( num_proc_channels(), constants_.agc_startup_min_volume, constants_.agc_clipped_level_min, constants_.use_experimental_agc_agc2_level_estimation, constants_.use_experimental_agc_agc2_digital_adaptive, capture_nonlocked_.split_rate)); } submodules_.agc_manager->Initialize(); submodules_.agc_manager->SetupDigitalGainControl( submodules_.gain_control.get()); submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted); } InitializeTransient(); InitializeHighPassFilter(); InitializeVoiceDetector(); InitializeResidualEchoDetector(); InitializeEchoController(); InitializeGainController2(); InitializeNoiseSuppressor(); InitializeAnalyzer(); InitializePostProcessor(); InitializePreProcessor(); if (aec_dump_) { aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis()); } return kNoError; } int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) { UpdateActiveSubmoduleStates(); for (const auto& stream : config.streams) { if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) { return kBadSampleRateError; } } const size_t num_in_channels = config.input_stream().num_channels(); const size_t num_out_channels = config.output_stream().num_channels(); // Need at least one input channel. // Need either one output channel or as many outputs as there are inputs. if (num_in_channels == 0 || !(num_out_channels == 1 || num_out_channels == num_in_channels)) { return kBadNumberChannelsError; } formats_.api_format = config; // Choose maximum rate to use for the split filtering. RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 || config_.pipeline.maximum_internal_processing_rate == 32000); int max_splitting_rate = 48000; if (config_.pipeline.maximum_internal_processing_rate == 32000) { max_splitting_rate = config_.pipeline.maximum_internal_processing_rate; } int capture_processing_rate = SuitableProcessRate( std::min(formats_.api_format.input_stream().sample_rate_hz(), formats_.api_format.output_stream().sample_rate_hz()), max_splitting_rate, submodule_states_.CaptureMultiBandSubModulesActive() || submodule_states_.RenderMultiBandSubModulesActive()); RTC_DCHECK_NE(8000, capture_processing_rate); capture_nonlocked_.capture_processing_format = StreamConfig(capture_processing_rate); int render_processing_rate; if (!capture_nonlocked_.echo_controller_enabled) { render_processing_rate = SuitableProcessRate( std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(), formats_.api_format.reverse_output_stream().sample_rate_hz()), max_splitting_rate, submodule_states_.CaptureMultiBandSubModulesActive() || submodule_states_.RenderMultiBandSubModulesActive()); } else { render_processing_rate = capture_processing_rate; } // If the forward sample rate is 8 kHz, the render stream is also processed // at this rate. if (capture_nonlocked_.capture_processing_format.sample_rate_hz() == kSampleRate8kHz) { render_processing_rate = kSampleRate8kHz; } else { render_processing_rate = std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz)); } RTC_DCHECK_NE(8000, render_processing_rate); if (submodule_states_.RenderMultiBandSubModulesActive()) { // By default, downmix the render stream to mono for analysis. This has been // demonstrated to work well for AEC in most practical scenarios. const bool experimental_multi_channel_render = config_.pipeline.experimental_multi_channel && constants_.experimental_multi_channel_render_support; int render_processing_num_channels = experimental_multi_channel_render ? formats_.api_format.reverse_input_stream().num_channels() : 1; formats_.render_processing_format = StreamConfig(render_processing_rate, render_processing_num_channels); } else { formats_.render_processing_format = StreamConfig( formats_.api_format.reverse_input_stream().sample_rate_hz(), formats_.api_format.reverse_input_stream().num_channels()); } if (capture_nonlocked_.capture_processing_format.sample_rate_hz() == kSampleRate32kHz || capture_nonlocked_.capture_processing_format.sample_rate_hz() == kSampleRate48kHz) { capture_nonlocked_.split_rate = kSampleRate16kHz; } else { capture_nonlocked_.split_rate = capture_nonlocked_.capture_processing_format.sample_rate_hz(); } return InitializeLocked(); } void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) { RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString(); // Run in a single-threaded manner when applying the settings. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); const bool pipeline_config_changed = config_.pipeline.experimental_multi_channel != config.pipeline.experimental_multi_channel; const bool aec_config_changed = config_.echo_canceller.enabled != config.echo_canceller.enabled || config_.echo_canceller.use_legacy_aec != config.echo_canceller.use_legacy_aec || config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode || (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec && config_.echo_canceller.legacy_moderate_suppression_level != config.echo_canceller.legacy_moderate_suppression_level); const bool agc1_config_changed = config_.gain_controller1.enabled != config.gain_controller1.enabled || config_.gain_controller1.mode != config.gain_controller1.mode || config_.gain_controller1.target_level_dbfs != config.gain_controller1.target_level_dbfs || config_.gain_controller1.compression_gain_db != config.gain_controller1.compression_gain_db || config_.gain_controller1.enable_limiter != config.gain_controller1.enable_limiter || config_.gain_controller1.analog_level_minimum != config.gain_controller1.analog_level_minimum || config_.gain_controller1.analog_level_maximum != config.gain_controller1.analog_level_maximum; const bool voice_detection_config_changed = config_.voice_detection.enabled != config.voice_detection.enabled; const bool ns_config_changed = config_.noise_suppression.enabled != config.noise_suppression.enabled || config_.noise_suppression.level != config.noise_suppression.level; config_ = config; if (aec_config_changed) { InitializeEchoController(); } if (ns_config_changed) { InitializeNoiseSuppressor(); } InitializeHighPassFilter(); if (agc1_config_changed) { ApplyAgc1Config(config_.gain_controller1); } const bool config_ok = GainController2::Validate(config_.gain_controller2); if (!config_ok) { RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n" "Gain Controller 2: " << GainController2::ToString(config_.gain_controller2) << "\nReverting to default parameter set"; config_.gain_controller2 = AudioProcessing::Config::GainController2(); } InitializeGainController2(); InitializePreAmplifier(); submodules_.gain_controller2->ApplyConfig(config_.gain_controller2); if (config_.level_estimation.enabled && !submodules_.output_level_estimator) { submodules_.output_level_estimator = std::make_unique<LevelEstimator>(); } if (voice_detection_config_changed) { InitializeVoiceDetector(); } // Reinitialization must happen after all submodule configuration to avoid // additional reinitializations on the next capture / render processing call. if (pipeline_config_changed) { InitializeLocked(formats_.api_format); } } void AudioProcessingImpl::ApplyAgc1Config( const Config::GainController1& config) { int error = submodules_.gain_control->Enable(config.enabled); RTC_DCHECK_EQ(kNoError, error); if (!submodules_.agc_manager) { error = submodules_.gain_control->set_mode( Agc1ConfigModeToInterfaceMode(config.mode)); RTC_DCHECK_EQ(kNoError, error); error = submodules_.gain_control->set_target_level_dbfs( config.target_level_dbfs); RTC_DCHECK_EQ(kNoError, error); error = submodules_.gain_control->set_compression_gain_db( config.compression_gain_db); RTC_DCHECK_EQ(kNoError, error); error = submodules_.gain_control->enable_limiter(config.enable_limiter); RTC_DCHECK_EQ(kNoError, error); error = submodules_.gain_control->set_analog_level_limits( config.analog_level_minimum, config.analog_level_maximum); RTC_DCHECK_EQ(kNoError, error); } } void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) { // Run in a single-threaded manner when setting the extra options. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); capture_nonlocked_.use_aec2_extended_filter = config.Get<ExtendedFilter>().enabled; capture_nonlocked_.use_aec2_delay_agnostic = config.Get<DelayAgnostic>().enabled; capture_nonlocked_.use_aec2_refined_adaptive_filter = config.Get<RefinedAdaptiveFilter>().enabled; if (capture_.transient_suppressor_enabled != config.Get<ExperimentalNs>().enabled) { capture_.transient_suppressor_enabled = config.Get<ExperimentalNs>().enabled; InitializeTransient(); } } int AudioProcessingImpl::proc_sample_rate_hz() const { // Used as callback from submodules, hence locking is not allowed. return capture_nonlocked_.capture_processing_format.sample_rate_hz(); } int AudioProcessingImpl::proc_fullband_sample_rate_hz() const { return capture_.capture_fullband_audio ? capture_.capture_fullband_audio->num_frames() * 100 : capture_nonlocked_.capture_processing_format.sample_rate_hz(); } int AudioProcessingImpl::proc_split_sample_rate_hz() const { // Used as callback from submodules, hence locking is not allowed. return capture_nonlocked_.split_rate; } size_t AudioProcessingImpl::num_reverse_channels() const { // Used as callback from submodules, hence locking is not allowed. return formats_.render_processing_format.num_channels(); } size_t AudioProcessingImpl::num_input_channels() const { // Used as callback from submodules, hence locking is not allowed. return formats_.api_format.input_stream().num_channels(); } size_t AudioProcessingImpl::num_proc_channels() const { // Used as callback from submodules, hence locking is not allowed. const bool experimental_multi_channel_capture = config_.pipeline.experimental_multi_channel && constants_.experimental_multi_channel_capture_support; if (capture_nonlocked_.echo_controller_enabled && !experimental_multi_channel_capture) { return 1; } return num_output_channels(); } size_t AudioProcessingImpl::num_output_channels() const { // Used as callback from submodules, hence locking is not allowed. return formats_.api_format.output_stream().num_channels(); } void AudioProcessingImpl::set_output_will_be_muted(bool muted) { rtc::CritScope cs(&crit_capture_); capture_.output_will_be_muted = muted; if (submodules_.agc_manager.get()) { submodules_.agc_manager->SetCaptureMuted(capture_.output_will_be_muted); } } void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) { switch (setting.type()) { case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting: case RuntimeSetting::Type::kPlayoutAudioDeviceChange: render_runtime_settings_enqueuer_.Enqueue(setting); return; case RuntimeSetting::Type::kCapturePreGain: case RuntimeSetting::Type::kCaptureCompressionGain: case RuntimeSetting::Type::kCaptureFixedPostGain: capture_runtime_settings_enqueuer_.Enqueue(setting); return; case RuntimeSetting::Type::kPlayoutVolumeChange: capture_runtime_settings_enqueuer_.Enqueue(setting); render_runtime_settings_enqueuer_.Enqueue(setting); return; case RuntimeSetting::Type::kNotSpecified: RTC_NOTREACHED(); return; } // The language allows the enum to have a non-enumerator // value. Check that this doesn't happen. RTC_NOTREACHED(); } AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer( SwapQueue<RuntimeSetting>* runtime_settings) : runtime_settings_(*runtime_settings) { RTC_DCHECK(runtime_settings); } AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() = default; void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue( RuntimeSetting setting) { size_t remaining_attempts = 10; while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) { RuntimeSetting setting_to_discard; if (runtime_settings_.Remove(&setting_to_discard)) RTC_LOG(LS_ERROR) << "The runtime settings queue is full. Oldest setting discarded."; } if (remaining_attempts == 0) RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting."; } int AudioProcessingImpl::ProcessStream(const float* const* src, const StreamConfig& input_config, const StreamConfig& output_config, float* const* dest) { TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig"); ProcessingConfig processing_config; bool reinitialization_required = false; { // Acquire the capture lock in order to safely call the function // that retrieves the render side data. This function accesses apm // getters that need the capture lock held when being called. rtc::CritScope cs_capture(&crit_capture_); EmptyQueuedRenderAudio(); if (!src || !dest) { return kNullPointerError; } processing_config = formats_.api_format; reinitialization_required = UpdateActiveSubmoduleStates(); } if (processing_config.input_stream() != input_config) { processing_config.input_stream() = input_config; reinitialization_required = true; } if (processing_config.output_stream() != output_config) { processing_config.output_stream() = output_config; reinitialization_required = true; } if (reinitialization_required) { // Reinitialize. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); RETURN_ON_ERR(InitializeLocked(processing_config)); } rtc::CritScope cs_capture(&crit_capture_); RTC_DCHECK_EQ(processing_config.input_stream().num_frames(), formats_.api_format.input_stream().num_frames()); if (aec_dump_) { RecordUnprocessedCaptureStream(src); } capture_.keyboard_info.Extract(src, formats_.api_format.input_stream()); capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream()); if (capture_.capture_fullband_audio) { capture_.capture_fullband_audio->CopyFrom( src, formats_.api_format.input_stream()); } RETURN_ON_ERR(ProcessCaptureStreamLocked()); if (capture_.capture_fullband_audio) { capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(), dest); } else { capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest); } if (aec_dump_) { RecordProcessedCaptureStream(dest); } return kNoError; } void AudioProcessingImpl::HandleCaptureRuntimeSettings() { RuntimeSetting setting; while (capture_runtime_settings_.Remove(&setting)) { if (aec_dump_) { aec_dump_->WriteRuntimeSetting(setting); } switch (setting.type()) { case RuntimeSetting::Type::kCapturePreGain: if (config_.pre_amplifier.enabled) { float value; setting.GetFloat(&value); config_.pre_amplifier.fixed_gain_factor = value; submodules_.pre_amplifier->SetGainFactor(value); } // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump. break; case RuntimeSetting::Type::kCaptureCompressionGain: { if (!submodules_.agc_manager) { float value; setting.GetFloat(&value); int int_value = static_cast<int>(value + .5f); config_.gain_controller1.compression_gain_db = int_value; int error = submodules_.gain_control->set_compression_gain_db(int_value); RTC_DCHECK_EQ(kNoError, error); } break; } case RuntimeSetting::Type::kCaptureFixedPostGain: { if (config_.gain_controller2.enabled) { float value; setting.GetFloat(&value); config_.gain_controller2.fixed_digital.gain_db = value; submodules_.gain_controller2->ApplyConfig(config_.gain_controller2); } break; } case RuntimeSetting::Type::kPlayoutVolumeChange: { int value; setting.GetInt(&value); capture_.playout_volume = value; break; } case RuntimeSetting::Type::kPlayoutAudioDeviceChange: RTC_NOTREACHED(); break; case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting: RTC_NOTREACHED(); break; case RuntimeSetting::Type::kNotSpecified: RTC_NOTREACHED(); break; } } } void AudioProcessingImpl::HandleRenderRuntimeSettings() { RuntimeSetting setting; while (render_runtime_settings_.Remove(&setting)) { if (aec_dump_) { aec_dump_->WriteRuntimeSetting(setting); } switch (setting.type()) { case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting: if (submodules_.render_pre_processor) { submodules_.render_pre_processor->SetRuntimeSetting(setting); } break; case RuntimeSetting::Type::kCapturePreGain: // fall-through case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through case RuntimeSetting::Type::kNotSpecified: RTC_NOTREACHED(); break; } } } void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) { RTC_DCHECK_GE(160, audio->num_frames_per_band()); // Insert the samples into the queue. if (submodules_.echo_cancellation) { RTC_DCHECK(aec_render_signal_queue_); EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(), num_reverse_channels(), &aec_render_queue_buffer_); if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) { // The data queue is full and needs to be emptied. EmptyQueuedRenderAudio(); // Retry the insert (should always work). bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_); RTC_DCHECK(result); } } if (submodules_.echo_control_mobile) { EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(), num_reverse_channels(), &aecm_render_queue_buffer_); RTC_DCHECK(aecm_render_signal_queue_); // Insert the samples into the queue. if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) { // The data queue is full and needs to be emptied. EmptyQueuedRenderAudio(); // Retry the insert (should always work). bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_); RTC_DCHECK(result); } } if (!submodules_.agc_manager) { GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_); // Insert the samples into the queue. if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) { // The data queue is full and needs to be emptied. EmptyQueuedRenderAudio(); // Retry the insert (should always work). bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_); RTC_DCHECK(result); } } } void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) { ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_); // Insert the samples into the queue. if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) { // The data queue is full and needs to be emptied. EmptyQueuedRenderAudio(); // Retry the insert (should always work). bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_); RTC_DCHECK(result); } } void AudioProcessingImpl::AllocateRenderQueue() { const size_t new_agc_render_queue_element_max_size = std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand); const size_t new_red_render_queue_element_max_size = std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame); // Reallocate the queues if the queue item sizes are too small to fit the // data to put in the queues. if (agc_render_queue_element_max_size_ < new_agc_render_queue_element_max_size) { agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size; std::vector<int16_t> template_queue_element( agc_render_queue_element_max_size_); agc_render_signal_queue_.reset( new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>( kMaxNumFramesToBuffer, template_queue_element, RenderQueueItemVerifier<int16_t>( agc_render_queue_element_max_size_))); agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_); agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_); } else { agc_render_signal_queue_->Clear(); } if (red_render_queue_element_max_size_ < new_red_render_queue_element_max_size) { red_render_queue_element_max_size_ = new_red_render_queue_element_max_size; std::vector<float> template_queue_element( red_render_queue_element_max_size_); red_render_signal_queue_.reset( new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>( kMaxNumFramesToBuffer, template_queue_element, RenderQueueItemVerifier<float>( red_render_queue_element_max_size_))); red_render_queue_buffer_.resize(red_render_queue_element_max_size_); red_capture_queue_buffer_.resize(red_render_queue_element_max_size_); } else { red_render_signal_queue_->Clear(); } } void AudioProcessingImpl::EmptyQueuedRenderAudio() { rtc::CritScope cs_capture(&crit_capture_); if (submodules_.echo_cancellation) { RTC_DCHECK(aec_render_signal_queue_); while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) { submodules_.echo_cancellation->ProcessRenderAudio( aec_capture_queue_buffer_); } } if (submodules_.echo_control_mobile) { RTC_DCHECK(aecm_render_signal_queue_); while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) { submodules_.echo_control_mobile->ProcessRenderAudio( aecm_capture_queue_buffer_); } } while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) { submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_); } while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) { RTC_DCHECK(submodules_.echo_detector); submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_); } } int AudioProcessingImpl::ProcessStream(AudioFrame* frame) { TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame"); { // Acquire the capture lock in order to safely call the function // that retrieves the render side data. This function accesses APM // getters that need the capture lock held when being called. rtc::CritScope cs_capture(&crit_capture_); EmptyQueuedRenderAudio(); } if (!frame) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } ProcessingConfig processing_config; bool reinitialization_required = false; { // Aquire lock for the access of api_format. // The lock is released immediately due to the conditional // reinitialization. rtc::CritScope cs_capture(&crit_capture_); // TODO(ajm): The input and output rates and channels are currently // constrained to be identical in the int16 interface. processing_config = formats_.api_format; reinitialization_required = UpdateActiveSubmoduleStates(); } reinitialization_required = reinitialization_required || processing_config.input_stream().sample_rate_hz() != frame->sample_rate_hz_ || processing_config.input_stream().num_channels() != frame->num_channels_ || processing_config.output_stream().sample_rate_hz() != frame->sample_rate_hz_ || processing_config.output_stream().num_channels() != frame->num_channels_; if (reinitialization_required) { processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_); processing_config.input_stream().set_num_channels(frame->num_channels_); processing_config.output_stream().set_sample_rate_hz( frame->sample_rate_hz_); processing_config.output_stream().set_num_channels(frame->num_channels_); // Reinitialize. rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); RETURN_ON_ERR(InitializeLocked(processing_config)); } rtc::CritScope cs_capture(&crit_capture_); if (frame->samples_per_channel_ != formats_.api_format.input_stream().num_frames()) { return kBadDataLengthError; } if (aec_dump_) { RecordUnprocessedCaptureStream(*frame); } capture_.capture_audio->CopyFrom(frame); if (capture_.capture_fullband_audio) { capture_.capture_fullband_audio->CopyFrom(frame); } RETURN_ON_ERR(ProcessCaptureStreamLocked()); if (submodule_states_.CaptureMultiBandProcessingPresent() || submodule_states_.CaptureFullBandProcessingActive()) { if (capture_.capture_fullband_audio) { capture_.capture_fullband_audio->CopyTo(frame); } else { capture_.capture_audio->CopyTo(frame); } } if (capture_.stats.voice_detected) { frame->vad_activity_ = *capture_.stats.voice_detected ? AudioFrame::kVadActive : AudioFrame::kVadPassive; } if (aec_dump_) { RecordProcessedCaptureStream(*frame); } return kNoError; } int AudioProcessingImpl::ProcessCaptureStreamLocked() { HandleCaptureRuntimeSettings(); // Ensure that not both the AEC and AECM are active at the same time. // TODO(peah): Simplify once the public API Enable functions for these // are moved to APM. RTC_DCHECK_LE(!!submodules_.echo_controller + !!submodules_.echo_cancellation + !!submodules_.echo_control_mobile, 1); AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity. if (submodules_.pre_amplifier) { submodules_.pre_amplifier->ApplyGain(AudioFrameView<float>( capture_buffer->channels(), capture_buffer->num_channels(), capture_buffer->num_frames())); } capture_input_rms_.Analyze(rtc::ArrayView<const float>( capture_buffer->channels_const()[0], capture_nonlocked_.capture_processing_format.num_frames())); const bool log_rms = ++capture_rms_interval_counter_ >= 1000; if (log_rms) { capture_rms_interval_counter_ = 0; RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak(); RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms", levels.average, 1, RmsLevel::kMinLevelDb, 64); RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms", levels.peak, 1, RmsLevel::kMinLevelDb, 64); } if (submodules_.echo_controller) { // Detect and flag any change in the analog gain. int analog_mic_level = recommended_stream_analog_level(); capture_.echo_path_gain_change = capture_.prev_analog_mic_level != analog_mic_level && capture_.prev_analog_mic_level != -1; capture_.prev_analog_mic_level = analog_mic_level; // Detect and flag any change in the pre-amplifier gain. if (submodules_.pre_amplifier) { float pre_amp_gain = submodules_.pre_amplifier->GetGainFactor(); capture_.echo_path_gain_change = capture_.echo_path_gain_change || (capture_.prev_pre_amp_gain != pre_amp_gain && capture_.prev_pre_amp_gain >= 0.f); capture_.prev_pre_amp_gain = pre_amp_gain; } // Detect volume change. capture_.echo_path_gain_change = capture_.echo_path_gain_change || (capture_.prev_playout_volume != capture_.playout_volume && capture_.prev_playout_volume >= 0); capture_.prev_playout_volume = capture_.playout_volume; submodules_.echo_controller->AnalyzeCapture(capture_buffer); } if (constants_.use_experimental_agc && submodules_.gain_control->is_enabled()) { submodules_.agc_manager->AnalyzePreProcess(capture_buffer); } if (submodule_states_.CaptureMultiBandSubModulesActive() && SampleRateSupportsMultiBand( capture_nonlocked_.capture_processing_format.sample_rate_hz())) { capture_buffer->SplitIntoFrequencyBands(); } const bool experimental_multi_channel_capture = config_.pipeline.experimental_multi_channel && constants_.experimental_multi_channel_capture_support; if (submodules_.echo_controller && !experimental_multi_channel_capture) { // Force down-mixing of the number of channels after the detection of // capture signal saturation. // TODO(peah): Look into ensuring that this kind of tampering with the // AudioBuffer functionality should not be needed. capture_buffer->set_num_channels(1); } if (submodules_.high_pass_filter) { submodules_.high_pass_filter->Process(capture_buffer); } RETURN_ON_ERR(submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer)); RTC_DCHECK( !(submodules_.legacy_noise_suppressor && submodules_.noise_suppressor)); if (submodules_.noise_suppressor) { submodules_.noise_suppressor->Analyze(*capture_buffer); } else if (submodules_.legacy_noise_suppressor) { submodules_.legacy_noise_suppressor->AnalyzeCaptureAudio(capture_buffer); } if (submodules_.echo_control_mobile) { // Ensure that the stream delay was set before the call to the // AECM ProcessCaptureAudio function. if (!was_stream_delay_set()) { return AudioProcessing::kStreamParameterNotSetError; } if (submodules_.noise_suppressor) { submodules_.noise_suppressor->Process(capture_buffer); } else if (submodules_.legacy_noise_suppressor) { submodules_.echo_control_mobile->CopyLowPassReference(capture_buffer); submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer); } RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio( capture_buffer, stream_delay_ms())); } else { if (submodules_.echo_controller) { data_dumper_->DumpRaw("stream_delay", stream_delay_ms()); if (was_stream_delay_set()) { submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms()); } AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get(); submodules_.echo_controller->ProcessCapture( capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change); } else if (submodules_.echo_cancellation) { // Ensure that the stream delay was set before the call to the // AEC ProcessCaptureAudio function. if (!was_stream_delay_set()) { return AudioProcessing::kStreamParameterNotSetError; } RETURN_ON_ERR(submodules_.echo_cancellation->ProcessCaptureAudio( capture_buffer, stream_delay_ms())); } if (submodules_.noise_suppressor) { submodules_.noise_suppressor->Process(capture_buffer); } else if (submodules_.legacy_noise_suppressor) { submodules_.legacy_noise_suppressor->ProcessCaptureAudio(capture_buffer); } } if (config_.voice_detection.enabled) { capture_.stats.voice_detected = submodules_.voice_detector->ProcessCaptureAudio(capture_buffer); } else { capture_.stats.voice_detected = absl::nullopt; } if (constants_.use_experimental_agc && submodules_.gain_control->is_enabled()) { submodules_.agc_manager->Process(capture_buffer); absl::optional<int> new_digital_gain = submodules_.agc_manager->GetDigitalComressionGain(); if (new_digital_gain) { submodules_.gain_control->set_compression_gain_db(*new_digital_gain); } } // TODO(peah): Add reporting from AEC3 whether there is echo. RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio( capture_buffer, submodules_.echo_cancellation && submodules_.echo_cancellation->stream_has_echo())); if (submodule_states_.CaptureMultiBandProcessingPresent() && SampleRateSupportsMultiBand( capture_nonlocked_.capture_processing_format.sample_rate_hz())) { capture_buffer->MergeFrequencyBands(); } if (capture_.capture_fullband_audio) { const auto& ec = submodules_.echo_controller; bool ec_active = ec ? ec->ActiveProcessing() : false; // Only update the fullband buffer if the multiband processing has changed // the signal. Keep the original signal otherwise. if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) { capture_buffer->CopyTo(capture_.capture_fullband_audio.get()); } capture_buffer = capture_.capture_fullband_audio.get(); } if (config_.residual_echo_detector.enabled) { RTC_DCHECK(submodules_.echo_detector); submodules_.echo_detector->AnalyzeCaptureAudio(rtc::ArrayView<const float>( capture_buffer->channels()[0], capture_buffer->num_frames())); } // TODO(aluebs): Investigate if the transient suppression placement should be // before or after the AGC. if (capture_.transient_suppressor_enabled) { float voice_probability = submodules_.agc_manager.get() ? submodules_.agc_manager->voice_probability() : 1.f; submodules_.transient_suppressor->Suppress( capture_buffer->channels()[0], capture_buffer->num_frames(), capture_buffer->num_channels(), capture_buffer->split_bands_const(0)[kBand0To8kHz], capture_buffer->num_frames_per_band(), capture_.keyboard_info.keyboard_data, capture_.keyboard_info.num_keyboard_frames, voice_probability, capture_.key_pressed); } // Experimental APM sub-module that analyzes |capture_buffer|. if (submodules_.capture_analyzer) { submodules_.capture_analyzer->Analyze(capture_buffer); } if (config_.gain_controller2.enabled) { submodules_.gain_controller2->NotifyAnalogLevel( recommended_stream_analog_level()); submodules_.gain_controller2->Process(capture_buffer); } if (submodules_.capture_post_processor) { submodules_.capture_post_processor->Process(capture_buffer); } // The level estimator operates on the recombined data. if (config_.level_estimation.enabled) { submodules_.output_level_estimator->ProcessStream(*capture_buffer); capture_.stats.output_rms_dbfs = submodules_.output_level_estimator->RMS(); } else { capture_.stats.output_rms_dbfs = absl::nullopt; } capture_output_rms_.Analyze(rtc::ArrayView<const float>( capture_buffer->channels_const()[0], capture_nonlocked_.capture_processing_format.num_frames())); if (log_rms) { RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak(); RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1, RmsLevel::kMinLevelDb, 64); RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms", levels.peak, 1, RmsLevel::kMinLevelDb, 64); } if (submodules_.agc_manager) { int level = recommended_stream_analog_level(); data_dumper_->DumpRaw("experimental_gain_control_stream_analog_level", 1, &level); } capture_.was_stream_delay_set = false; return kNoError; } int AudioProcessingImpl::AnalyzeReverseStream( const float* const* data, const StreamConfig& reverse_config) { TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig"); rtc::CritScope cs(&crit_render_); return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config); } int AudioProcessingImpl::ProcessReverseStream(const float* const* src, const StreamConfig& input_config, const StreamConfig& output_config, float* const* dest) { TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig"); rtc::CritScope cs(&crit_render_); RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config)); if (submodule_states_.RenderMultiBandProcessingActive() || submodule_states_.RenderFullBandProcessingActive()) { render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(), dest); } else if (formats_.api_format.reverse_input_stream() != formats_.api_format.reverse_output_stream()) { render_.render_converter->Convert(src, input_config.num_samples(), dest, output_config.num_samples()); } else { CopyAudioIfNeeded(src, input_config.num_frames(), input_config.num_channels(), dest); } return kNoError; } int AudioProcessingImpl::AnalyzeReverseStreamLocked( const float* const* src, const StreamConfig& input_config, const StreamConfig& output_config) { if (src == nullptr) { return kNullPointerError; } if (input_config.num_channels() == 0) { return kBadNumberChannelsError; } ProcessingConfig processing_config = formats_.api_format; processing_config.reverse_input_stream() = input_config; processing_config.reverse_output_stream() = output_config; RETURN_ON_ERR(MaybeInitializeRender(processing_config)); RTC_DCHECK_EQ(input_config.num_frames(), formats_.api_format.reverse_input_stream().num_frames()); if (aec_dump_) { const size_t channel_size = formats_.api_format.reverse_input_stream().num_frames(); const size_t num_channels = formats_.api_format.reverse_input_stream().num_channels(); aec_dump_->WriteRenderStreamMessage( AudioFrameView<const float>(src, num_channels, channel_size)); } render_.render_audio->CopyFrom(src, formats_.api_format.reverse_input_stream()); return ProcessRenderStreamLocked(); } int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) { TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame"); rtc::CritScope cs(&crit_render_); if (frame == nullptr) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } if (frame->num_channels_ <= 0) { return kBadNumberChannelsError; } ProcessingConfig processing_config = formats_.api_format; processing_config.reverse_input_stream().set_sample_rate_hz( frame->sample_rate_hz_); processing_config.reverse_input_stream().set_num_channels( frame->num_channels_); processing_config.reverse_output_stream().set_sample_rate_hz( frame->sample_rate_hz_); processing_config.reverse_output_stream().set_num_channels( frame->num_channels_); RETURN_ON_ERR(MaybeInitializeRender(processing_config)); if (frame->samples_per_channel_ != formats_.api_format.reverse_input_stream().num_frames()) { return kBadDataLengthError; } if (aec_dump_) { aec_dump_->WriteRenderStreamMessage(*frame); } render_.render_audio->CopyFrom(frame); RETURN_ON_ERR(ProcessRenderStreamLocked()); if (submodule_states_.RenderMultiBandProcessingActive() || submodule_states_.RenderFullBandProcessingActive()) { render_.render_audio->CopyTo(frame); } return kNoError; } int AudioProcessingImpl::ProcessRenderStreamLocked() { AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity. HandleRenderRuntimeSettings(); if (submodules_.render_pre_processor) { submodules_.render_pre_processor->Process(render_buffer); } QueueNonbandedRenderAudio(render_buffer); if (submodule_states_.RenderMultiBandSubModulesActive() && SampleRateSupportsMultiBand( formats_.render_processing_format.sample_rate_hz())) { render_buffer->SplitIntoFrequencyBands(); } if (submodule_states_.RenderMultiBandSubModulesActive()) { QueueBandedRenderAudio(render_buffer); } // TODO(peah): Perform the queuing inside QueueRenderAudiuo(). if (submodules_.echo_controller) { submodules_.echo_controller->AnalyzeRender(render_buffer); } if (submodule_states_.RenderMultiBandProcessingActive() && SampleRateSupportsMultiBand( formats_.render_processing_format.sample_rate_hz())) { render_buffer->MergeFrequencyBands(); } return kNoError; } int AudioProcessingImpl::set_stream_delay_ms(int delay) { rtc::CritScope cs(&crit_capture_); Error retval = kNoError; capture_.was_stream_delay_set = true; delay += capture_.delay_offset_ms; if (delay < 0) { delay = 0; retval = kBadStreamParameterWarning; } // TODO(ajm): the max is rather arbitrarily chosen; investigate. if (delay > 500) { delay = 500; retval = kBadStreamParameterWarning; } capture_nonlocked_.stream_delay_ms = delay; return retval; } bool AudioProcessingImpl::GetLinearAecOutput( rtc::ArrayView<std::array<float, 160>> linear_output) const { rtc::CritScope cs(&crit_capture_); AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get(); RTC_DCHECK(linear_aec_buffer); if (linear_aec_buffer) { RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands()); RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels()); for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) { RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames()); rtc::ArrayView<const float> channel_view = rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch], linear_aec_buffer->num_frames()); std::copy(channel_view.begin(), channel_view.end(), linear_output[ch].begin()); } return true; } RTC_LOG(LS_ERROR) << "No linear AEC output available"; RTC_NOTREACHED(); return false; } int AudioProcessingImpl::stream_delay_ms() const { // Used as callback from submodules, hence locking is not allowed. return capture_nonlocked_.stream_delay_ms; } bool AudioProcessingImpl::was_stream_delay_set() const { // Used as callback from submodules, hence locking is not allowed. return capture_.was_stream_delay_set; } void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) { rtc::CritScope cs(&crit_capture_); capture_.key_pressed = key_pressed; } void AudioProcessingImpl::set_delay_offset_ms(int offset) { rtc::CritScope cs(&crit_capture_); capture_.delay_offset_ms = offset; } int AudioProcessingImpl::delay_offset_ms() const { rtc::CritScope cs(&crit_capture_); return capture_.delay_offset_ms; } void AudioProcessingImpl::set_stream_analog_level(int level) { rtc::CritScope cs_capture(&crit_capture_); if (submodules_.agc_manager) { submodules_.agc_manager->set_stream_analog_level(level); data_dumper_->DumpRaw("experimental_gain_control_set_stream_analog_level", 1, &level); } else { int error = submodules_.gain_control->set_stream_analog_level(level); RTC_DCHECK_EQ(kNoError, error); } } int AudioProcessingImpl::recommended_stream_analog_level() const { rtc::CritScope cs_capture(&crit_capture_); if (submodules_.agc_manager) { return submodules_.agc_manager->stream_analog_level(); } return submodules_.gain_control->stream_analog_level(); } void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) { RTC_DCHECK(aec_dump); rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); // The previously attached AecDump will be destroyed with the // 'aec_dump' parameter, which is after locks are released. aec_dump_.swap(aec_dump); WriteAecDumpConfigMessage(true); aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis()); } void AudioProcessingImpl::DetachAecDump() { // The d-tor of a task-queue based AecDump blocks until all pending // tasks are done. This construction avoids blocking while holding // the render and capture locks. std::unique_ptr<AecDump> aec_dump = nullptr; { rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); aec_dump = std::move(aec_dump_); } } void AudioProcessingImpl::AttachPlayoutAudioGenerator( std::unique_ptr<AudioGenerator> audio_generator) { // TODO(bugs.webrtc.org/8882) Stub. // Reset internal audio generator with audio_generator. } void AudioProcessingImpl::DetachPlayoutAudioGenerator() { // TODO(bugs.webrtc.org/8882) Stub. // Delete audio generator, if one is attached. } AudioProcessingStats AudioProcessingImpl::GetStatistics( bool has_remote_tracks) const { rtc::CritScope cs_capture(&crit_capture_); if (!has_remote_tracks) { return capture_.stats; } AudioProcessingStats stats = capture_.stats; EchoCancellationImpl::Metrics metrics; if (submodules_.echo_controller) { auto ec_metrics = submodules_.echo_controller->GetMetrics(); stats.echo_return_loss = ec_metrics.echo_return_loss; stats.echo_return_loss_enhancement = ec_metrics.echo_return_loss_enhancement; stats.delay_ms = ec_metrics.delay_ms; } if (config_.residual_echo_detector.enabled) { RTC_DCHECK(submodules_.echo_detector); auto ed_metrics = submodules_.echo_detector->GetMetrics(); stats.residual_echo_likelihood = ed_metrics.echo_likelihood; stats.residual_echo_likelihood_recent_max = ed_metrics.echo_likelihood_recent_max; } return stats; } void AudioProcessingImpl::MutateConfig( rtc::FunctionView<void(AudioProcessing::Config*)> mutator) { rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); mutator(&config_); ApplyConfig(config_); } AudioProcessing::Config AudioProcessingImpl::GetConfig() const { rtc::CritScope cs_render(&crit_render_); rtc::CritScope cs_capture(&crit_capture_); return config_; } bool AudioProcessingImpl::UpdateActiveSubmoduleStates() { return submodule_states_.Update( config_.high_pass_filter.enabled, !!submodules_.echo_cancellation, !!submodules_.echo_control_mobile, config_.residual_echo_detector.enabled, !!submodules_.legacy_noise_suppressor || !!submodules_.noise_suppressor, submodules_.gain_control->is_enabled(), config_.gain_controller2.enabled, config_.pre_amplifier.enabled, capture_nonlocked_.echo_controller_enabled, config_.voice_detection.enabled, capture_.transient_suppressor_enabled); } void AudioProcessingImpl::InitializeTransient() { if (capture_.transient_suppressor_enabled) { if (!submodules_.transient_suppressor.get()) { submodules_.transient_suppressor.reset(new TransientSuppressor()); } submodules_.transient_suppressor->Initialize(proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate, num_proc_channels()); } } void AudioProcessingImpl::InitializeHighPassFilter() { if (submodule_states_.HighPassFilteringRequired()) { submodules_.high_pass_filter.reset(new HighPassFilter(num_proc_channels())); } else { submodules_.high_pass_filter.reset(); } } void AudioProcessingImpl::InitializeVoiceDetector() { if (config_.voice_detection.enabled) { submodules_.voice_detector = std::make_unique<VoiceDetection>( proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood); } else { submodules_.voice_detector.reset(); } } void AudioProcessingImpl::InitializeEchoController() { bool use_echo_controller = echo_control_factory_ || (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode && !config_.echo_canceller.use_legacy_aec); if (use_echo_controller) { // Create and activate the echo controller. if (echo_control_factory_) { submodules_.echo_controller = echo_control_factory_->Create( proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels()); RTC_DCHECK(submodules_.echo_controller); } else { submodules_.echo_controller = std::make_unique<EchoCanceller3>( EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels()); } // Setup the storage for returning the linear AEC output. if (config_.echo_canceller.export_linear_aec_output) { constexpr int kLinearOutputRateHz = 16000; capture_.linear_aec_output = std::make_unique<AudioBuffer>( kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz, num_proc_channels()); } else { capture_.linear_aec_output.reset(); } capture_nonlocked_.echo_controller_enabled = true; submodules_.echo_cancellation.reset(); aec_render_signal_queue_.reset(); submodules_.echo_control_mobile.reset(); aecm_render_signal_queue_.reset(); return; } submodules_.echo_controller.reset(); capture_nonlocked_.echo_controller_enabled = false; capture_.linear_aec_output.reset(); if (!config_.echo_canceller.enabled) { submodules_.echo_cancellation.reset(); aec_render_signal_queue_.reset(); submodules_.echo_control_mobile.reset(); aecm_render_signal_queue_.reset(); return; } if (config_.echo_canceller.mobile_mode) { // Create and activate AECM. size_t max_element_size = std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand * EchoControlMobileImpl::NumCancellersRequired( num_output_channels(), num_reverse_channels())); std::vector<int16_t> template_queue_element(max_element_size); aecm_render_signal_queue_.reset( new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>( kMaxNumFramesToBuffer, template_queue_element, RenderQueueItemVerifier<int16_t>(max_element_size))); aecm_render_queue_buffer_.resize(max_element_size); aecm_capture_queue_buffer_.resize(max_element_size); submodules_.echo_control_mobile.reset(new EchoControlMobileImpl()); submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(), num_reverse_channels(), num_output_channels()); submodules_.echo_cancellation.reset(); aec_render_signal_queue_.reset(); return; } submodules_.echo_control_mobile.reset(); aecm_render_signal_queue_.reset(); // Create and activate AEC2. submodules_.echo_cancellation.reset(new EchoCancellationImpl()); submodules_.echo_cancellation->SetExtraOptions( capture_nonlocked_.use_aec2_extended_filter, capture_nonlocked_.use_aec2_delay_agnostic, capture_nonlocked_.use_aec2_refined_adaptive_filter); size_t element_max_size = std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand * EchoCancellationImpl::NumCancellersRequired( num_output_channels(), num_reverse_channels())); std::vector<float> template_queue_element(element_max_size); aec_render_signal_queue_.reset( new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>( kMaxNumFramesToBuffer, template_queue_element, RenderQueueItemVerifier<float>(element_max_size))); aec_render_queue_buffer_.resize(element_max_size); aec_capture_queue_buffer_.resize(element_max_size); submodules_.echo_cancellation->Initialize( proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(), num_proc_channels()); submodules_.echo_cancellation->set_suppression_level( config_.echo_canceller.legacy_moderate_suppression_level ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression : EchoCancellationImpl::SuppressionLevel::kHighSuppression); } void AudioProcessingImpl::InitializeGainController2() { if (config_.gain_controller2.enabled) { submodules_.gain_controller2->Initialize(proc_fullband_sample_rate_hz()); } } void AudioProcessingImpl::InitializeNoiseSuppressor() { submodules_.legacy_noise_suppressor.reset(); submodules_.noise_suppressor.reset(); if (config_.noise_suppression.enabled) { const bool use_legacy_ns = config_.noise_suppression.use_legacy_ns || enforced_usage_of_legacy_ns_; if (!use_legacy_ns) { auto map_level = [](AudioProcessing::Config::NoiseSuppression::Level level) { using NoiseSuppresionConfig = AudioProcessing::Config::NoiseSuppression; switch (level) { case NoiseSuppresionConfig::kLow: return NsConfig::SuppressionLevel::k6dB; case NoiseSuppresionConfig::kModerate: return NsConfig::SuppressionLevel::k12dB; case NoiseSuppresionConfig::kHigh: return NsConfig::SuppressionLevel::k18dB; case NoiseSuppresionConfig::kVeryHigh: return NsConfig::SuppressionLevel::k21dB; default: RTC_NOTREACHED(); } }; NsConfig cfg; cfg.target_level = map_level(config_.noise_suppression.level); submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>( cfg, proc_sample_rate_hz(), num_proc_channels()); } else { auto ns_level = NsConfigLevelToInterfaceLevel(config_.noise_suppression.level); submodules_.legacy_noise_suppressor = std::make_unique<NoiseSuppression>( num_proc_channels(), proc_sample_rate_hz(), ns_level); } } } void AudioProcessingImpl::InitializePreAmplifier() { if (config_.pre_amplifier.enabled) { submodules_.pre_amplifier.reset( new GainApplier(true, config_.pre_amplifier.fixed_gain_factor)); } else { submodules_.pre_amplifier.reset(); } } void AudioProcessingImpl::InitializeResidualEchoDetector() { RTC_DCHECK(submodules_.echo_detector); submodules_.echo_detector->Initialize( proc_fullband_sample_rate_hz(), 1, formats_.render_processing_format.sample_rate_hz(), 1); } void AudioProcessingImpl::InitializeAnalyzer() { if (submodules_.capture_analyzer) { submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(), num_proc_channels()); } } void AudioProcessingImpl::InitializePostProcessor() { if (submodules_.capture_post_processor) { submodules_.capture_post_processor->Initialize( proc_fullband_sample_rate_hz(), num_proc_channels()); } } void AudioProcessingImpl::InitializePreProcessor() { if (submodules_.render_pre_processor) { submodules_.render_pre_processor->Initialize( formats_.render_processing_format.sample_rate_hz(), formats_.render_processing_format.num_channels()); } } void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {} void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) { if (!aec_dump_) { return; } std::string experiments_description = ""; if (submodules_.echo_cancellation) { experiments_description += submodules_.echo_cancellation->GetExperimentsDescription(); } // TODO(peah): Add semicolon-separated concatenations of experiment // descriptions for other submodules. if (constants_.agc_clipped_level_min != kClippedLevelMin) { experiments_description += "AgcClippingLevelExperiment;"; } if (capture_nonlocked_.echo_controller_enabled) { experiments_description += "EchoController;"; } if (config_.gain_controller2.enabled) { experiments_description += "GainController2;"; } InternalAPMConfig apm_config; apm_config.aec_enabled = config_.echo_canceller.enabled; apm_config.aec_delay_agnostic_enabled = submodules_.echo_cancellation && submodules_.echo_cancellation->is_delay_agnostic_enabled(); apm_config.aec_drift_compensation_enabled = submodules_.echo_cancellation && submodules_.echo_cancellation->is_drift_compensation_enabled(); apm_config.aec_extended_filter_enabled = submodules_.echo_cancellation && submodules_.echo_cancellation->is_extended_filter_enabled(); apm_config.aec_suppression_level = submodules_.echo_cancellation ? static_cast<int>(submodules_.echo_cancellation->suppression_level()) : 0; apm_config.aecm_enabled = !!submodules_.echo_control_mobile; apm_config.aecm_comfort_noise_enabled = submodules_.echo_control_mobile && submodules_.echo_control_mobile->is_comfort_noise_enabled(); apm_config.aecm_routing_mode = submodules_.echo_control_mobile ? static_cast<int>(submodules_.echo_control_mobile->routing_mode()) : 0; apm_config.agc_enabled = submodules_.gain_control->is_enabled(); apm_config.agc_mode = static_cast<int>(submodules_.gain_control->mode()); apm_config.agc_limiter_enabled = submodules_.gain_control->is_limiter_enabled(); apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager; apm_config.hpf_enabled = config_.high_pass_filter.enabled; apm_config.ns_enabled = config_.noise_suppression.enabled; apm_config.ns_level = static_cast<int>(config_.noise_suppression.level); apm_config.transient_suppression_enabled = capture_.transient_suppressor_enabled; apm_config.experiments_description = experiments_description; apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled; apm_config.pre_amplifier_fixed_gain_factor = config_.pre_amplifier.fixed_gain_factor; if (!forced && apm_config == apm_config_for_aec_dump_) { return; } aec_dump_->WriteConfig(apm_config); apm_config_for_aec_dump_ = apm_config; } void AudioProcessingImpl::RecordUnprocessedCaptureStream( const float* const* src) { RTC_DCHECK(aec_dump_); WriteAecDumpConfigMessage(false); const size_t channel_size = formats_.api_format.input_stream().num_frames(); const size_t num_channels = formats_.api_format.input_stream().num_channels(); aec_dump_->AddCaptureStreamInput( AudioFrameView<const float>(src, num_channels, channel_size)); RecordAudioProcessingState(); } void AudioProcessingImpl::RecordUnprocessedCaptureStream( const AudioFrame& capture_frame) { RTC_DCHECK(aec_dump_); WriteAecDumpConfigMessage(false); aec_dump_->AddCaptureStreamInput(capture_frame); RecordAudioProcessingState(); } void AudioProcessingImpl::RecordProcessedCaptureStream( const float* const* processed_capture_stream) { RTC_DCHECK(aec_dump_); const size_t channel_size = formats_.api_format.output_stream().num_frames(); const size_t num_channels = formats_.api_format.output_stream().num_channels(); aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>( processed_capture_stream, num_channels, channel_size)); aec_dump_->WriteCaptureStreamMessage(); } void AudioProcessingImpl::RecordProcessedCaptureStream( const AudioFrame& processed_capture_frame) { RTC_DCHECK(aec_dump_); aec_dump_->AddCaptureStreamOutput(processed_capture_frame); aec_dump_->WriteCaptureStreamMessage(); } void AudioProcessingImpl::RecordAudioProcessingState() { RTC_DCHECK(aec_dump_); AecDump::AudioProcessingState audio_proc_state; audio_proc_state.delay = capture_nonlocked_.stream_delay_ms; audio_proc_state.drift = submodules_.echo_cancellation ? submodules_.echo_cancellation->stream_drift_samples() : 0; audio_proc_state.level = recommended_stream_analog_level(); audio_proc_state.keypress = capture_.key_pressed; aec_dump_->AddAudioProcessingState(audio_proc_state); } AudioProcessingImpl::ApmCaptureState::ApmCaptureState( bool transient_suppressor_enabled) : delay_offset_ms(0), was_stream_delay_set(false), output_will_be_muted(false), key_pressed(false), transient_suppressor_enabled(transient_suppressor_enabled), capture_processing_format(kSampleRate16kHz), split_rate(kSampleRate16kHz), echo_path_gain_change(false), prev_analog_mic_level(-1), prev_pre_amp_gain(-1.f), playout_volume(-1), prev_playout_volume(-1) {} AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default; void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract( const float* const* data, const StreamConfig& stream_config) { if (stream_config.has_keyboard()) { keyboard_data = data[stream_config.num_channels()]; } else { keyboard_data = NULL; } num_keyboard_frames = stream_config.num_frames(); } AudioProcessingImpl::ApmRenderState::ApmRenderState() = default; AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default; } // namespace webrtc
// Copyright (c) 2013-2020 The worldwideweb Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/tx_check.h> #include <consensus/validation.h> #include <hash.h> #include <script/interpreter.h> #include <script/script.h> #include <serialize.h> #include <streams.h> #include <test/data/sighash.json.h> #include <test/util/setup_common.h> #include <util/strencodings.h> #include <util/system.h> #include <version.h> #include <iostream> #include <boost/test/unit_test.hpp> #include <univalue.h> UniValue read_json(const std::string& jsondata); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { if (nIn >= txTo.vin.size()) { return uint256::ONE; } CMutableTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. FindAndDelete(scriptCode, CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { return uint256::ONE; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (InsecureRandRange(10)); for (int i=0; i<ops; i++) script << oplist[InsecureRandRange(std::size(oplist))]; } void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { tx.nVersion = InsecureRand32(); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0; int ins = (InsecureRandBits(2)) + 1; int outs = fSingle ? ins : (InsecureRandBits(2)) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = InsecureRand256(); txin.prevout.n = InsecureRandBits(2); RandomScript(txin.scriptSig); txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : std::numeric_limits<uint32_t>::max(); } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = InsecureRandRange(100000000); RandomScript(txout.scriptPubKey); } } BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sighash_test) { #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; int nRandomTests = 500; #else int nRandomTests = 50000; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = InsecureRand32(); CMutableTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = InsecureRandRange(txTo.vin.size()); uint256 sh, sho; sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx, raw_script, sigHashHex; int nIn, nHashType; uint256 sh; CTransactionRef tx; CScript scriptCode = CScript(); try { // deserialize test data raw_tx = test[0].get_str(); raw_script = test[1].get_str(); nIn = test[2].get_int(); nHashType = test[3].get_int(); sigHashHex = test[4].get_str(); CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); stream >> tx; TxValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest); BOOST_CHECK(state.IsValid()); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); } catch (...) { BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); continue; } sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2008-2009 The Chromium Embedded Framework Authors. // Portions copyright (c) 2006-2008 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 "libcef/browser_webkit_glue.h" #include "third_party/WebKit/Source/WebCore/config.h" MSVC_PUSH_WARNING_LEVEL(0); #include "CrossOriginPreflightResultCache.h" // NOLINT(build/include) #include "DocumentLoader.h" // NOLINT(build/include) #include "MemoryCache.h" // NOLINT(build/include) #include "ScriptController.h" // NOLINT(build/include) #include "TextEncoding.h" // NOLINT(build/include) #include "third_party/WebKit/Source/WebKit/chromium/src/WebFrameImpl.h" MSVC_POP_WARNING(); #undef LOG #include "base/logging.h" #include "base/string_util.h" #include "net/base/mime_util.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "webkit/glue/webkit_glue.h" #include "webkit/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" #include "webkit/gpu/webgraphicscontext3d_in_process_impl.h" #include "webkit/plugins/npapi/plugin_list.h" // Generated by GRIT #include "grit/webkit_resources.h" using WebKit::WebFrameImpl; namespace webkit_glue { bool IsMediaPlayerAvailable() { return true; } void InitializeTextEncoding() { WebCore::UTF8Encoding(); } v8::Handle<v8::Context> GetV8Context(WebKit::WebFrame* frame) { WebFrameImpl* impl = static_cast<WebFrameImpl*>(frame); return WebCore::ScriptController::mainWorldContext(impl->frame()); } void ClearCache() { if (WebCore::memoryCache()->disabled()) return; // Clear the memory cache by disabling and then re-enabling it. WebCore::memoryCache()->setDisabled(true); WebCore::memoryCache()->setDisabled(false); // Empty the Cross-Origin Preflight cache WebCore::CrossOriginPreflightResultCache::shared().empty(); } #if defined(OS_LINUX) int MatchFontWithFallback(const std::string& face, bool bold, bool italic, int charset) { return -1; } bool GetFontTable(int fd, uint32_t table, uint8_t* output, size_t* output_length) { return false; } #endif // Adapted from Chromium's BufferedResourceHandler::ShouldDownload bool ShouldDownload(const std::string& content_disposition, const std::string& mime_type) { std::string type = StringToLowerASCII(mime_type); std::string disposition = StringToLowerASCII(content_disposition); // First, examine content-disposition. if (!disposition.empty()) { bool should_download = true; // Some broken sites just send ... // Content-Disposition: ; filename="file" // ... screen those out here. if (disposition[0] == ';') should_download = false; if (disposition.compare(0, 6, "inline") == 0) should_download = false; // Some broken sites just send ... // Content-Disposition: filename="file" // ... without a disposition token... Screen those out. if (disposition.compare(0, 8, "filename") == 0) should_download = false; // Also in use is Content-Disposition: name="file" if (disposition.compare(0, 4, "name") == 0) should_download = false; // We have a content-disposition of "attachment" or unknown. // RFC 2183, section 2.8 says that an unknown disposition // value should be treated as "attachment". if (should_download) return true; } // Mirrors WebViewImpl::CanShowMIMEType() if (type.empty() || net::IsSupportedMimeType(type)) return false; // Finally, check the plugin list. bool allow_wildcard = false; std::vector<webkit::WebPluginInfo> plugins; webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( GURL(), type, allow_wildcard, NULL, &plugins, NULL); // If any associated plugins exist and are enabled don't allow the download. if (!plugins.empty()) { std::vector<webkit::WebPluginInfo>::const_iterator it = plugins.begin(); for (; it != plugins.end(); ++it) { if (webkit_glue::IsPluginEnabled(*it)) return false; } } return true; } bool IsPluginEnabled(const webkit::WebPluginInfo& plugin) { return true; } WebKit::WebGraphicsContext3D* CreateGraphicsContext3D( cef_graphics_implementation_t graphics_implementation, const WebKit::WebGraphicsContext3D::Attributes& attributes, WebKit::WebView* web_view, bool renderDirectlyToWebView) { #if defined(OS_WIN) bool use_command_buffer = (graphics_implementation == ANGLE_IN_PROCESS_COMMAND_BUFFER || graphics_implementation == DESKTOP_IN_PROCESS_COMMAND_BUFFER); #else bool use_command_buffer = (graphics_implementation == DESKTOP_IN_PROCESS_COMMAND_BUFFER); #endif if (use_command_buffer) { return new webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl(attributes); } else { return webkit::gpu::WebGraphicsContext3DInProcessImpl::CreateForWebView( attributes, renderDirectlyToWebView); } } } // namespace webkit_glue
#include <ply-build-repo/Module.h> // [ply module="codec"] void module_ply_codec(ModuleArgs* args) { args->addSourceFiles("ply-codec"); args->addIncludeDir(Visibility::Public, "."); args->addTarget(Visibility::Public, "runtime"); args->addTarget(Visibility::Public, "image"); args->addTarget(Visibility::Public, "audio-primitives"); args->addExtern(Visibility::Private, "libavcodec"); } // [ply extern="libavcodec" provider="macports"] ExternResult extern_libavcodec_macports(ExternCommand cmd, ExternProviderArgs* args) { PackageProvider prov{ PackageProvider::MacPorts, "ffmpeg", [&](StringView prefix) { args->dep->includeDirs.append(NativePath::join(prefix, "include")); args->dep->libs.append(NativePath::join(prefix, "lib/libavcodec.dylib")); args->dep->libs.append(NativePath::join(prefix, "lib/libavutil.dylib")); args->dep->libs.append(NativePath::join(prefix, "lib/libswresample.dylib")); args->dep->libs.append(NativePath::join(prefix, "lib/libswscale.dylib")); args->dep->libs.append(NativePath::join(prefix, "lib/libavformat.dylib")); }}; return prov.handle(cmd, args); } // [ply extern="libavcodec" provider="apt"] ExternResult extern_libavcodec_apt(ExternCommand cmd, ExternProviderArgs* args) { PackageProvider prov{PackageProvider::Apt, "libavcodec-dev", [&](StringView prefix) { args->dep->libs.append("-lavcodec"); args->dep->libs.append("-lavutil"); args->dep->libs.append("-lavformat"); args->dep->libs.append("-lswresample"); args->dep->libs.append("-lswscale"); }}; return prov.handle(cmd, args); } // [ply extern="libavcodec" provider="prebuilt"] ExternResult extern_libavcodec_prebuilt(ExternCommand cmd, ExternProviderArgs* args) { // Toolchain filters if (args->toolchain->targetPlatform.name != "windows") { return {ExternResult::UnsupportedToolchain, "Target platform must be 'windows'"}; } if (findItem(ArrayView<const StringView>{"x86", "x64"}, args->toolchain->arch) < 0) { return {ExternResult::UnsupportedToolchain, "Target arch must be 'x86' or 'x64'"}; } if (args->providerArgs) { return {ExternResult::BadArgs, ""}; } StringView libArch = (args->toolchain->arch == "x86" ? "win32" : "win64"); StringView version = "4.2.2"; StringView avcodecVersion = "avcodec-58"; StringView avutilVersion = "avutil-56"; StringView avformatVersion = "avformat-58"; StringView swresampleVersion = "swresample-3"; StringView swscaleVersion = "swscale-5"; // Handle Command Tuple<ExternResult, ExternFolder*> er = args->findExistingExternFolder(args->toolchain->arch); if (cmd == ExternCommand::Status) { return er.first; } else if (cmd == ExternCommand::Install) { if (er.first.code != ExternResult::SupportedButNotInstalled) { return er.first; } ExternFolder* externFolder = args->createExternFolder(args->toolchain->arch); for (StringView archiveType : ArrayView<const StringView>{"shared", "dev"}) { String archiveName = String::format("ffmpeg-{}-{}-{}.zip", version, libArch, archiveType); String archivePath = NativePath::join(externFolder->path, archiveName + ".zip"); String url = String::format("https://ffmpeg.zeranoe.com/builds/{}/{}/{}", libArch, archiveType, archiveName); if (!downloadFile(archivePath, url)) { return {ExternResult::InstallFailed, String::format("Error downloading '{}'", url)}; } if (!extractFile(archivePath)) { return {ExternResult::InstallFailed, String::format("Error extracting '{}'", archivePath)}; } FileSystem::native()->deleteFile(archivePath); } externFolder->success = true; externFolder->save(); return {ExternResult::Installed, ""}; } else if (cmd == ExternCommand::Instantiate) { if (er.first.code != ExternResult::Installed) { return er.first; } args->dep->includeDirs.append(NativePath::join( er.second->path, String::format("ffmpeg-{}-{}-dev/include", version, libArch))); args->dep->libs.append(NativePath::join( er.second->path, String::format("ffmpeg-{}-{}-dev/lib/avcodec.lib", version, libArch))); args->dep->libs.append(NativePath::join( er.second->path, String::format("ffmpeg-{}-{}-dev/lib/avutil.lib", version, libArch))); args->dep->libs.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-dev/lib/swresample.lib", version, libArch))); args->dep->libs.append(NativePath::join( er.second->path, String::format("ffmpeg-{}-{}-dev/lib/swscale.lib", version, libArch))); args->dep->libs.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-dev/lib/avformat.lib", version, libArch))); args->dep->dlls.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-shared/bin/{}.dll", version, libArch, avcodecVersion))); args->dep->dlls.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-shared/bin/{}.dll", version, libArch, avutilVersion))); args->dep->dlls.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-shared/bin/{}.dll", version, libArch, avformatVersion))); args->dep->dlls.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-shared/bin/{}.dll", version, libArch, swresampleVersion))); args->dep->dlls.append( NativePath::join(er.second->path, String::format("ffmpeg-{}-{}-shared/bin/{}.dll", version, libArch, swscaleVersion))); return {ExternResult::Instantiated, ""}; } PLY_ASSERT(0); return {ExternResult::Unknown, ""}; }
// (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. // Adapted from <boost/config/auto_link.hpp> and from // http://www.boost.org/more/separate_compilation.html, by John Maddock. #ifndef BOOST_IOSTREAMS_DETAIL_CONFIG_GCC_HPP_INCLUDED #define BOOST_IOSTREAMS_DETAIL_CONFIG_GCC_HPP_INCLUDED #if defined(_MSC_VER) # pragma once #endif #include <boost/config.hpp> // BOOST_INTEL. #if defined(__GNUC__) && !defined(BOOST_INTEL) # define BOOST_IOSTREAMS_GCC (__GNUC__ * 100 + __GNUC_MINOR__) # define BOOST_IOSTREAMS_GCC_WORKAROUND_GUARD 1 #else # define BOOST_IOSTREAMS_GCC_WORKAROUND_GUARD 0 #endif #endif // #ifndef BOOST_IOSTREAMS_DETAIL_CONFIG_GCC_HPP_INCLUDED
#include "chainerx/native/native_device.h" #include <cstdint> #include "chainerx/arithmetic_ops.h" #include "chainerx/array.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/float16.h" #include "chainerx/kernels/arithmetic.h" #include "chainerx/native/elementwise.h" #include "chainerx/native/kernel_regist.h" #include "chainerx/numeric.h" #include "chainerx/routines/arithmetic.h" #include "chainerx/scalar.h" namespace chainerx { namespace native { namespace { CHAINERX_NATIVE_REGISTER_ELTWISE_BINARY_KERNEL(AddKernel, { out = ArithmeticOps<T>::Add(x1, x2); }); class NativeAddASKernel : public AddASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = ArithmeticOps<T>::Add(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(AddASKernel, NativeAddASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(SubtractKernel, { out = ArithmeticOps<T>::Subtract(x1, x2); }, VisitNumericDtype); class NativeSubtractASKernel : public SubtractASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitNumericDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = ArithmeticOps<T>::Subtract(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(SubtractASKernel, NativeSubtractASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_BINARY_KERNEL(MultiplyKernel, { out = ArithmeticOps<T>::Multiply(x1, x2); }); class NativeMultiplyASKernel : public MultiplyASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = ArithmeticOps<T>::Multiply(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(MultiplyASKernel, NativeMultiplyASKernel); int32_t FloorDivide(int32_t x, int32_t y) { if (y == 0) { return 0; } auto div = std::div(x, y); return div.quot - ((y >= 0 ? div.rem : -div.rem) < 0 ? 1 : 0); } int64_t FloorDivide(int64_t x, int64_t y) { if (y == 0) { return 0; } auto div = std::div(x, y); return div.quot - ((y >= 0 ? div.rem : -div.rem) < 0 ? 1 : 0); } int8_t FloorDivide(int8_t x, int8_t y) { return static_cast<int8_t>(FloorDivide(static_cast<int32_t>(x), static_cast<int32_t>(y))); } int16_t FloorDivide(int16_t x, int16_t y) { return static_cast<int16_t>(FloorDivide(static_cast<int32_t>(x), static_cast<int32_t>(y))); } uint8_t FloorDivide(uint8_t x, uint8_t y) { if (y == 0) { return 0; } return x / y; } float FloorDivide(float x, float y) { float rem = std::fmod(x, y); return (x - rem) / y - ((rem < 0 && y > 0) || (rem > 0 && y < 0) ? 1 : 0); } double FloorDivide(double x, double y) { double rem = std::fmod(x, y); return (x - rem) / y - ((rem < 0 && y > 0) || (rem > 0 && y < 0) ? 1 : 0); } chainerx::Float16 FloorDivide(chainerx::Float16 x, chainerx::Float16 y) { return chainerx::Float16{FloorDivide(static_cast<float>(x), static_cast<float>(y))}; } CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(FloorDivideKernel, { out = native::FloorDivide(x1, x2); }, VisitNumericDtype); class NativeFloorDivideASKernel : public FloorDivideASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitNumericDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = native::FloorDivide(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(FloorDivideASKernel, NativeFloorDivideASKernel); class NativeFloorDivideSAKernel : public FloorDivideSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitNumericDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = native::FloorDivide(x1, x2); } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(FloorDivideSAKernel, NativeFloorDivideSAKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_BINARY_KERNEL(DivideKernel, { out = ArithmeticOps<T>::Divide(x1, x2); }); class NativeDivideASKernel : public DivideASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = ArithmeticOps<T>::Divide(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(DivideASKernel, NativeDivideASKernel); class NativeDivideSAKernel : public DivideSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = ArithmeticOps<T>::Divide(x1, x2); } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(DivideSAKernel, NativeDivideSAKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(PowerKernel, { out = chainerx::Power(x1, x2); }, VisitNumericDtype); class NativePowerASKernel : public PowerASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitNumericDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = chainerx::Power(x1, x2); } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(PowerASKernel, NativePowerASKernel); class NativePowerSAKernel : public PowerSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitNumericDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = chainerx::Power(x1, x2); } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(PowerSAKernel, NativePowerSAKernel); } // namespace } // namespace native } // namespace chainerx
#ifndef BOOST_MPL_AUX_PREPROCESSOR_FILTER_PARAMS_HPP_INCLUDED #define BOOST_MPL_AUX_PREPROCESSOR_FILTER_PARAMS_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$ // $Date$ // $Revision$ #define BOOST_MPL_PP_FILTER_PARAMS_0(p1, p2, p3, p4, p5, p6, p7, p8, p9) #define BOOST_MPL_PP_FILTER_PARAMS_1(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1 #define BOOST_MPL_PP_FILTER_PARAMS_2(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2 #define BOOST_MPL_PP_FILTER_PARAMS_3(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3 #define BOOST_MPL_PP_FILTER_PARAMS_4(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4 #define BOOST_MPL_PP_FILTER_PARAMS_5(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4,p5 #define BOOST_MPL_PP_FILTER_PARAMS_6(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4,p5,p6 #define BOOST_MPL_PP_FILTER_PARAMS_7(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4,p5,p6,p7 #define BOOST_MPL_PP_FILTER_PARAMS_8(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4,p5,p6,p7,p8 #define BOOST_MPL_PP_FILTER_PARAMS_9(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1,p2,p3,p4,p5,p6,p7,p8,p9 #endif // BOOST_MPL_AUX_PREPROCESSOR_FILTER_PARAMS_HPP_INCLUDED
#include <iostream> #include "ql/quantlib.hpp" int main() { using namespace QuantLib; auto date = Date(2, August, 2019); std::cout << date << '\n'; return 0; }
#pragma once #include <cli/Cli.hpp> #include <client/Notifier.hpp> #include <db/LevelMap.hpp> #include <db/Exception.hpp> #include <net/ChainServer.hpp> #include <net/Upnp.hpp> #include <fc/log/appender.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/program_options.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/tee.hpp> #include <fstream> #include <iostream> #include <glua/hsrcore_lua_api.h> #include <glua/hsrcore_lua_lib.h> #include <blockchain/GluaChainApi.hpp> namespace hsrcore { namespace client { typedef boost::iostreams::tee_device<std::ostream, std::ofstream> TeeDevice; typedef boost::iostreams::stream<TeeDevice> TeeStream; namespace detail { using namespace boost; using namespace hsrcore::wallet; using namespace hsrcore::blockchain; // wrap the exception database in a class that logs the exception to the normal logging stream // in addition to just storing it class LoggingExceptionDb { public: typedef hsrcore::db::LevelMap<fc::time_point, fc::exception> ExceptionLeveldbType; private: ExceptionLeveldbType _db; public: void open(const fc::path& filename) { try { _db.open(filename); } catch (const hsrcore::db::level_map_open_failure&) { fc::remove_all(filename); _db.open(filename); } } void store(const fc::exception& e) { elog("storing error in database: ${e}", ("e", e)); _db.store(fc::time_point::now(), e); } ExceptionLeveldbType::iterator lower_bound(const fc::time_point time) const { return _db.lower_bound(time); } ExceptionLeveldbType::iterator begin() const { return _db.begin(); } void remove(const fc::time_point key) { _db.remove(key); } }; class ClientImpl : public hsrcore::net::NodeDelegate, public hsrcore::api::CommonApi { public: class UserAppender : public fc::appender { public: UserAppender(ClientImpl& c) : _client_impl(c), _thread(&fc::thread::current()) {} virtual void log(const fc::log_message& m) override { if (!_thread->is_current()) return _thread->async([&](){ log(m); }, "user_appender::log").wait(); string format = m.get_format(); // lookup translation on format here // perform variable substitution; string message = format_string(format, m.get_data()); _history.emplace_back(message); if (_client_impl._cli) _client_impl._cli->display_status_message(message); else std::cout << message << "\n"; // call a callback to the client... // we need an RPC call to fetch this log and display the // current status. } vector<string> get_history()const { if (!_thread->is_current()) return _thread->async([&](){ return get_history(); }, "user_appender::get_history").wait(); return _history; } void clear_history() { if (!_thread->is_current()) return _thread->async([&](){ return clear_history(); }, "user_appender::clear_history").wait(); _history.clear(); } private: // TODO: consider a deque and enforce maximum length? vector<string> _history; ClientImpl& _client_impl; fc::thread* _thread; }; ClientImpl(hsrcore::client::Client* self, const std::string& user_agent) : _self(self), _user_agent(user_agent), _last_sync_status_message_indicated_in_sync(true), _last_sync_status_head_block(0), _remaining_items_to_sync(0), _sync_speed_accumulator(boost::accumulators::tag::rolling_window::window_size = 5), _connection_count_notification_interval(fc::minutes(5)), _connection_count_always_notify_threshold(5), _connection_count_last_value_displayed(0), _blockchain_synopsis_size_limit((unsigned)(log2(HSR_BLOCKCHAIN_BLOCKS_PER_YEAR * 20))), _debug_last_wait_block(0), dHashesPerSec(0.0), nHPSTimerStart(fc::time_point_sec(0)), nBlockSize(0), nBlockTx(1000), fgenerate(false), nLastCoinStakeSearchInterval(0), fposgenerate(false), exit_miner_thread(0), exit_stake_thread(0) { try { if (hsrcore::lua::api::global_glua_chain_api == nullptr) hsrcore::lua::api::global_glua_chain_api = new hsrcore::lua::api::GluaChainApi; _user_appender = fc::shared_ptr<UserAppender>(new UserAppender(*this)); fc::logger::get("user").add_appender(_user_appender); try { _rpc_server = std::make_shared<RpcServer>(self); } FC_RETHROW_EXCEPTIONS(warn, "rpc server") try { _chain_db = std::make_shared<ChainDatabase>(); } FC_RETHROW_EXCEPTIONS(warn, "chain_db") } FC_RETHROW_EXCEPTIONS(warn, "") } virtual ~ClientImpl() override { cancel_blocks_too_old_monitor_task(); cancel_rebroadcast_pending_loop(); if (_chain_downloader_future.valid() && !_chain_downloader_future.ready()) _chain_downloader_future.cancel_and_wait(__FUNCTION__); _rpc_server.reset(); // this needs to shut down before the _p2p_node because several RPC requests will try to dereference _p2p_node. Shutting down _rpc_server kills all active/pending requests delete _cli; _cli = nullptr; _p2p_node.reset(); } void start() { std::exception_ptr unexpected_exception; try { _cli->start(); } catch (...) { unexpected_exception = std::current_exception(); } if (unexpected_exception) { if (_notifier) _notifier->notify_client_exiting_unexpectedly(); std::rethrow_exception(unexpected_exception); } } /** * If the current thread is not created or did not start then start delegate loop * * @return void */ void reschedule_delegate_loop(); void start_delegate_loop(); void cancel_delegate_loop(); void delegate_loop(); void GenerateBitcoins(bool fGenerate, int nThreads); void GenerateStakes(bool fGenerate = true); float GetDiffculty(SignedBlockHeader& block_header,bool is_coinstake); double GetPoSKernelPS(); void set_target_connections(uint32_t target); hsrcore::blockchain::TransactionIdType network_broadcast_transactions(const std::vector<hsrcore::blockchain::SignedTransaction>& transactions_to_broadcast); void start_rebroadcast_pending_loop(); void cancel_rebroadcast_pending_loop(); void rebroadcast_pending_loop(); fc::future<void> _rebroadcast_pending_loop_done; void start_fork_update_time_loop(); void fork_update_time_loop(); fc::future<void> _fork_update_loop_done; void configure_rpc_server(Config& cfg, const program_options::variables_map& option_variables); void configure_chain_server(Config& cfg, const program_options::variables_map& option_variables); BlockForkData on_new_block(const FullBlock& block, const BlockIdType& block_id, bool sync_mode); bool on_new_transaction(const SignedTransaction& trx); void blocks_too_old_monitor_task(); void cancel_blocks_too_old_monitor_task(); void set_client_debug_name(const string& name) { _config.client_debug_name = name; return; } /* Implement node_delegate */ // @{ virtual bool has_item(const hsrcore::net::ItemId& id) override; fc::time_point_sec handle_ntp_time(bool need_update)override; virtual bool handle_message(const hsrcore::net::Message&, bool sync_mode) override; virtual std::vector<hsrcore::net::ItemHashType> get_item_ids(uint32_t item_type, const vector<hsrcore::net::ItemHashType>& blockchain_synopsis, uint32_t& remaining_item_count, uint32_t limit = 2000) override; virtual hsrcore::net::Message get_item(const hsrcore::net::ItemId& id) override; virtual fc::sha256 get_chain_id() const override { FC_ASSERT(_chain_db != nullptr); return _chain_db->get_chain_id(); } virtual std::vector<hsrcore::net::ItemHashType> get_blockchain_synopsis(uint32_t item_type, const hsrcore::net::ItemHashType& reference_point = hsrcore::net::ItemHashType(), uint32_t number_of_blocks_after_reference_point = 0) override; virtual void sync_status(uint32_t item_type, uint32_t item_count) override; virtual void connection_count_changed(uint32_t c) override; virtual uint32_t get_block_number(const hsrcore::net::ItemHashType& block_id) override; virtual fc::time_point_sec get_block_time(const hsrcore::net::ItemHashType& block_id) override; virtual fc::time_point_sec get_blockchain_now() override; virtual hsrcore::net::ItemHashType get_head_block_id() const override; virtual uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t unix_timestamp) const override; virtual void error_encountered(const std::string& message, const fc::oexception& error) override; /// @} hsrcore::client::Client* _self; std::string _user_agent; hsrcore::cli::Cli* _cli = nullptr; std::unique_ptr<std::istream> _command_script_holder; std::ofstream _console_log; std::unique_ptr<std::ostream> _output_stream; std::unique_ptr<TeeDevice> _tee_device; std::unique_ptr<TeeStream> _tee_stream; bool _enable_ulog = false; bool _test_net = false; fc::path _data_dir; fc::shared_ptr<UserAppender> _user_appender; bool _simulate_disconnect = false; fc::scoped_connection _time_discontinuity_connection; hsrcore::rpc::RpcServerPtr _rpc_server = nullptr; std::unique_ptr<hsrcore::net::ChainServer> _chain_server = nullptr; std::unique_ptr<hsrcore::net::UpnpService> _upnp_service = nullptr; ChainDatabasePtr _chain_db = nullptr; unordered_map<TransactionIdType, SignedTransaction> _pending_trxs; WalletPtr _wallet = nullptr; // std::shared_ptr<hsrcore::mail::server> _mail_server = nullptr; // std::shared_ptr<hsrcore::mail::client> _mail_client = nullptr; fc::time_point _last_sync_status_message_time; bool _last_sync_status_message_indicated_in_sync; uint32_t _last_sync_status_head_block; uint32_t _remaining_items_to_sync; boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::rolling_mean> > _sync_speed_accumulator; // Chain downloader fc::future<void> _chain_downloader_future; bool _chain_downloader_running = false; uint32_t _chain_downloader_blocks_remaining = 0; fc::time_point _last_connection_count_message_time; /** display messages about the connection count changing at most once every _connection_count_notification_interval */ fc::microseconds _connection_count_notification_interval; /** exception: if you have fewer than _connection_count_always_notify_threshold connections, notify any time the count changes */ uint32_t _connection_count_always_notify_threshold; uint32_t _connection_count_last_value_displayed; Config _config; LoggingExceptionDb _exception_db; // Delegate block production fc::future<void> _delegate_loop_complete; bool _delegate_loop_first_run = true; DelegateConfig _delegate_config; //start by assuming not syncing, network won't send us a msg if we start synced and stay synched. //at worst this means we might briefly sending some pending transactions while not synched. bool _sync_mode = false; RpcServerConfig _tmp_rpc_config; hsrcore::net::NodePtr _p2p_node = nullptr; bool _simulated_network = false; HSRGntpNotifierPtr _notifier; fc::future<void> _blocks_too_old_monitor_done; const unsigned _blockchain_synopsis_size_limit; fc::future<void> _client_done; uint32_t _debug_last_wait_block; uint32_t _debug_stop_before_block_num; double dHashesPerSec; fc::time_point_sec nHPSTimerStart; uint64_t nBlockSize; uint64_t nBlockTx; bool fgenerate; bool fposgenerate; uint32_t nThread; int64_t nLastCoinStakeSearchInterval; std::map<std::string, FullBlock> mapNewBlock; PublicKeyType coinbase; int exit_miner_thread; int exit_stake_thread; void wallet_http_callback(const string& url, const LedgerEntry& e); int save_code_to_file(const string& name, GluaModuleByteStream *stream, char* err_msg) const; Address get_contract_address(const string& contract, ChainInterfacePtr db=nullptr) const; ChainInterfacePtr sandbox_get_correct_state_ptr() const; Address sandbox_get_contract_address(const string& contract) const; fc::path compile_contract_helper(const fc::path& filename) const; boost::signals2::scoped_connection _http_callback_signal_connection; //-------------------------------------------------- JSON-RPC Method Implementations // include all of the method overrides generated by the hsr_api_generator // this file just contains a bunch of lines that look like: // virtual void some_method(const string& some_arg) override; #include <rpc_stubs/CommonApiOverrides.ipp>//include auto-generated RPC API declarations }; void compile_contract_callback(lua_State *L, std::list<void*>*args_list); } } } // namespace hsrcore::client::detail
/* * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #include <botan/symkey.h> namespace Botan_Tests { namespace { using Botan::OctetString; Test::Result test_from_rng() { Test::Result result("OctetString"); OctetString os(Test::rng(), 32); result.test_eq("length is 32 bytes", os.size(), 32); return result; } Test::Result test_from_hex() { Test::Result result("OctetString"); OctetString os("0123456789ABCDEF"); result.test_eq("length is 8 bytes", os.size(), 8); return result; } Test::Result test_from_byte() { Test::Result result("OctetString"); auto rand_bytes = Test::rng().random_vec(8); OctetString os(rand_bytes.data(), rand_bytes.size()); result.test_eq("length is 8 bytes", os.size(), 8); return result; } Test::Result test_odd_parity() { Test::Result result("OctetString"); OctetString os("FFFFFFFFFFFFFFFF"); os.set_odd_parity(); OctetString expected("FEFEFEFEFEFEFEFE"); result.test_eq("odd parity set correctly", os, expected); OctetString os2("EFCBDA4FAA997F63"); os2.set_odd_parity(); OctetString expected2("EFCBDA4FAB987F62"); result.test_eq("odd parity set correctly", os2, expected2); return result; } Test::Result test_as_string() { Test::Result result("OctetString"); OctetString os("0123456789ABCDEF"); result.test_eq("OctetString::as_string() returns correct string", os.as_string(), "0123456789ABCDEF"); return result; } Test::Result test_xor() { Test::Result result("OctetString"); OctetString os1("0000000000000000"); OctetString os2("FFFFFFFFFFFFFFFF"); OctetString xor_result = os1 ^ os2; result.test_eq("OctetString XOR operations works as expected", xor_result, os2); xor_result = os1; xor_result ^= os2; result.test_eq("OctetString XOR operations works as expected", xor_result, os2); xor_result = os2 ^ os2; result.test_eq("OctetString XOR operations works as expected", xor_result, os1); OctetString os3("0123456789ABCDEF"); xor_result = os3 ^ os2; OctetString expected("FEDCBA9876543210"); result.test_eq("OctetString XOR operations works as expected", xor_result, expected); return result; } Test::Result test_equality() { Test::Result result("OctetString"); OctetString os1("0000000000000000"); OctetString os2("FFFFFFFFFFFFFFFF"); result.confirm("OctetString equality operations works as expected", os1 == os1); result.confirm("OctetString equality operations works as expected", os2 == os2); result.confirm("OctetString equality operations works as expected", os1 != os2); return result; } Test::Result test_append() { Test::Result result("OctetString"); OctetString os1("0000"); OctetString os2("FFFF"); OctetString expected("0000FFFF"); OctetString append_result = os1 + os2; result.test_eq("OctetString append operations works as expected", append_result, expected); return result; } class OctetString_Tests : public Test { public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; std::vector<std::function<Test::Result()>> fns = { test_from_rng, test_from_hex, test_from_byte, test_odd_parity, test_as_string, test_xor, test_equality, test_append }; for(size_t i = 0; i != fns.size(); ++i) { try { results.push_back(fns[ i ]()); } catch(std::exception& e) { results.push_back(Test::Result::Failure("OctetString tests " + std::to_string(i), e.what())); } } return results; } }; BOTAN_REGISTER_TEST("octetstring", OctetString_Tests); } }
/* * 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/cs/model/DescribeExternalAgentResult.h> #include <json/json.h> using namespace AlibabaCloud::CS; using namespace AlibabaCloud::CS::Model; DescribeExternalAgentResult::DescribeExternalAgentResult() : ServiceResult() {} DescribeExternalAgentResult::DescribeExternalAgentResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeExternalAgentResult::~DescribeExternalAgentResult() {} void DescribeExternalAgentResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["config"].isNull()) config_ = value["config"].asString(); } std::string DescribeExternalAgentResult::getConfig()const { return config_; }
/* * File: dht.hpp * Created Date: 2019-12-29 * Author: Lei Pan * Contact: <panlei7@gmail.com> * * Last Modified: Sunday December 29th 2019 12:00:12 pm * * MIT License * * Copyright (c) 2019 Lei Pan * * 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. * ----- * HISTORY: * Date By Comments * ---------- --- * ---------------------------------------------------------- */ #ifndef DHT_DHT_H_ #define DHT_DHT_H_ #include <Eigen/Dense> class DiscreteHankelTransform { public: DiscreteHankelTransform(int order, int nr); ~DiscreteHankelTransform(); Eigen::VectorXd r_sampling(double rmax); Eigen::VectorXd k_sampling(double rmax); // k is rho in the paper Eigen::VectorXd forward(const Eigen::Ref<const Eigen::VectorXd> &fr); Eigen::VectorXd backward(const Eigen::Ref<const Eigen::VectorXd> &fk); Eigen::VectorXd shift(const Eigen::Ref<const Eigen::VectorXd> &raw, int m); Eigen::MatrixXd tmatrix() const; protected: int order_; double rmax_; int nr_; Eigen::VectorXd roots_; Eigen::MatrixXd tmatrix_; }; #endif
/*++ Copyright (c) 2016 KelvinChan. All rights reserved. Use of this source code is governed by a MIT-style license that can be found in the LICENSE file. Module Name: vmx.cpp Abstract: Intel VT-x , VMX Instruction and behavior Emulation Author: Kelvin Chan Environment: Kernel VMM Mode --*/ #include <intrin.h> #include "..\HyperPlatform\util.h" #include "vmcs.h" #include "vmx.h" #include "..\HyperPlatform\vmm.h" #include "..\HyperPlatform\log.h" #include "..\HyperPlatform\common.h" #include "vmx_common.h" #include "..\HyperPlatform\ept.h" extern "C" { //////////////////////////////////////////////////////////////////////////////////////////////////// //// Prototype //// VOID SaveGuestCr8( VCPUVMX* vcpu, ULONG_PTR cr8 ); VOID RestoreGuestCr8( VCPUVMX* vcpu ); VOID VmxAssertPrint( ULONG Line, bool IsVerified ); //////////////////////////////////////////////////////////////////////////////////////////////////// //// Marco //// #define HYPERPLATFORM_ASSERT(statement) \ VmxAssertPrint(__LINE__ , statement); //////////////////////////////////////////////////////////////////////////////////////////////////// //// //// Variable //// extern BOOLEAN IsEmulateVMExit; //////////////////////////////////////////////////////////////////////////////////////////////////// //// //// Type //// //////////////////////////////////////////////////////////////////////////////////////////////////// //// //// Implementation //// //------------------------------------------------------------------------------------------------// BOOLEAN VmxIsGuestPaePaging() /*++ Desscription: Validating guest PAE mode. Paremeters: Guest Context Return Value: NO --*/ { VmxVmEntryControls VmEntryCtrl = { UtilVmRead(VmcsField::kVmEntryControls) }; FlagRegister rflags = { UtilVmRead(VmcsField::kGuestRflags) }; Cr0 cr0 = { UtilVmRead(VmcsField::kGuestCr0) }; Cr4 cr4 = { UtilVmRead(VmcsField::kGuestCr4) }; if (cr0.fields.pg && cr4.fields.pae && !VmEntryCtrl.fields.ia32e_mode_guest) { return TRUE; } return FALSE; } //------------------------------------------------------------------------------------------------// VOID VmxAssertPrint( _In_ ULONG Line, _In_ bool IsVerified ) /*++ Desscription: Test assert. debug use. Paremeters: Guest Context Return Value: NO --*/ { if (!IsVerified) { PrintVMCS(); ///NT_ASSERT(IsVerified); HYPERPLATFORM_COMMON_DBG_BREAK(); HYPERPLATFORM_LOG_DEBUG("Somethings wrong ~~~ Line: %x", Line); } } //------------------------------------------------------------------------------------------------// VOID LEAVE_GUEST_MODE( _In_ VCPUVMX* vm ) /*++ Desscription: Virtual process enter the Root Mode. Paremeters: Guest Context Return Value: NO --*/ { vm->inRoot = RootMode; HYPERPLATFORM_LOG_DEBUG_SAFE("VMM: %I64x RIP= %p Enter Root mode Reason: %d", vm, UtilVmRead(VmcsField::kGuestRip), UtilVmRead(VmcsField::kVmExitReason)); } //------------------------------------------------------------------------------------------------// VOID ENTER_GUEST_MODE( _In_ VCPUVMX* vm ) /*++ Desscription: Virtual process enter the Guest Mode. Paremeters: Guest Context Return Value: NO --*/ { vm->inRoot = GuestMode; HYPERPLATFORM_LOG_DEBUG_SAFE("VMM: %I64x Enter Guest mode", vm); } //------------------------------------------------------------------------------------------------// VMX_MODE VmxGetVmxMode( _In_ VCPUVMX* vmx ) /*++ Desscription: Get VMX Mode of the corresponding virtual processor Paremeters: Guest Context Return Value: Emulated-Root or Emulated-Guest Mode --*/ { if (vmx) { return vmx->inRoot; } else { return VMX_MODE::RootMode; } } //------------------------------------------------------------------------------------------------// VOID SaveGuestCr8( _In_ VCPUVMX* vcpu, _In_ ULONG_PTR cr8 ) /*++ Desscription: NO Paremeters: Guest Context Return Value: NO --*/ { vcpu->guest_cr8 = cr8; } //------------------------------------------------------------------------------------------------// VOID RestoreGuestCr8( _In_ VCPUVMX* vcpu ) /*++ Desscription: NO Paremeters: Guest Context Return Value: NO --*/ { __writecr8(vcpu->guest_cr8); } //------------------------------------------------------------------------------------------------// VOID DumpVcpu( _In_ GuestContext* guest_context ) { /*++ Desscription: Dumping the virtual process context. Paremeters: Guest Context Return Value: NO --*/ ULONG64 vmcs12_va = 0; ULONG64 vmcs_pa; VCPUVMX* vmx = NULL; if (!guest_context) { HYPERPLATFORM_LOG_DEBUG_SAFE("GuestContex Empty"); return; } vmx = VmmpGetVcpuVmx(guest_context); __vmx_vmptrst(&vmcs_pa); HYPERPLATFORM_LOG_DEBUG_SAFE("CurrentVmcs: %I64X vm: %I64x vmcs02: %I64X vmcs01: %I64x vmcs12: %I64x root mode: %I64x \r\n", vmcs_pa, vmx, vmx->vmcs02_pa, vmx->vmcs01_pa, vmx->vmcs12_pa, vmx->inRoot, VmmpGetvCpuMode(guest_context)); } //------------------------------------------------------------------------------------------------// VOID VmxVmEntryCheckGuestReg() /*++ Desscription: Validating VMCS0-2's guest register state for vmentry to L2 during emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { VmxVmEntryControls VmEntryCtrl = { UtilVmRead(VmcsField::kVmEntryControls) }; FlagRegister rflags = { UtilVmRead(VmcsField::kGuestRflags) }; Cr0 cr0 = { UtilVmRead(VmcsField::kGuestCr0) }; Cr0 cr0_fixed0 = { UtilReadMsr(Msr::kIa32VmxCr0Fixed0) }; Cr0 cr0_fixed1 = { UtilReadMsr(Msr::kIa32VmxCr0Fixed1) }; Cr0 cr0_test = { 0 }; cr0_test.all = cr0.all; cr0_test.all &= cr0_fixed1.all; cr0_test.all |= cr0_fixed0.all; HYPERPLATFORM_ASSERT(cr0_test.all == cr0.all); Cr4 cr4 = { UtilVmRead(VmcsField::kGuestCr4) }; Cr4 cr4_fixed0 = { UtilReadMsr(Msr::kIa32VmxCr4Fixed0) }; Cr4 cr4_fixed1 = { UtilReadMsr(Msr::kIa32VmxCr4Fixed1) }; Cr4 cr4_test = { 0 }; cr4_test.all = cr4.all; cr4_test.all &= cr4_fixed1.all; cr4_test.all |= cr4_fixed0.all; HYPERPLATFORM_ASSERT(cr4_test.all == cr4.all); if (VmEntryCtrl.fields.ia32e_mode_guest) { HYPERPLATFORM_ASSERT(cr0.fields.pg && cr4.fields.pae); } else { HYPERPLATFORM_ASSERT(!cr4.fields.pcide); } HYPERPLATFORM_ASSERT(cr0.fields.pg && cr0.fields.pe); if (VmEntryCtrl.fields.load_debug_controls) { MSR_IA32_DEBUGCTL DbgCtrl = { UtilVmRead64(VmcsField::kGuestIa32Debugctl)}; HYPERPLATFORM_ASSERT(!DbgCtrl.fields.Reserved1 && !DbgCtrl.fields.Reserved2); HYPERPLATFORM_ASSERT(!(UtilVmRead64(VmcsField::kGuestDr7) >> 32)); } HYPERPLATFORM_ASSERT(UtilpIsCanonicalFormAddress((void*)UtilVmRead64(VmcsField::kGuestSysenterEip)) && UtilpIsCanonicalFormAddress((void*)UtilVmRead64(VmcsField::kGuestSysenterEsp))); if (VmEntryCtrl.fields.load_ia32_perf_global_ctrl) { MSR_IA32_PERF_GLOBAL_CTRL PerfCtrl = { UtilVmRead(VmcsField::kGuestIa32PerfGlobalCtrl) }; HYPERPLATFORM_ASSERT( !PerfCtrl.fields.Reserved && !PerfCtrl.fields.Reserved2); } if (VmEntryCtrl.fields.load_ia32_efer) { MSR_EFER efer = { UtilVmRead(VmcsField::kGuestIa32Efer) }; if (cr0.fields.pg) { HYPERPLATFORM_ASSERT(efer.fields.LMA == VmEntryCtrl.fields.ia32e_mode_guest == efer.fields.LME); } else { HYPERPLATFORM_ASSERT(efer.fields.LMA == VmEntryCtrl.fields.ia32e_mode_guest); } } if (VmEntryCtrl.fields.ia32e_mode_guest || !cr0.fields.pe) { HYPERPLATFORM_ASSERT(!rflags.fields.vm); } } //--------------------------------------------------------------------------------------------------------- ------------// VOID VmxVmEntryCheckGuestSegReg() /*++ Desscription: Validating VMCS0-2's Segment Register for vmentry to L2 during emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { FlagRegister GuestRflags = { UtilVmRead64(VmcsField::kGuestRflags) }; VmxVmEntryControls VmEntryCtrl = { UtilVmRead64(VmcsField::kVmEntryControls) }; VmxSecondaryProcessorBasedControls VmSecondProcCtrl = { UtilVmRead64(VmcsField::kSecondaryVmExecControl) }; BOOLEAN IsGuestOnV8086 = FALSE; BOOLEAN IsGuestOnIa32e = FALSE; if (GuestRflags.fields.vm) { IsGuestOnV8086 = TRUE; } else if (VmEntryCtrl.fields.ia32e_mode_guest) { IsGuestOnIa32e = TRUE; } if (IsGuestOnV8086) { HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestCsBase) == UtilVmRead(VmcsField::kGuestCsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestDsBase) == UtilVmRead(VmcsField::kGuestDsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestSsBase) == UtilVmRead(VmcsField::kGuestSsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestEsBase) == UtilVmRead(VmcsField::kGuestEsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestFsBase) == UtilVmRead(VmcsField::kGuestFsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestGsBase) == UtilVmRead(VmcsField::kGuestGsSelector) << 4); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestCsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestDsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestSsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestEsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestFsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestGsLimit) == 0xFFFF); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestCsArBytes) == 0xF3); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestDsArBytes) == 0xF3); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestSsArBytes) == 0xF3); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestEsArBytes) == 0xF3); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestFsArBytes) == 0xF3); HYPERPLATFORM_ASSERT(UtilVmRead(VmcsField::kGuestGsArBytes) == 0xF3); } else { Cr0 cr0 = { UtilVmRead(VmcsField::kGuestCr0) }; ULONG CsBase = UtilVmRead(VmcsField::kGuestCsBase) ; ULONG DsBase = UtilVmRead(VmcsField::kGuestDsBase) ; ULONG SsBase = UtilVmRead(VmcsField::kGuestSsBase) ; ULONG EsBase = UtilVmRead(VmcsField::kGuestEsBase) ; ULONG FsBase = UtilVmRead(VmcsField::kGuestFsBase) ; ULONG GsBase = UtilVmRead(VmcsField::kGuestGsBase) ; ULONG TrBase = UtilVmRead(VmcsField::kGuestTrBase) ; ULONG LdtrBase = UtilVmRead(VmcsField::kGuestLdtrBase); VmxSegmentDescriptorAccessRight CsArBytes = { UtilVmRead(VmcsField::kGuestCsArBytes) }; VmxSegmentDescriptorAccessRight DsArBytes = { UtilVmRead(VmcsField::kGuestDsArBytes) }; VmxSegmentDescriptorAccessRight SsArBytes = { UtilVmRead(VmcsField::kGuestSsArBytes) }; VmxSegmentDescriptorAccessRight EsArBytes = { UtilVmRead(VmcsField::kGuestEsArBytes) }; VmxSegmentDescriptorAccessRight FsArBytes = { UtilVmRead(VmcsField::kGuestFsArBytes) }; VmxSegmentDescriptorAccessRight GsArBytes = { UtilVmRead(VmcsField::kGuestGsArBytes) }; VmxSegmentDescriptorAccessRight TrArBytes = { UtilVmRead(VmcsField::kGuestTrArBytes) }; VmxSegmentDescriptorAccessRight LdtrArBytes = { UtilVmRead(VmcsField::kGuestLdtrArBytes) }; SegmentSelector SsSelector = { UtilVmRead(VmcsField::kGuestSsSelector) }; SegmentSelector CsSelector = { UtilVmRead(VmcsField::kGuestCsSelector) }; SegmentSelector EsSelector = { UtilVmRead(VmcsField::kGuestEsSelector) }; SegmentSelector FsSelector = { UtilVmRead(VmcsField::kGuestFsSelector) }; SegmentSelector GsSelector = { UtilVmRead(VmcsField::kGuestGsSelector) }; SegmentSelector DsSelector = { UtilVmRead(VmcsField::kGuestDsSelector) }; SegmentSelector TrSelector = { UtilVmRead(VmcsField::kGuestTrSelector) }; SegmentSelector LdtrSelector = { UtilVmRead(VmcsField::kGuestLdtrSelector) }; bool VerifiedCsSelectorAr = (CsArBytes.fields.type == 9 || CsArBytes.fields.type == 11 || CsArBytes.fields.type == 13 || CsArBytes.fields.type == 15); if (VmSecondProcCtrl.fields.unrestricted_guest) { //read/write accessed expand-up data segment HYPERPLATFORM_ASSERT(VerifiedCsSelectorAr || CsArBytes.fields.type == 3); } else { //accessed code segment HYPERPLATFORM_ASSERT(VerifiedCsSelectorAr); HYPERPLATFORM_ASSERT(VerifiedCsSelectorAr || SsArBytes.fields.dpl == SsSelector.fields.rpl); if (!DsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((DsArBytes.fields.dpl >= DsSelector.fields.rpl) && (DsArBytes.fields.type <= 11)); } if (!EsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((EsArBytes.fields.dpl >= EsSelector.fields.rpl) && (EsArBytes.fields.type <= 11)); } if (!FsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((FsArBytes.fields.dpl >= FsSelector.fields.rpl) && (FsArBytes.fields.type <= 11)); } if (!GsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((GsArBytes.fields.dpl >= GsSelector.fields.rpl) && (GsArBytes.fields.type <= 11)); } } // Check valid Type if (!SsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((SsArBytes.fields.type == 3 || SsArBytes.fields.type == 7)); } if (!DsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(DsArBytes.fields.type >= 1); } if (!EsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(EsArBytes.fields.type >= 1); } if (!FsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(FsArBytes.fields.type >= 1); } if (!GsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(GsArBytes.fields.type >= 1); } if (!CsArBytes.fields.unusable) { //Check System bit HYPERPLATFORM_ASSERT(CsArBytes.fields.system); } //Check DPL , other selector is checked by unrestricted guest .... switch (CsArBytes.fields.type) { //read/write accessed expand-up data segment case 3: if (!CsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(!CsArBytes.fields.dpl && VmSecondProcCtrl.fields.unrestricted_guest); } HYPERPLATFORM_ASSERT(!SsArBytes.fields.dpl); break; //non-conforming code segment case 9 : case 11: if (!CsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT((CsArBytes.fields.dpl == SsArBytes.fields.dpl)); } break; //conforming code segment case 13: case 15: if (!CsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(CsArBytes.fields.dpl < SsArBytes.fields.dpl); } break; } if (!cr0.fields.pe) { HYPERPLATFORM_ASSERT(!SsArBytes.fields.dpl); } //Check P bit if (!CsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(CsArBytes.fields.present); if (VmEntryCtrl.fields.ia32e_mode_guest && (CsArBytes.fields.l == 1)) { HYPERPLATFORM_ASSERT(!CsArBytes.fields.db ); } HYPERPLATFORM_ASSERT(!(CsBase >> 32)); } if (!DsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(DsArBytes.fields.present); HYPERPLATFORM_ASSERT(!DsArBytes.fields.reserved1); HYPERPLATFORM_ASSERT(!(DsBase >> 32)); } if (!EsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(EsArBytes.fields.present); HYPERPLATFORM_ASSERT(!EsArBytes.fields.reserved1); HYPERPLATFORM_ASSERT(!(EsBase >> 32)); } if (!SsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(SsArBytes.fields.present); HYPERPLATFORM_ASSERT(!SsArBytes.fields.reserved1); HYPERPLATFORM_ASSERT(!(SsBase >> 32)); } if (!FsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(FsArBytes.fields.present); HYPERPLATFORM_ASSERT(!FsArBytes.fields.reserved1); HYPERPLATFORM_ASSERT(UtilpIsCanonicalFormAddress((void*)FsBase)); } if (!GsArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(GsArBytes.fields.present); HYPERPLATFORM_ASSERT(!GsArBytes.fields.reserved1); HYPERPLATFORM_ASSERT(UtilpIsCanonicalFormAddress((void*)GsBase)); } if (!TrArBytes.fields.unusable) { HYPERPLATFORM_ASSERT(TrArBytes.fields.type == 3 || TrArBytes.fields.type == 11); HYPERPLATFORM_ASSERT(UtilpIsCanonicalFormAddress((void*)TrBase)); HYPERPLATFORM_ASSERT(!TrArBytes.fields.system && TrArBytes.fields.present && !TrArBytes.fields.unusable && !TrArBytes.fields.reserved2); } //NT_ASSERT(!LdtrArBytes.fields.unusable && (LdtrArBytes.fields.type == 2) && !LdtrArBytes.fields.system && LdtrArBytes.fields.present && !LdtrArBytes.fields.reserved1 && !LdtrArBytes.fields.reserved2); } } //------------------------------------------------------------------------------------------------// VOID VmxVmEntryCheckGuestDescTableReg() /*++ Desscription: Validating VMCS0-2 Descriptor Table register for vmentry to L2 during emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { ULONG64 GdtrBase = { UtilVmRead64(VmcsField::kGuestGdtrBase) }; ULONG64 IdtrBase = { UtilVmRead64(VmcsField::kGuestIdtrBase) }; ULONG GdtrLimit = UtilVmRead(VmcsField::kGuestGdtrLimit); ULONG IdtrLimit = UtilVmRead(VmcsField::kGuestIdtrLimit); HYPERPLATFORM_ASSERT(UtilpIsCanonicalFormAddress((void*)GdtrBase) && UtilpIsCanonicalFormAddress((void*)IdtrBase)); HYPERPLATFORM_ASSERT(!((GdtrLimit >> 16) & 0xFFFF)); HYPERPLATFORM_ASSERT(!((IdtrLimit >> 16) & 0xFFFF)); } //------------------------------------------------------------------------------------------------// VOID VmxVmEntryCheckGuestRipRflags() /*++ Desscription: Validating VMCS0-2 rip and rflags register for vmentry to L2 during emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { VmxVmEntryControls VmEntryCtrl = { UtilVmRead64(VmcsField::kVmEntryControls) }; VmxSegmentDescriptorAccessRight CsArBytes = { UtilVmRead(VmcsField::kGuestCsArBytes) }; VmxSecondaryProcessorBasedControls VmSecondProcCtrl = { UtilVmRead64(VmcsField::kSecondaryVmExecControl) }; VmEntryInterruptionInformationField VmInterruptField = { UtilVmRead64(VmcsField::kVmEntryIntrInfoField) }; FlagRegister rflags = { UtilVmRead64(VmcsField::kGuestRflags) }; Cr0 cr0 = { UtilVmRead(VmcsField::kGuestCr0) }; //Check Rip if (!VmEntryCtrl.fields.ia32e_mode_guest || !CsArBytes.fields.l) { HYPERPLATFORM_ASSERT(!(UtilVmRead64(VmcsField::kGuestRip) >> 32)); } //Check Rflags HYPERPLATFORM_ASSERT(rflags.fields.reserved1); HYPERPLATFORM_ASSERT(!rflags.fields.reserved3 && !rflags.fields.reserved2 && !rflags.fields.reserved4 && !rflags.fields.reserved5); if (VmEntryCtrl.fields.ia32e_mode_guest || !cr0.fields.pe) { HYPERPLATFORM_ASSERT(!rflags.fields.vm); } HYPERPLATFORM_ASSERT(!rflags.fields.reserved3 && !rflags.fields.reserved2 && !rflags.fields.reserved4 && !rflags.fields.reserved5); if (VmInterruptField.fields.valid && (VmInterruptField.fields.interruption_type == static_cast<ULONG32>(InterruptionType::kExternalInterrupt))) { HYPERPLATFORM_ASSERT(rflags.fields.intf); } } //------------------------------------------------------------------------------------------------// VOID VmxVmEntryCheckGuestNonRegstate() /*++ Desscription: Validating VMCS0-2 non-register for vmentry to L2 during emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { ActivityState state = static_cast<ActivityState>(UtilVmRead64(VmcsField::kGuestActivityState)); VmxSegmentDescriptorAccessRight SsArBytes = { UtilVmRead(VmcsField::kGuestSsArBytes) }; VmEntryInterruptionInformationField IntrInfo = { UtilVmRead(VmcsField::kVmEntryIntrInfoField) }; VmxVmEntryControls VmEntryCtrl = { UtilVmRead64(VmcsField::kVmEntryControls) }; HYPERPLATFORM_ASSERT(state >= 0 && state <=3); if (SsArBytes.fields.dpl) { HYPERPLATFORM_ASSERT(state != HLT); } if (IntrInfo.fields.valid) { // TODO : CHECK and disable / pending the interruption switch (state) { case HLT: break; case ShutDown: break; case WaitForSipi: break; case Active: default: break; } } if (VmEntryCtrl.fields.entry_to_smm) { HYPERPLATFORM_ASSERT(state != WaitForSipi); } } //------------------------------------------------------------------------------------------------// VOID VmxVmEntryCheckGuestPdptes() { if(VmxIsGuestPaePaging()) { } } //------------------------------------------------------------------------------------------------// VOID VmEntryCheck() { VmxVmEntryCheckGuestReg(); VmxVmEntryCheckGuestSegReg(); VmxVmEntryCheckGuestDescTableReg(); VmxVmEntryCheckGuestRipRflags(); VmxVmEntryCheckGuestNonRegstate(); } //------------------------------------------------------------------------------------------------// NTSTATUS SaveExceptionInformationFromVmcs02(VCPUVMX* vcpu) /*++ Descritpion: 1. Call before emulate a VMExit, Read All VMExit related-Information From VMCS0-2, And backup it into VMCS1-2, the purpose is for emulate VMExit, 2. Actually the Emulation of VMExit is that we RESUME the L0 to L1, so when L1 make any VMREAD/WRITE, will trap by us, we return a VMCS1-2 to its. Parameters: 1. VMExit Reason 2. Physical Address for VMCS1-2 --*/ { ULONG_PTR vmcs12_va = 0; //all nested vm-exit should record if (!vcpu) { return STATUS_UNSUCCESSFUL; } if (!vcpu->vmcs12_pa) { return STATUS_UNSUCCESSFUL; } vmcs12_va = (ULONG_PTR)UtilVaFromPa(vcpu->vmcs12_pa); if (!vmcs12_va) { return STATUS_UNSUCCESSFUL; } const VmExitInformation exit_reason = {UtilVmRead(VmcsField::kVmExitReason)}; const VmExitInterruptionInformationField exception = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmExitIntrInfo)) }; ULONG_PTR vmexit_qualification = UtilVmRead(VmcsField::kExitQualification); VmcsVmWrite32(VmcsField::kVmExitIntrInfo, vmcs12_va, exception.all); VmcsVmWrite32(VmcsField::kVmExitReason, vmcs12_va, exit_reason.all); VmcsVmWrite32(VmcsField::kExitQualification, vmcs12_va, vmexit_qualification); VmcsVmWrite32(VmcsField::kVmExitInstructionLen, vmcs12_va, UtilVmRead(VmcsField::kVmExitInstructionLen)); VmcsVmWrite32(VmcsField::kVmInstructionError, vmcs12_va, UtilVmRead(VmcsField::kVmInstructionError)); VmcsVmWrite32(VmcsField::kVmExitIntrErrorCode, vmcs12_va, UtilVmRead(VmcsField::kVmExitIntrErrorCode)); VmcsVmWrite32(VmcsField::kIdtVectoringInfoField, vmcs12_va, UtilVmRead(VmcsField::kIdtVectoringInfoField)); VmcsVmWrite32(VmcsField::kIdtVectoringErrorCode, vmcs12_va, UtilVmRead(VmcsField::kIdtVectoringErrorCode)); VmcsVmWrite32(VmcsField::kVmxInstructionInfo, vmcs12_va, UtilVmRead(VmcsField::kVmxInstructionInfo)); VmcsVmWrite64(VmcsField::kGuestLinearAddress, vmcs12_va, UtilVmRead(VmcsField::kGuestLinearAddress)); VmcsVmWrite64(VmcsField::kGuestPhysicalAddress, vmcs12_va, UtilVmRead(VmcsField::kGuestPhysicalAddress)); } //------------------------------------------------------------------------------------------------// NTSTATUS SaveGuestFieldFromVmcs02(VCPUVMX* vcpu) /*++ Descritpion: Call before emulate a VMExit, Read All Guest Field From VMCS0-2, And backup into VMCS1-2, the purpose is for emulated VMExit, but actually we RESUME the VM to L1, when L1 make any VMREAD/WRITE, we return a VMCS1-2 to its. Parameters: Physical Address for VMCS1-2 --*/ { ULONG_PTR vmcs12_va = 0; //all nested vm-exit should record if(!vcpu) { return STATUS_UNSUCCESSFUL; } if (!vcpu->vmcs12_pa) { return STATUS_UNSUCCESSFUL; } vmcs12_va = (ULONG_PTR)UtilVaFromPa(vcpu->vmcs12_pa); if (!vmcs12_va) { return STATUS_UNSUCCESSFUL; } VmcsVmWrite64(VmcsField::kGuestRip, vmcs12_va, UtilVmRead(VmcsField::kGuestRip)); VmcsVmWrite64(VmcsField::kGuestRsp, vmcs12_va, UtilVmRead(VmcsField::kGuestRsp)); VmcsVmWrite64(VmcsField::kGuestCr3, vmcs12_va, UtilVmRead(VmcsField::kGuestCr3)); VmcsVmWrite64(VmcsField::kGuestCr0, vmcs12_va, UtilVmRead(VmcsField::kGuestCr0)); VmcsVmWrite64(VmcsField::kGuestCr4, vmcs12_va, UtilVmRead(VmcsField::kGuestCr4)); VmcsVmWrite64(VmcsField::kGuestDr7, vmcs12_va, UtilVmRead(VmcsField::kGuestDr7)); VmcsVmWrite64(VmcsField::kGuestRflags, vmcs12_va, UtilVmRead(VmcsField::kGuestRflags)); VmcsVmWrite16(VmcsField::kGuestEsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestEsSelector)); VmcsVmWrite16(VmcsField::kGuestCsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestCsSelector)); VmcsVmWrite16(VmcsField::kGuestSsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestSsSelector)); VmcsVmWrite16(VmcsField::kGuestDsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestDsSelector)); VmcsVmWrite16(VmcsField::kGuestFsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestFsSelector)); VmcsVmWrite16(VmcsField::kGuestGsSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestGsSelector)); VmcsVmWrite16(VmcsField::kGuestLdtrSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestLdtrSelector)); VmcsVmWrite16(VmcsField::kGuestTrSelector, vmcs12_va, UtilVmRead(VmcsField::kGuestTrSelector)); VmcsVmWrite32(VmcsField::kGuestEsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestEsLimit)); VmcsVmWrite32(VmcsField::kGuestCsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestCsLimit)); VmcsVmWrite32(VmcsField::kGuestSsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestSsLimit)); VmcsVmWrite32(VmcsField::kGuestDsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestDsLimit)); VmcsVmWrite32(VmcsField::kGuestFsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestFsLimit)); VmcsVmWrite32(VmcsField::kGuestGsLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestGsLimit)); VmcsVmWrite32(VmcsField::kGuestLdtrLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestLdtrLimit)); VmcsVmWrite32(VmcsField::kGuestTrLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestTrLimit)); VmcsVmWrite32(VmcsField::kGuestGdtrLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestGdtrLimit)); VmcsVmWrite32(VmcsField::kGuestIdtrLimit, vmcs12_va, UtilVmRead(VmcsField::kGuestIdtrLimit)); VmcsVmWrite32(VmcsField::kGuestEsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestEsArBytes)); VmcsVmWrite32(VmcsField::kGuestCsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestCsArBytes)); VmcsVmWrite32(VmcsField::kGuestSsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestSsArBytes)); VmcsVmWrite32(VmcsField::kGuestDsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestDsArBytes)); VmcsVmWrite32(VmcsField::kGuestFsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestFsArBytes)); VmcsVmWrite32(VmcsField::kGuestGsArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestGsArBytes)); VmcsVmWrite32(VmcsField::kGuestLdtrArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestLdtrArBytes)); VmcsVmWrite32(VmcsField::kGuestTrArBytes, vmcs12_va, UtilVmRead(VmcsField::kGuestTrArBytes)); VmcsVmWrite32(VmcsField::kGuestInterruptibilityInfo, vmcs12_va, UtilVmRead(VmcsField::kGuestInterruptibilityInfo)); VmcsVmWrite32(VmcsField::kGuestActivityState, vmcs12_va, UtilVmRead(VmcsField::kGuestActivityState)); VmcsVmWrite32(VmcsField::kGuestSysenterCs, vmcs12_va, UtilVmRead(VmcsField::kGuestSysenterCs)); VmcsVmWrite64(VmcsField::kGuestSysenterEsp, vmcs12_va, UtilVmRead(VmcsField::kGuestSysenterEsp)); VmcsVmWrite64(VmcsField::kGuestSysenterEip, vmcs12_va, UtilVmRead(VmcsField::kGuestSysenterEip)); VmcsVmWrite64(VmcsField::kGuestPendingDbgExceptions, vmcs12_va, UtilVmRead(VmcsField::kGuestPendingDbgExceptions)); VmcsVmWrite64(VmcsField::kGuestEsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestEsBase)); VmcsVmWrite64(VmcsField::kGuestCsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestCsBase)); VmcsVmWrite64(VmcsField::kGuestSsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestSsBase)); VmcsVmWrite64(VmcsField::kGuestDsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestDsBase)); VmcsVmWrite64(VmcsField::kGuestFsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestFsBase)); VmcsVmWrite64(VmcsField::kGuestGsBase, vmcs12_va, UtilVmRead(VmcsField::kGuestGsBase)); VmcsVmWrite64(VmcsField::kGuestLdtrBase, vmcs12_va, UtilVmRead(VmcsField::kGuestLdtrBase)); VmcsVmWrite64(VmcsField::kGuestTrBase, vmcs12_va, UtilVmRead(VmcsField::kGuestTrBase)); VmcsVmWrite64(VmcsField::kGuestGdtrBase, vmcs12_va, UtilVmRead(VmcsField::kGuestGdtrBase)); VmcsVmWrite64(VmcsField::kGuestIdtrBase, vmcs12_va, UtilVmRead(VmcsField::kGuestIdtrBase)); VmcsVmWrite64(VmcsField::kGuestIa32Efer, vmcs12_va, UtilVmRead(VmcsField::kGuestIa32Efer)); /* VmcsVmWrite64(VmcsField::kGuestPdptr0, vmcs12_va, UtilVmRead(VmcsField::kGuestPdptr0)); VmcsVmWrite64(VmcsField::kGuestPdptr1, vmcs12_va, UtilVmRead(VmcsField::kGuestPdptr1)); VmcsVmWrite64(VmcsField::kGuestPdptr2, vmcs12_va, UtilVmRead(VmcsField::kGuestPdptr2)); VmcsVmWrite64(VmcsField::kGuestPdptr3, vmcs12_va, UtilVmRead(VmcsField::kGuestPdptr3)); */ } //------------------------------------------------------------------------------------------------// NTSTATUS LoadHostStateForLevel1( _In_ VCPUVMX* vcpu ) /*++ Descritpion: Load VMCS1-2 into VMCS0-1 Parameters: VCPUVMX --*/ { ULONG_PTR Vmcs01_pa = 0; ULONG_PTR Vmcs12_va = 0; if (!vcpu || !vcpu->vmcs01_pa || !vcpu->vmcs12_pa) { HYPERPLATFORM_COMMON_DBG_BREAK(); return STATUS_UNSUCCESSFUL; } Vmcs01_pa = vcpu->vmcs01_pa; Vmcs12_va = (ULONG_PTR)UtilVaFromPa(vcpu->vmcs12_pa); if (!Vmcs01_pa || !Vmcs12_va) { HYPERPLATFORM_COMMON_DBG_BREAK(); return STATUS_UNSUCCESSFUL; } VmxStatus status; // Host Data Field ULONG64 VMCS12_HOST_RIP = 0; ULONG64 VMCS12_HOST_STACK = 0; ULONG_PTR VMCS12_HOST_RFLAGs = 0; ULONG64 VMCS12_HOST_CR4 = 0; ULONG64 VMCS12_HOST_CR3 = 0; ULONG64 VMCS12_HOST_CR0 = 0; ULONG64 VMCS12_HOST_CS = 0; ULONG64 VMCS12_HOST_SS = 0; ULONG64 VMCS12_HOST_DS = 0; ULONG64 VMCS12_HOST_ES = 0; ULONG64 VMCS12_HOST_FS = 0; ULONG64 VMCS12_HOST_GS = 0; ULONG64 VMCS12_HOST_TR = 0; ULONG32 VMCS12_HOST_SYSENTER_CS = 0; ULONG64 VMCS12_HOST_SYSENTER_RIP = 0; ULONG64 VMCS12_HOST_SYSENTER_RSP = 0; ULONG64 VMCS12_HOST_FS_BASE = 0; ULONG64 VMCS12_HOST_GS_BASE = 0; ULONG64 VMCS12_HOST_TR_BASE = 0; if (VmxStatus::kOk != (status = static_cast<VmxStatus>(__vmx_vmptrld(&Vmcs01_pa)))) { VmxInstructionError error = static_cast<VmxInstructionError>(UtilVmRead(VmcsField::kVmInstructionError)); HYPERPLATFORM_LOG_DEBUG_SAFE("Error vmptrld error code :%x , %x", status, error); } VmcsVmRead64(VmcsField::kHostRip, Vmcs12_va, &VMCS12_HOST_RIP); VmcsVmRead64(VmcsField::kHostRsp, Vmcs12_va, &VMCS12_HOST_STACK); VmcsVmRead64(VmcsField::kHostCr0, Vmcs12_va, &VMCS12_HOST_CR0); VmcsVmRead64(VmcsField::kHostCr3, Vmcs12_va, &VMCS12_HOST_CR3); VmcsVmRead64(VmcsField::kHostCr4, Vmcs12_va, &VMCS12_HOST_CR4); VmcsVmRead64(VmcsField::kHostCsSelector, Vmcs12_va, &VMCS12_HOST_CS); VmcsVmRead64(VmcsField::kHostSsSelector, Vmcs12_va, &VMCS12_HOST_SS); VmcsVmRead64(VmcsField::kHostDsSelector, Vmcs12_va, &VMCS12_HOST_DS); VmcsVmRead64(VmcsField::kHostEsSelector, Vmcs12_va, &VMCS12_HOST_ES); VmcsVmRead64(VmcsField::kHostFsSelector, Vmcs12_va, &VMCS12_HOST_FS); VmcsVmRead64(VmcsField::kHostGsSelector, Vmcs12_va, &VMCS12_HOST_GS); VmcsVmRead64(VmcsField::kHostTrSelector, Vmcs12_va, &VMCS12_HOST_TR); VmcsVmRead32(VmcsField::kHostIa32SysenterCs, Vmcs12_va, &VMCS12_HOST_SYSENTER_CS); VmcsVmRead64(VmcsField::kHostIa32SysenterEip, Vmcs12_va, &VMCS12_HOST_SYSENTER_RSP); VmcsVmRead64(VmcsField::kHostIa32SysenterEsp, Vmcs12_va, &VMCS12_HOST_SYSENTER_RIP); VmcsVmRead64(VmcsField::kHostFsBase, Vmcs12_va, &VMCS12_HOST_FS_BASE); VmcsVmRead64(VmcsField::kHostGsBase, Vmcs12_va, &VMCS12_HOST_GS_BASE); VmcsVmRead64(VmcsField::kHostTrBase, Vmcs12_va, &VMCS12_HOST_TR_BASE); //Disable Interrupt Flags FlagRegister rflags = { VMCS12_HOST_RFLAGs }; rflags.fields.reserved1 = 1; UtilVmWrite(VmcsField::kGuestRflags, rflags.all); UtilVmWrite(VmcsField::kGuestRip, VMCS12_HOST_RIP); UtilVmWrite(VmcsField::kGuestRsp, VMCS12_HOST_STACK); UtilVmWrite(VmcsField::kGuestCr0, VMCS12_HOST_CR0); UtilVmWrite(VmcsField::kGuestCr3, VMCS12_HOST_CR3); UtilVmWrite(VmcsField::kGuestCr4, VMCS12_HOST_CR4); UtilVmWrite(VmcsField::kGuestDr7, 0x400); UtilVmWrite(VmcsField::kGuestCsSelector, VMCS12_HOST_CS); UtilVmWrite(VmcsField::kGuestSsSelector, VMCS12_HOST_SS); UtilVmWrite(VmcsField::kGuestDsSelector, VMCS12_HOST_DS); UtilVmWrite(VmcsField::kGuestEsSelector, VMCS12_HOST_ES); UtilVmWrite(VmcsField::kGuestFsSelector, VMCS12_HOST_FS); UtilVmWrite(VmcsField::kGuestGsSelector, VMCS12_HOST_GS); UtilVmWrite(VmcsField::kGuestTrSelector, VMCS12_HOST_TR); UtilVmWrite(VmcsField::kGuestSysenterCs, VMCS12_HOST_SYSENTER_CS); UtilVmWrite(VmcsField::kGuestSysenterEsp, VMCS12_HOST_SYSENTER_RSP); UtilVmWrite(VmcsField::kGuestSysenterEip, VMCS12_HOST_SYSENTER_RIP); // Sync L1's Host segment base with L0 VMM Host Host segment base UtilVmWrite(VmcsField::kGuestCsBase, 0); UtilVmWrite(VmcsField::kGuestSsBase, 0); UtilVmWrite(VmcsField::kGuestDsBase, 0); UtilVmWrite(VmcsField::kGuestEsBase, 0); UtilVmWrite(VmcsField::kGuestFsBase, VMCS12_HOST_FS_BASE); UtilVmWrite(VmcsField::kGuestGsBase, VMCS12_HOST_GS_BASE); UtilVmWrite(VmcsField::kGuestTrBase, VMCS12_HOST_TR_BASE); // Sync L1's Host Host segment Limit with L0 Host Host segment Limit UtilVmWrite(VmcsField::kGuestEsLimit, GetSegmentLimit(AsmReadES())); UtilVmWrite(VmcsField::kGuestCsLimit, GetSegmentLimit(AsmReadCS())); UtilVmWrite(VmcsField::kGuestSsLimit, GetSegmentLimit(AsmReadSS())); UtilVmWrite(VmcsField::kGuestDsLimit, GetSegmentLimit(AsmReadDS())); UtilVmWrite(VmcsField::kGuestFsLimit, GetSegmentLimit(AsmReadFS())); UtilVmWrite(VmcsField::kGuestGsLimit, GetSegmentLimit(AsmReadGS())); UtilVmWrite(VmcsField::kGuestLdtrLimit, GetSegmentLimit(AsmReadLDTR())); UtilVmWrite(VmcsField::kGuestTrLimit, GetSegmentLimit(AsmReadTR())); // Sync L1's Host segment ArBytes with L0 Host segment ArBytes UtilVmWrite(VmcsField::kGuestEsArBytes, VmpGetSegmentAccessRight(AsmReadES())); UtilVmWrite(VmcsField::kGuestCsArBytes, VmpGetSegmentAccessRight(AsmReadCS())); UtilVmWrite(VmcsField::kGuestSsArBytes, VmpGetSegmentAccessRight(AsmReadSS())); UtilVmWrite(VmcsField::kGuestDsArBytes, VmpGetSegmentAccessRight(AsmReadDS())); UtilVmWrite(VmcsField::kGuestFsArBytes, VmpGetSegmentAccessRight(AsmReadFS())); UtilVmWrite(VmcsField::kGuestGsArBytes, VmpGetSegmentAccessRight(AsmReadGS())); UtilVmWrite(VmcsField::kGuestLdtrArBytes, VmpGetSegmentAccessRight(AsmReadLDTR())); UtilVmWrite(VmcsField::kGuestTrArBytes, VmpGetSegmentAccessRight(AsmReadTR()) | LONG_MODE_BUSY_TSS); UtilVmWrite(VmcsField::kGuestIa32Debugctl, 0); //Clean VMCS1-2 Injecting event since it shouldn't be injected VmcsVmWrite32(VmcsField::kVmEntryIntrInfoField, Vmcs12_va, 0); VmcsVmWrite32(VmcsField::kVmEntryExceptionErrorCode, Vmcs12_va, 0); UtilVmWrite(VmcsField::kVmEntryIntrInfoField, 0); UtilVmWrite(VmcsField::kVmEntryExceptionErrorCode, 0); return STATUS_SUCCESS; } //------------------------------------------------------------------------------------------------// NTSTATUS VmxVMExitEmulate( _In_ VCPUVMX* vCPU, _In_ GuestContext* guest_context ) /*++ Description: Emulating the VMExit behavior from L2 to L1 We need to emulate the exception if and only if the vCPU mode is Guest Mode , and only the exception is somethings we want to redirect to L1 VMM to handle it. VCPU Mode as follow: Root Mode: - if the Guest's vCPU is root mode , that means he dun expected the action will be trap. so that action should not give its VMExit handler, otherwise. Guest Mode: - If the Guest's vCPU is in guest mode, that means he expected the action will be trapped And handle by its VMExit handler After this function, VCPU mode should be changed to ROOT Mode , since every other step should be worded as root mode , and We turn it back to Guest whenever L1's VMM want to do this through VMlaunch or VMResume instruction. We desginated the L1 wants to handle any breakpoint exception but the others. So that we only nested it for testing purpose. Parameters: vCPU - corresponding structure to current Virtual processor guest_context - guest context Return Value: If the vmexit's context passed, return STATUS_SUCEESS. Otherwise, return STATUS_UNSUCCESSFUL --*/ { NTSTATUS status = STATUS_UNSUCCESSFUL; do { if (!vCPU) { break; } // Since VMXON, but VMPTRLD if (!vCPU->vmcs02_pa || !vCPU->vmcs12_pa || vCPU->vmcs12_pa == ~0x0 || vCPU->vmcs02_pa == ~0x0) { //HYPERPLATFORM_LOG_DEBUG_SAFE("cannot find vmcs \r\n"); break; } LEAVE_GUEST_MODE(vCPU); SaveGuestKernelGsBase(VmmpGetProcessorData(guest_context)); LoadHostKernelGsBase(VmmpGetProcessorData(guest_context)); SaveGuestFieldFromVmcs02(vCPU); SaveExceptionInformationFromVmcs02(vCPU); SaveGuestCr8(vCPU, VmmpGetGuestCr8(guest_context)); LoadHostStateForLevel1(vCPU); status = STATUS_SUCCESS; } while (FALSE); return status; } //--------------------------------------------------------------------------------------// NTSTATUS VMEntryEmulate( _In_ VCPUVMX* vCPU, _In_ GuestContext* guest_context , _In_ BOOLEAN IsVmLaunch ) /*++ Description: Emulating VMEntry behavior from L1 to L2. After L1 handles any VM Exit and should be executes VMRESUME for back L2 But this time trapped by VMCS01 and We can't get any VM-Exit information from it. So we need to read from VMCS12 and return from here immediately. We saved the vmcs02 GuestRip into VMCS12 our VMExit Handler because when L1 was executing VMRESUME(We injected VMExit to it), and it is running on VMCS01, we can't and shouldn't change it. See: VmmVmExitHandler N.B. if the VMEntry is not passed, the control transfer to debugger or BSOD. Parameters: vCPU - corresponding structure to current Virtual processor guest_context - guest context IsVmLaunch - Indicate the Virtual-VMentry either come from VMLAUNCH or VMRESUME Return Value: If the vmentry's context passed, return STATUS_SUCEESS. Otherwise, return STATUS_UNSUCCESSFUL --*/ { ULONG_PTR vmcs02_va = 0; ULONG_PTR vmcs12_va = 0; Ia32VmxBasicMsr vmx_basic_msr = { 0 }; VmControlStructure* vmcs02_ptr = NULL; if (!vCPU) { return STATUS_UNSUCCESSFUL; } // Since VMXON, but VMPTRLD if (!vCPU->vmcs02_pa || !vCPU->vmcs12_pa || vCPU->vmcs12_pa == ~0x0 || vCPU->vmcs02_pa == ~0x0) { //HYPERPLATFORM_LOG_DEBUG_SAFE("cannot find vmcs \r\n"); return STATUS_UNSUCCESSFUL; } vmcs02_va = (ULONG_PTR)UtilVaFromPa(vCPU->vmcs02_pa); vmcs12_va = (ULONG_PTR)UtilVaFromPa(vCPU->vmcs12_pa); if (!vmcs02_va || !vmcs12_va) { return STATUS_UNSUCCESSFUL; } ENTER_GUEST_MODE(vCPU); // Write a VMCS revision identifier vmx_basic_msr = { UtilReadMsr64(Msr::kIa32VmxBasic) }; vmcs02_ptr = (VmControlStructure*)vmcs02_va; vmcs02_ptr->revision_identifier = vmx_basic_msr.fields.revision_identifier; //Prepare VMCS01 Host / Control Field VmcsPrepareHostAndControlField(vmcs12_va, vCPU->vmcs02_pa, IsVmLaunch); VmcsPrepareGuestStateField(vmcs12_va); SaveHostKernelGsBase(VmmpGetProcessorData(guest_context)); VmEntryCheck(); if (IsVmLaunch) { VmxStatus status; #ifdef __NEST_EPT_ENBLE VmxSecondaryProcessorBasedControls ProcCtrl = { UtilVmRead64(VmcsField::kSecondaryVmExecControl) }; if (ProcCtrl.fields.enable_ept) { EptData* Ept02Data=nullptr; EptData* Ept12Data=nullptr; //1. Determine if Nested EPT Enabled. EptData* Ept01Data=nullptr; //2. Build-EPT0-2 ULONG64 _Ept12Ptr = NULL; VmcsVmRead64(VmcsField::kEptPointer, vmcs12_va, &_Ept12Ptr); Ept02Data = EptBuildEptDataByEptp(); Ept12Data = EptBuildEptDataByEptp(); Ept01Data = VmmGetCurrentEpt01Pointer(guest_context); if (Ept02Data && Ept12Data && Ept01Data) { EptpBuildNestedEpt(_Ept12Ptr, Ept12Data, Ept02Data); VmmSaveCurrentEpt02Pointer(guest_context, Ept02Data); VmmSaveCurrentEpt12Pointer(guest_context, Ept12Data); EptpInvalidateEpt(Ept12Data, Ept01Data); UtilVmWrite64(VmcsField::kEptPointer, Ept02Data->ept_pointer->all); UtilInveptGlobal(); } } #endif // We must be careful of this, since we jmp back to the Guest soon. // It is a exceptional case if (VmmpGetGuestIrql(guest_context) < DISPATCH_LEVEL) { KeLowerIrql(VmmpGetGuestIrql(guest_context)); } if (VmxStatus::kOk != (status = static_cast<VmxStatus>(__vmx_vmlaunch()))) { VmxInstructionError error2 = static_cast<VmxInstructionError>(UtilVmRead(VmcsField::kVmInstructionError)); HYPERPLATFORM_LOG_DEBUG_SAFE("Error VMLAUNCH error code :%x , %x ", status, error2); HYPERPLATFORM_COMMON_DBG_BREAK(); } } else { #ifdef __NEST_EPT_ENBLE VmxSecondaryProcessorBasedControls ProcCtrl = { UtilVmRead64(VmcsField::kSecondaryVmExecControl) }; if (ProcCtrl.fields.enable_ept) { EptData* ept_data02 = VmmGetCurrentEpt02Pointer(guest_context); if (ept_data02) { UtilVmWrite64(VmcsField::kEptPointer, ept_data02->ept_pointer->all); } } #endif RestoreGuestCr8(vCPU); LoadGuestKernelGsBase(VmmpGetProcessorData(guest_context)); } return STATUS_SUCCESS; } //------------------------------------------------------------------------------------------------// VOID VmxVmxonEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating Vmxon instruction, Allocating the data structure of Virtual Processors, and initial the virtual prcoessors as VMX-root mode. Paremeters: Guest Context Return Value: NO --*/ { do { VCPUVMX* nested_vmx = NULL; ULONG64 InstructionPointer = 0; ULONG64 StackPointer = 0; ULONG64 vmxon_region_pa = 0; ULONG64 guest_address = NULL; VmControlStructure* vmxon_region_struct = NULL; PROCESSOR_NUMBER number = { 0 }; InstructionPointer = { UtilVmRead64(VmcsField::kGuestRip) }; StackPointer = { UtilVmRead64(VmcsField::kGuestRsp) }; guest_address = DecodeVmclearOrVmptrldOrVmptrstOrVmxon(guest_context); if (VmmpGetvCpuMode(guest_context) == VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode !")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (!guest_address || !UtilpIsCanonicalFormAddress((void*)guest_address)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXON: guest_address Parameter is NULL !")); //#UD ThrowInvalidCodeException(); break; } vmxon_region_pa = *(PULONG64)guest_address; // VMXON_REGION IS NULL if (!vmxon_region_pa) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXON: vmxon_region_pa Parameter is NULL !")); //#UD ThrowInvalidCodeException(); break; } //if is it not page aglined if (!CheckPageAlgined(vmxon_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXON: not page aligned physical address %I64X !"), vmxon_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } //if IA32_VMX_BASIC[48] == 1 it is not support 64bit addressing, so address[32] to address[63] supposed = 0 if (!CheckPhysicalAddress(vmxon_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXON: invalid physical address %I64X !"), vmxon_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } // todo: check vcpu context ...' nested_vmx = (VCPUVMX*)ExAllocatePool(NonPagedPoolNx, sizeof(VCPUVMX)); nested_vmx->inRoot = RootMode; nested_vmx->blockINITsignal = TRUE; nested_vmx->blockAndDisableA20M = TRUE; nested_vmx->vmcs02_pa = 0xFFFFFFFFFFFFFFFF; nested_vmx->vmcs12_pa = 0xFFFFFFFFFFFFFFFF; __vmx_vmptrst(&nested_vmx->vmcs01_pa); nested_vmx->vmxon_region = vmxon_region_pa; nested_vmx->InitialCpuNumber = KeGetCurrentProcessorNumberEx(&number); // vcpu etner vmx-root mode now VmmpEnterVmxMode(guest_context); VmmpSetvCpuVmx(guest_context, nested_vmx); HYPERPLATFORM_LOG_DEBUG("VMXON: Guest Instruction Pointer %I64X Guest Stack Pointer: %I64X Guest VMXON_Region: %I64X stored at %I64x physical address\r\n", InstructionPointer, StackPointer, vmxon_region_pa, guest_address); HYPERPLATFORM_LOG_DEBUG("VMXON: Run Successfully with VMXON_Region: %I64X Total Vitrualized Core: %x Current Cpu: %x in Cpu Group : %x Number: %x \r\n", vmxon_region_pa, nested_vmx->InitialCpuNumber, number.Group, number.Number); BuildGernericVMCSMap(); VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmxoffEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating Vmxoff instruction , releasing the data structure of Virtual Processors, and initial the virtual prcoessors as VMX-root mode. Paremeters: Guest Context Return Value: NO --*/ { do { VCPUVMX* vcpu_vmx = NULL; HYPERPLATFORM_COMMON_DBG_BREAK(); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } vcpu_vmx = VmmpGetVcpuVmx(guest_context); if (!vcpu_vmx) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Don't have Nested vCPU ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG_SAFE(("Vmxoff: Unimplemented third level virualization \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } ULONG GuestRip = UtilVmRead(VmcsField::kGuestRip); ULONG InstLen = UtilVmRead(VmcsField::kVmExitInstructionLen); //load back vmcs01 __vmx_vmptrld(&vcpu_vmx->vmcs01_pa); EptData* ept_data01 = VmmGetCurrentEpt01Pointer(guest_context); EptData* ept_data12 = VmmGetCurrentEpt12Pointer(guest_context); if (ept_data01 && ept_data12) { EptpValidateEpt(ept_data12, ept_data01); ExFreePool(ept_data12); ept_data12 = nullptr; } VmmSaveCurrentEpt02Pointer(guest_context, nullptr); VmmSaveCurrentEpt12Pointer(guest_context, nullptr); UtilVmWrite(VmcsField::kGuestRip, GuestRip + InstLen); VmmpSetvCpuVmx(guest_context, NULL); VmmpLeaveVmxMode(guest_context); ExFreePool(vcpu_vmx); vcpu_vmx = NULL; HYPERPLATFORM_LOG_DEBUG("VMXOFF Stopped Nested Virtualization, and Back to Normal Guest OS "); VMSucceed(VmmpGetFlagReg(guest_context)); } while (0); } //------------------------------------------------------------------------------------------------// VOID VmxVmclearEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMClear instruction, We basically clear the VMCS0-2 which is transparent to the L1's VMM, because we need to load this VMCS into the real processors. So we need to make an effect on them. Paremeters: Guest Context Return Value: NO --*/ { do { //*(PULONG64)(StackPointer + offset); //May need to be fixed later VCPUVMX* nested_vmx = NULL; ULONG64 InstructionPointer = 0; ULONG64 StackPointer = 0; ULONG64 vmcs_region_pa = 0; ULONG64 guest_address = NULL; PROCESSOR_NUMBER procnumber = { 0 }; InstructionPointer = { UtilVmRead64(VmcsField::kGuestRip) }; StackPointer = { UtilVmRead64(VmcsField::kGuestRsp) }; guest_address = DecodeVmclearOrVmptrldOrVmptrstOrVmxon(guest_context); if (!guest_address || !UtilpIsCanonicalFormAddress((void*)guest_address)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR: guest_address NULL ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } vmcs_region_pa = *(PULONG64)guest_address; if (!vmcs_region_pa) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR: vmcs_region_pa NULL ! \r\n")); ThrowInvalidCodeException(); break; } if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR: Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR : Unimplemented third level virualization \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } nested_vmx = VmmpGetVcpuVmx(guest_context); if (!nested_vmx) { DumpVcpu(guest_context); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } //if is it not page aglined if (!CheckPageAlgined(vmcs_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXCLEAR: not page aligned physical address %I64X ! \r\n"), vmcs_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } //if IA32_VMX_BASIC[48] == 1 it is not support 64bit addressing, so address[32] to address[63] supposed = 0 if (!CheckPhysicalAddress(vmcs_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXCLEAR: invalid physical address %I64X ! \r\n"), vmcs_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } //if vmcs != vmregion if (nested_vmx && (vmcs_region_pa == nested_vmx->vmxon_region)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMXCLEAR: VMCS region %I64X same as VMXON region %I64X ! \r\n"), vmcs_region_pa, nested_vmx->vmxon_region); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (vmcs_region_pa == nested_vmx->vmcs12_pa) { nested_vmx->vmcs12_pa = 0xFFFFFFFFFFFFFFFF; } __vmx_vmclear(&nested_vmx->vmcs02_pa); nested_vmx->vmcs02_pa = 0xFFFFFFFFFFFFFFFF; HYPERPLATFORM_LOG_DEBUG_SAFE("VMCLEAR: Guest Instruction Pointer %I64X Guest Stack Pointer: %I64X Guest vmcs region: %I64X stored at %I64x on stack\r\n", InstructionPointer, StackPointer, vmcs_region_pa, guest_address); HYPERPLATFORM_LOG_DEBUG_SAFE("VMCLEAR: Run Successfully Current Cpu: %x in Cpu Group : %x Number: %x \r\n", nested_vmx->InitialCpuNumber, procnumber.Group, procnumber.Number); HYPERPLATFORM_LOG_DEBUG_SAFE("VMCLEAR: VCPU No.: %i Current VMCS : %I64X VMXON Region : %I64X ", nested_vmx->InitialCpuNumber, nested_vmx->vmcs02_pa, nested_vmx->vmxon_region); VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmptrldEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMPTRLD instruction , We basically initial the corresponding EPT to the virtual processor with VMCS1-2 Paremeters: Guest Context Return Value: NO --*/ { do { VCPUVMX* nested_vmx = NULL; ULONG64 InstructionPointer = 0; ULONG64 StackPointer = 0; PUCHAR vmcs02_region_va = NULL; ULONG64 vmcs02_region_pa = NULL; ULONG64 vmcs12_region_pa = 0; ULONG64 guest_address = NULL; PROCESSOR_NUMBER procnumber = { 0 }; InstructionPointer = { UtilVmRead64(VmcsField::kGuestRip) }; StackPointer = { UtilVmRead64(VmcsField::kGuestRsp) }; guest_address = DecodeVmclearOrVmptrldOrVmptrstOrVmxon(guest_context); if (!guest_address || !UtilpIsCanonicalFormAddress((void*)guest_address)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR: guest_address NULL ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } vmcs12_region_pa = *(PULONG64)guest_address; if (!vmcs12_region_pa) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMCLEAR: vmcs_region_pa NULL ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG_SAFE("VMPTRLD Unimplemented third level virualization %I64x \r\n", VmmpGetVcpuVmx(guest_context)); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } //if is it not page aglined if (!CheckPageAlgined(vmcs12_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMPTRLD: not page aligned physical address %I64X ! \r\n"), vmcs12_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } //if IA32_VMX_BASIC[48] == 1 it is not support 64bit addressing, so address[32] to address[63] supposed = 0 if (!CheckPhysicalAddress(vmcs12_region_pa)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMPTRLD: invalid physical address %I64X ! \r\n"), vmcs12_region_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } nested_vmx = VmmpGetVcpuVmx(guest_context); if (nested_vmx && (vmcs12_region_pa == nested_vmx->vmxon_region)) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMPTRLD: VMCS region %I64X same as VMXON region %I64X ! \r\n"), vmcs12_region_pa, nested_vmx->vmxon_region); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } vmcs02_region_va = (PUCHAR)ExAllocatePool(NonPagedPoolNx, PAGE_SIZE); if (!vmcs02_region_va) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMPTRLD: vmcs02_region_va NULL ! \r\n"), vmcs12_region_pa, nested_vmx->vmxon_region); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } RtlZeroMemory(vmcs02_region_va, PAGE_SIZE); vmcs02_region_pa = UtilPaFromVa(vmcs02_region_va); nested_vmx->vmcs02_pa = vmcs02_region_pa; //vmcs02' physical address - DIRECT VMREAD/WRITE nested_vmx->vmcs12_pa = vmcs12_region_pa; //vmcs12' physical address - we will control its structure in Vmread/Vmwrite nested_vmx->kVirtualProcessorId = (USHORT)KeGetCurrentProcessorNumberEx(nullptr) + 1; HYPERPLATFORM_LOG_DEBUG_SAFE("[VMPTRLD] Run Successfully \r\n"); HYPERPLATFORM_LOG_DEBUG_SAFE("[VMPTRLD] VMCS02 PA: %I64X VA: %I64X \r\n", vmcs02_region_pa, vmcs02_region_va); HYPERPLATFORM_LOG_DEBUG_SAFE("[VMPTRLD] VMCS12 PA: %I64X \r\n", vmcs12_region_pa); HYPERPLATFORM_LOG_DEBUG_SAFE("[VMPTRLD] VMCS01 PA: %I64X VA: %I64X \r\n", nested_vmx->vmcs01_pa, UtilVaFromPa(nested_vmx->vmcs01_pa)); HYPERPLATFORM_LOG_DEBUG_SAFE("[VMPTRLD] Current Cpu: %x in Cpu Group : %x Number: %x \r\n", nested_vmx->InitialCpuNumber, procnumber.Group, procnumber.Number); VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmreadEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMRead instruction , we are passing through the contents of paremeter, to the VMCS1-2, L1's VMM doesn't realize the effect is not making on the VMCS0-2, however, that is not really loaded into physical processor. But it is used to be a material for producing the VMCS0-2 Paremeters: Guest Context Return Value: NO --*/ { do { VmcsField field; ULONG_PTR offset; ULONG_PTR value; BOOLEAN RorM; ULONG_PTR regIndex; ULONG_PTR memAddress; PROCESSOR_NUMBER procnumber = { 0 }; VCPUVMX* NestedvCPU = VmmpGetVcpuVmx(guest_context); ULONG64 vmcs12_pa = NestedvCPU->vmcs12_pa; ULONG64 vmcs12_va = (ULONG64)UtilVaFromPa(vmcs12_pa); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (!NestedvCPU) { DumpVcpu(guest_context); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG(" Vmread: Unimplemented third level virualization VMX: %I64x VMCS12: %I64x \r\n", VmmpGetVcpuVmx(guest_context), vmcs12_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } field = VmcsDecodeVmwriteOrVmRead(VmmpGetGpReg(guest_context), &offset, &value, &RorM, &regIndex, &memAddress); if (!is_vmcs_field_supported(field)) { HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD: Virtual VT-x is not supported this feature [field: %I64X] \r\n", field); //#gp VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if ((ULONG64)vmcs12_va == 0xFFFFFFFFFFFFFFFF) { HYPERPLATFORM_LOG_DEBUG_SAFE(("VMREAD: 0xFFFFFFFFFFFFFFFF ! \r\n")); //#gp VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } auto operand_size = VMCS_FIELD_WIDTH((int)field); if (RorM) { auto reg = VmmpSelectRegister((ULONG)regIndex, guest_context); if (operand_size == VMCS_FIELD_WIDTH_16BIT) { VmcsVmRead16(field, vmcs12_va, (PUSHORT)reg); HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD16: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PUSHORT)reg); } if (operand_size == VMCS_FIELD_WIDTH_32BIT) { VmcsVmRead32(field, vmcs12_va, (PULONG32)reg); HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD32: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PULONG32)reg); } if (operand_size == VMCS_FIELD_WIDTH_64BIT || operand_size == VMCS_FIELD_WIDTH_NATURAL_WIDTH) { VmcsVmRead64(field, vmcs12_va, (PULONG64)reg); HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD64: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PULONG64)reg); } } else { if (operand_size == VMCS_FIELD_WIDTH_16BIT) { VmcsVmRead16(field, vmcs12_va, (PUSHORT)memAddress); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD16: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PUSHORT)memAddress); } if (operand_size == VMCS_FIELD_WIDTH_32BIT) { VmcsVmRead32(field, vmcs12_va, (PULONG32)memAddress); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD32: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PULONG32)memAddress); } if (operand_size == VMCS_FIELD_WIDTH_64BIT || operand_size == VMCS_FIELD_WIDTH_NATURAL_WIDTH) { VmcsVmRead64(field, vmcs12_va, (PULONG64)memAddress); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMREAD64: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, *(PULONG64)memAddress); } } VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmwriteEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMWrite instruction , we are passing through the contents of paremeter, to the VMCS1-2, L1's VMM doesn't realize the effect is not making on the VMCS0-2, however, that is not really loaded into physical processor. But it is used to be a material for producing the VMCS0-2. Paremeters: Guest Context Return Value: NO --*/ { do { VmcsField field; ULONG_PTR offset; ULONG_PTR Value; BOOLEAN RorM; PROCESSOR_NUMBER procnumber = { 0 }; VCPUVMX* NestedvCPU = VmmpGetVcpuVmx(guest_context); ULONG64 vmcs12_pa = (ULONG64)NestedvCPU->vmcs12_pa; ULONG64 vmcs12_va = (ULONG64)UtilVaFromPa(vmcs12_pa); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE((" Vmwrite: Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG(" Vmwrite: Unimplemented third level virualization VMX: %I64x VMCS12: %I64x \r\n", VmmpGetVcpuVmx(guest_context), vmcs12_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (!NestedvCPU) { DumpVcpu(guest_context); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } ///TODO: If in VMX non-root operation, should be VM Exit field = VmcsDecodeVmwriteOrVmRead(VmmpGetGpReg(guest_context), &offset, &Value, &RorM); if (!is_vmcs_field_supported(field)) { HYPERPLATFORM_LOG_DEBUG_SAFE("VMWRITE: IS NOT SUPPORT %X ! \r\n", field); //#gp VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } /*if (!g_vcpus[vcpu_index]->inRoot) { ///TODO: Should INJECT vmexit to L1 /// And Handle it well break; }*/ auto operand_size = VMCS_FIELD_WIDTH((int)field); if (operand_size == VMCS_FIELD_WIDTH_16BIT) { VmcsVmWrite16(field, vmcs12_va, Value); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMWRITE: field: %I64X base: %I64X Offset: %I64X Value: %I64X \r\n", field, vmcs12_va, offset, (USHORT)Value); } if (operand_size == VMCS_FIELD_WIDTH_32BIT) { VmcsVmWrite32(field, vmcs12_va, Value); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMWRITE: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, (ULONG32)Value); } if (operand_size == VMCS_FIELD_WIDTH_64BIT || operand_size == VMCS_FIELD_WIDTH_NATURAL_WIDTH) { VmcsVmWrite64(field, vmcs12_va, Value); //HYPERPLATFORM_LOG_DEBUG_SAFE("VMWRITE: field: %I64X base: %I64X Offset: %I64X Value: %I64X\r\n", field, vmcs12_va, offset, (ULONG64)Value); } VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmlaunchEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMLaunch instruction , start the emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { PROCESSOR_NUMBER procnumber = { 0 }; VCPUVMX* NestedvCPU = VmmpGetVcpuVmx(guest_context); VmxStatus status; do { HYPERPLATFORM_COMMON_DBG_BREAK(); HYPERPLATFORM_LOG_DEBUG_SAFE("-----start vmlaunch---- \r\n"); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (!NestedvCPU) { DumpVcpu(guest_context); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG(" Vmlaunch: Unimplemented third level virualization VMX: %I64x VMCS12: %I64x \r\n", VmmpGetVcpuVmx(guest_context), NestedvCPU->vmcs12_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } VMEntryEmulate(NestedvCPU, guest_context, TRUE); HYPERPLATFORM_LOG_DEBUG_SAFE("Error VMLAUNCH error code :%x , %x ", 0, 0); return; } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmresumeEmulate( _In_ GuestContext* guest_context ) /*++ Desscription: Emulating VMLaunch instruction , start the emulation of the VMEntry Paremeters: Guest Context Return Value: NO --*/ { do { VmxStatus status; PROCESSOR_NUMBER procnumber = { 0 }; VCPUVMX* NestedvCPU = VmmpGetVcpuVmx(guest_context); // HYPERPLATFORM_LOG_DEBUG_SAFE("----Start Emulate VMRESUME---"); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } if (!NestedvCPU) { DumpVcpu(guest_context); HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG(" Vmresume: Unimplemented third level virualization VMX: %I64x VMCS12: %I64x \r\n", VmmpGetVcpuVmx(guest_context), NestedvCPU->vmcs12_pa); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } VMEntryEmulate(NestedvCPU, guest_context, FALSE); //HYPERPLATFORM_COMMON_DBG_BREAK(); VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------// VOID VmxVmptrstEmulate( GuestContext* guest_context ) /*++ Desscription: Emulating VMPtrst instruction , simple emulation , may not be consistent with Intel's behavior Paremeters: Guest Context Return Value: NO --*/ { do { PROCESSOR_NUMBER procnumber = {}; ULONG64 InstructionPointer = { UtilVmRead64(VmcsField::kGuestRip) }; ULONG64 StackPointer = { UtilVmRead64(VmcsField::kGuestRsp) }; ULONG64 vmcs12_region_pa = *(PULONG64)DecodeVmclearOrVmptrldOrVmptrstOrVmxon(guest_context); ULONG vcpu_index = KeGetCurrentProcessorNumberEx(&procnumber); if (!vmcs12_region_pa) { HYPERPLATFORM_LOG_DEBUG_SAFE(("vmcs12_region_pa null ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } ULONG64 vmcs12_region_va = (ULONG64)UtilVaFromPa(vmcs12_region_pa); if (VmmpGetvCpuMode(guest_context) != VmxMode) { HYPERPLATFORM_LOG_DEBUG_SAFE(("Current vCPU already in VMX mode ! \r\n")); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } // if VCPU not run in VMX mode if (VmxGetVmxMode(VmmpGetVcpuVmx(guest_context)) != RootMode) { // Inject ...' HYPERPLATFORM_LOG_DEBUG_SAFE("Vmptrst: Unimplemented third level virualization %I64x \r\n", VmmpGetVcpuVmx(guest_context)); VMfailInvalid(VmmpGetFlagReg(guest_context)); break; } *(PULONG64)vmcs12_region_va = VmmpGetVcpuVmx(guest_context)->vmcs12_pa; VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } //------------------------------------------------------------------------------------------------//VOID void VmxInveptEmulate( _In_ GuestContext* guest_context ) { do{ /*EptpRefreshEpt02( VmmGetCurrentEpt02Pointer(guest_context), VmmGetCurrentEpt12Pointer(guest_context), VmmGetCurrentEpt01Pointer(guest_context) );*/ VMSucceed(VmmpGetFlagReg(guest_context)); } while (FALSE); } }
/** * 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 <event2/event.h> #include <process/future.hpp> #include <process/io.hpp> #include <process/process.hpp> // For process::initialize. #include "libevent.hpp" namespace process { namespace io { namespace internal { struct Poll { Promise<short> promise; event* ev; }; void pollCallback(evutil_socket_t, short what, void* arg) { Poll* poll = reinterpret_cast<Poll*>(arg); if (poll->promise.future().hasDiscard()) { poll->promise.discard(); } else { // Convert libevent specific EV_READ / EV_WRITE to io::* specific // values of these enumerations. short events = ((what & EV_READ) ? io::READ : 0) | ((what & EV_WRITE) ? io::WRITE : 0); poll->promise.set(events); } event_free(poll->ev); delete poll; } void pollDiscard(event* ev) { event_active(ev, EV_READ, 0); } } // namespace internal { Future<short> poll(int fd, short events) { process::initialize(); internal::Poll* poll = new internal::Poll(); Future<short> future = poll->promise.future(); // Convert io::READ / io::WRITE to libevent specific values of these // enumerations. short what = ((events & io::READ) ? EV_READ : 0) | ((events & io::WRITE) ? EV_WRITE : 0); poll->ev = event_new(base, fd, what, &internal::pollCallback, poll); if (poll->ev == NULL) { LOG(FATAL) << "Failed to poll, event_new"; } event_add(poll->ev, NULL); return future .onDiscard(lambda::bind(&internal::pollDiscard, poll->ev)); } } // namespace io { } // namespace process {
#include <tempus/timer_queue.hpp> #include <cassert> #include "timer_queue_impl.hpp" namespace tempus { timer_queue::timer_queue() : impl_(new impl::timer_queue()) { } timer_queue::~timer_queue() { delete impl_; } uint64_t timer_queue::add( int64_t milliseconds, std::function<void(bool)> handler) { return impl_->add(milliseconds, handler); } size_t timer_queue::cancel( uint64_t id) { return impl_->cancel(id); } size_t timer_queue::cancel_all() { return impl_->cancel_all(); } } // namespace tempus
#include <touchgfx/Font.hpp> #ifndef NO_USING_NAMESPACE_TOUCHGFX using namespace touchgfx; #endif FONT_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::KerningNode kerning_NotoSans_Regular_12_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = { {0, 0} };
#include "wiGPUBVH.h" #include "wiScene.h" #include "wiRenderer.h" #include "ShaderInterop_BVH.h" #include "wiProfiler.h" #include "wiResourceManager.h" #include "wiGPUSortLib.h" #include "wiTextureHelper.h" #include "wiBackLog.h" #include "wiEvent.h" //#define BVH_VALIDATE // slow but great for debug! #ifdef BVH_VALIDATE #include <set> #endif // BVH_VALIDATE using namespace std; using namespace wiGraphics; using namespace wiScene; using namespace wiECS; enum CSTYPES_BVH { CSTYPE_BVH_PRIMITIVES, CSTYPE_BVH_HIERARCHY, CSTYPE_BVH_PROPAGATEAABB, CSTYPE_BVH_COUNT }; static Shader computeShaders[CSTYPE_BVH_COUNT]; static GPUBuffer constantBuffer; void wiGPUBVH::UpdateGlobalMaterialResources(const Scene& scene, CommandList cmd) { GraphicsDevice* device = wiRenderer::GetDevice(); using namespace wiRectPacker; for (size_t i = 0; i < scene.objects.GetCount(); ++i) { const ObjectComponent& object = scene.objects[i]; if (object.meshID != INVALID_ENTITY) { const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); for (auto& subset : mesh.subsets) { const MaterialComponent& material = *scene.materials.GetComponent(subset.materialID); if (material.textures[MaterialComponent::BASECOLORMAP].resource != nullptr) { sceneTextures.insert(material.textures[MaterialComponent::BASECOLORMAP].resource); } if (material.textures[MaterialComponent::SURFACEMAP].resource != nullptr) { sceneTextures.insert(material.textures[MaterialComponent::SURFACEMAP].resource); } if (material.textures[MaterialComponent::EMISSIVEMAP].resource != nullptr) { sceneTextures.insert(material.textures[MaterialComponent::EMISSIVEMAP].resource); } if (material.textures[MaterialComponent::NORMALMAP].resource != nullptr) { sceneTextures.insert(material.textures[MaterialComponent::NORMALMAP].resource); } } } } bool repackAtlas = false; const int atlasWrapBorder = 1; for (auto res : sceneTextures) { if (res == nullptr) { continue; } if (storedTextures.find(res) == storedTextures.end()) { // we need to pack this texture into the atlas rect_xywh newRect = rect_xywh(0, 0, res->texture->GetDesc().Width + atlasWrapBorder * 2, res->texture->GetDesc().Height + atlasWrapBorder * 2); storedTextures[res] = newRect; repackAtlas = true; } } if (repackAtlas) { vector<rect_xywh*> out_rects(storedTextures.size()); int i = 0; for (auto& it : storedTextures) { out_rects[i] = &it.second; i++; } std::vector<bin> bins; if (pack(out_rects.data(), (int)storedTextures.size(), 16384, bins)) { assert(bins.size() == 1 && "The regions won't fit into the texture!"); TextureDesc desc; desc.Width = (uint32_t)bins[0].size.w; desc.Height = (uint32_t)bins[0].size.h; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = FORMAT_R8G8B8A8_UNORM; desc.SampleCount = 1; desc.Usage = USAGE_DEFAULT; desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; device->CreateTexture(&desc, nullptr, &globalMaterialAtlas); device->SetName(&globalMaterialAtlas, "globalMaterialAtlas"); for (auto& it : storedTextures) { wiRenderer::CopyTexture2D(globalMaterialAtlas, -1, it.second.x + atlasWrapBorder, it.second.y + atlasWrapBorder, *it.first->texture, 0, cmd, wiRenderer::BORDEREXPAND_WRAP); } } else { wiBackLog::post("Tracing atlas packing failed!"); } } materialArray.clear(); // Pre-gather scene properties: for (size_t i = 0; i < scene.objects.GetCount(); ++i) { const ObjectComponent& object = scene.objects[i]; if (object.meshID != INVALID_ENTITY) { const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); for (auto& subset : mesh.subsets) { const MaterialComponent& material = *scene.materials.GetComponent(subset.materialID); ShaderMaterial global_material; material.WriteShaderMaterial(&global_material); // Add extended properties: const TextureDesc& desc = globalMaterialAtlas.GetDesc(); if (material.textures[MaterialComponent::BASECOLORMAP].resource != nullptr) { rect_xywh rect = storedTextures[material.textures[MaterialComponent::BASECOLORMAP].resource]; // eliminate border expansion: rect.x += atlasWrapBorder; rect.y += atlasWrapBorder; rect.w -= atlasWrapBorder * 2; rect.h -= atlasWrapBorder * 2; global_material.baseColorAtlasMulAdd = XMFLOAT4((float)rect.w / (float)desc.Width, (float)rect.h / (float)desc.Height, (float)rect.x / (float)desc.Width, (float)rect.y / (float)desc.Height); } if (material.textures[MaterialComponent::SURFACEMAP].resource != nullptr) { rect_xywh rect = storedTextures[material.textures[MaterialComponent::SURFACEMAP].resource]; // eliminate border expansion: rect.x += atlasWrapBorder; rect.y += atlasWrapBorder; rect.w -= atlasWrapBorder * 2; rect.h -= atlasWrapBorder * 2; global_material.surfaceMapAtlasMulAdd = XMFLOAT4((float)rect.w / (float)desc.Width, (float)rect.h / (float)desc.Height, (float)rect.x / (float)desc.Width, (float)rect.y / (float)desc.Height); } if (material.textures[MaterialComponent::EMISSIVEMAP].resource != nullptr) { rect_xywh rect = storedTextures[material.textures[MaterialComponent::EMISSIVEMAP].resource]; // eliminate border expansion: rect.x += atlasWrapBorder; rect.y += atlasWrapBorder; rect.w -= atlasWrapBorder * 2; rect.h -= atlasWrapBorder * 2; global_material.emissiveMapAtlasMulAdd = XMFLOAT4((float)rect.w / (float)desc.Width, (float)rect.h / (float)desc.Height, (float)rect.x / (float)desc.Width, (float)rect.y / (float)desc.Height); } if (material.textures[MaterialComponent::NORMALMAP].resource != nullptr) { rect_xywh rect = storedTextures[material.textures[MaterialComponent::NORMALMAP].resource]; // eliminate border expansion: rect.x += atlasWrapBorder; rect.y += atlasWrapBorder; rect.w -= atlasWrapBorder * 2; rect.h -= atlasWrapBorder * 2; global_material.normalMapAtlasMulAdd = XMFLOAT4((float)rect.w / (float)desc.Width, (float)rect.h / (float)desc.Height, (float)rect.x / (float)desc.Width, (float)rect.y / (float)desc.Height); } materialArray.push_back(global_material); } } } if (materialArray.empty()) { return; } if (globalMaterialBuffer.GetDesc().ByteWidth != sizeof(ShaderMaterial) * materialArray.size()) { GPUBufferDesc desc; desc.BindFlags = BIND_SHADER_RESOURCE; desc.StructureByteStride = sizeof(ShaderMaterial); desc.ByteWidth = desc.StructureByteStride * (uint32_t)materialArray.size(); desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &globalMaterialBuffer); } device->UpdateBuffer(&globalMaterialBuffer, materialArray.data(), cmd, sizeof(ShaderMaterial) * (int)materialArray.size()); } void wiGPUBVH::Build(const Scene& scene, CommandList cmd) { GraphicsDevice* device = wiRenderer::GetDevice(); if (!constantBuffer.IsValid()) { GPUBufferDesc bd; bd.Usage = USAGE_DYNAMIC; bd.CPUAccessFlags = CPU_ACCESS_WRITE; bd.BindFlags = BIND_CONSTANT_BUFFER; bd.ByteWidth = sizeof(BVHCB); device->CreateBuffer(&bd, nullptr, &constantBuffer); device->SetName(&constantBuffer, "BVHGeneratorCB"); } if (!primitiveCounterBuffer.IsValid()) { GPUBufferDesc desc; desc.BindFlags = BIND_SHADER_RESOURCE; desc.StructureByteStride = sizeof(uint); desc.ByteWidth = desc.StructureByteStride; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &primitiveCounterBuffer); device->SetName(&primitiveCounterBuffer, "primitiveCounterBuffer"); } // Pre-gather scene properties: uint totalTriangles = 0; for (size_t i = 0; i < scene.objects.GetCount(); ++i) { const ObjectComponent& object = scene.objects[i]; if (object.meshID != INVALID_ENTITY) { const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); totalTriangles += (uint)mesh.indices.size() / 3; } } if (totalTriangles > primitiveCapacity) { primitiveCapacity = std::max(2u, totalTriangles); GPUBufferDesc desc; desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(BVHNode); desc.ByteWidth = desc.StructureByteStride * primitiveCapacity * 2; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &bvhNodeBuffer); device->SetName(&bvhNodeBuffer, "BVHNodeBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(uint); desc.ByteWidth = desc.StructureByteStride * primitiveCapacity * 2; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &bvhParentBuffer); device->SetName(&bvhParentBuffer, "BVHParentBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(uint); desc.ByteWidth = desc.StructureByteStride * (((primitiveCapacity - 1) + 31) / 32); // bitfield for internal nodes desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &bvhFlagBuffer); device->SetName(&bvhFlagBuffer, "BVHFlagBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(uint); desc.ByteWidth = desc.StructureByteStride * primitiveCapacity; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &primitiveIDBuffer); device->SetName(&primitiveIDBuffer, "primitiveIDBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(BVHPrimitive); desc.ByteWidth = desc.StructureByteStride * primitiveCapacity; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &primitiveBuffer); device->SetName(&primitiveBuffer, "primitiveBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.StructureByteStride = sizeof(BVHPrimitiveData); desc.ByteWidth = desc.StructureByteStride * primitiveCapacity; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; device->CreateBuffer(&desc, nullptr, &primitiveDataBuffer); device->SetName(&primitiveDataBuffer, "primitiveDataBuffer"); desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS; desc.ByteWidth = desc.StructureByteStride * primitiveCapacity; desc.CPUAccessFlags = 0; desc.Format = FORMAT_UNKNOWN; desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED; desc.Usage = USAGE_DEFAULT; desc.StructureByteStride = sizeof(float); // morton buffer is float because sorting must be done and gpu sort operates on floats for now! device->CreateBuffer(&desc, nullptr, &primitiveMortonBuffer); device->SetName(&primitiveMortonBuffer, "primitiveMortonBuffer"); } auto range = wiProfiler::BeginRangeGPU("BVH Rebuild", cmd); UpdateGlobalMaterialResources(scene, cmd); primitiveCount = 0; uint32_t materialCount = 0; device->EventBegin("BVH - Primitive Builder", cmd); { device->BindComputeShader(&computeShaders[CSTYPE_BVH_PRIMITIVES], cmd); GPUResource* uavs[] = { &primitiveIDBuffer, &primitiveBuffer, &primitiveDataBuffer, &primitiveMortonBuffer, }; device->BindUAVs(CS, uavs, 0, arraysize(uavs), cmd); for (size_t i = 0; i < scene.objects.GetCount(); ++i) { const ObjectComponent& object = scene.objects[i]; if (object.meshID != INVALID_ENTITY) { const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); BVHCB cb; cb.xBVHWorld = object.transform_index >= 0 ? scene.transforms[object.transform_index].world : IDENTITYMATRIX; cb.xBVHInstanceColor = object.color; cb.xBVHMaterialOffset = materialCount; cb.xBVHMeshTriangleOffset = primitiveCount; cb.xBVHMeshTriangleCount = (uint)mesh.indices.size() / 3; cb.xBVHMeshVertexPOSStride = sizeof(MeshComponent::Vertex_POS); device->UpdateBuffer(&constantBuffer, &cb, cmd); primitiveCount += cb.xBVHMeshTriangleCount; device->BindConstantBuffer(CS, &constantBuffer, CB_GETBINDSLOT(BVHCB), cmd); const GPUResource* res[] = { &globalMaterialBuffer, &mesh.indexBuffer, mesh.streamoutBuffer_POS.IsValid() ? &mesh.streamoutBuffer_POS : &mesh.vertexBuffer_POS, &mesh.vertexBuffer_UV0, &mesh.vertexBuffer_UV1, &mesh.vertexBuffer_COL, &mesh.vertexBuffer_SUB, }; device->BindResources(CS, res, TEXSLOT_ONDEMAND0, arraysize(res), cmd); device->Dispatch((cb.xBVHMeshTriangleCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); materialCount += (uint32_t)mesh.subsets.size(); } } GPUBarrier barriers[] = { GPUBarrier::Memory() }; device->Barrier(barriers, arraysize(barriers), cmd); device->UnbindUAVs(0, arraysize(uavs), cmd); } device->UpdateBuffer(&primitiveCounterBuffer, &primitiveCount, cmd); device->EventEnd(cmd); device->EventBegin("BVH - Sort Primitive Mortons", cmd); wiGPUSortLib::Sort(primitiveCount, primitiveMortonBuffer, primitiveCounterBuffer, 0, primitiveIDBuffer, cmd); device->EventEnd(cmd); device->EventBegin("BVH - Build Hierarchy", cmd); { device->BindComputeShader(&computeShaders[CSTYPE_BVH_HIERARCHY], cmd); GPUResource* uavs[] = { &bvhNodeBuffer, &bvhParentBuffer, &bvhFlagBuffer }; device->BindUAVs(CS, uavs, 0, arraysize(uavs), cmd); GPUResource* res[] = { &primitiveCounterBuffer, &primitiveIDBuffer, &primitiveMortonBuffer, }; device->BindResources(CS, res, TEXSLOT_ONDEMAND0, arraysize(res), cmd); device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); GPUBarrier barriers[] = { GPUBarrier::Memory() }; device->Barrier(barriers, arraysize(barriers), cmd); device->UnbindUAVs(0, arraysize(uavs), cmd); } device->EventEnd(cmd); device->EventBegin("BVH - Propagate AABB", cmd); { GPUBarrier barriers[] = { GPUBarrier::Memory() }; device->Barrier(barriers, arraysize(barriers), cmd); device->BindComputeShader(&computeShaders[CSTYPE_BVH_PROPAGATEAABB], cmd); GPUResource* uavs[] = { &bvhNodeBuffer, &bvhFlagBuffer, }; device->BindUAVs(CS, uavs, 0, arraysize(uavs), cmd); GPUResource* res[] = { &primitiveCounterBuffer, &primitiveIDBuffer, &primitiveBuffer, &bvhParentBuffer, }; device->BindResources(CS, res, TEXSLOT_ONDEMAND0, arraysize(res), cmd); device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); device->Barrier(barriers, arraysize(barriers), cmd); device->UnbindUAVs(0, arraysize(uavs), cmd); } device->EventEnd(cmd); wiProfiler::EndRange(range); // BVH rebuild #ifdef BVH_VALIDATE GPUBufferDesc readback_desc; bool download_success; // Download primitive count: readback_desc = primitiveCounterBuffer.GetDesc(); readback_desc.Usage = USAGE_STAGING; readback_desc.CPUAccessFlags = CPU_ACCESS_READ; readback_desc.BindFlags = 0; readback_desc.MiscFlags = 0; GPUBuffer readback_primitiveCounterBuffer; device->CreateBuffer(&readback_desc, nullptr, &readback_primitiveCounterBuffer); uint primitiveCount; download_success = device->DownloadResource(&primitiveCounterBuffer, &readback_primitiveCounterBuffer, &primitiveCount, cmd); assert(download_success); if (primitiveCount > 0) { const uint leafNodeOffset = primitiveCount - 1; // Validate node buffer: readback_desc = bvhNodeBuffer.GetDesc(); readback_desc.Usage = USAGE_STAGING; readback_desc.CPUAccessFlags = CPU_ACCESS_READ; readback_desc.BindFlags = 0; readback_desc.MiscFlags = 0; GPUBuffer readback_nodeBuffer; device->CreateBuffer(&readback_desc, nullptr, &readback_nodeBuffer); vector<BVHNode> nodes(readback_desc.ByteWidth / sizeof(BVHNode)); download_success = device->DownloadResource(&bvhNodeBuffer, &readback_nodeBuffer, nodes.data(), cmd); assert(download_success); set<uint> visitedLeafs; vector<uint> stack; stack.push_back(0); while (!stack.empty()) { uint nodeIndex = stack.back(); stack.pop_back(); if (nodeIndex >= leafNodeOffset) { // leaf node assert(visitedLeafs.count(nodeIndex) == 0); // leaf node was already visited, this must not happen! visitedLeafs.insert(nodeIndex); } else { // internal node BVHNode& node = nodes[nodeIndex]; stack.push_back(node.LeftChildIndex); stack.push_back(node.RightChildIndex); } } for (uint i = 0; i < primitiveCount; ++i) { uint nodeIndex = leafNodeOffset + i; BVHNode& leaf = nodes[nodeIndex]; assert(leaf.LeftChildIndex == 0 && leaf.RightChildIndex == 0); // a leaf must have no children assert(visitedLeafs.count(nodeIndex) > 0); // every leaf node must have been visited in the traversal above } // Validate flag buffer: readback_desc = bvhFlagBuffer.GetDesc(); readback_desc.Usage = USAGE_STAGING; readback_desc.CPUAccessFlags = CPU_ACCESS_READ; readback_desc.BindFlags = 0; readback_desc.MiscFlags = 0; GPUBuffer readback_flagBuffer; device->CreateBuffer(&readback_desc, nullptr, &readback_flagBuffer); vector<uint> flags(readback_desc.ByteWidth / sizeof(uint)); download_success = device->DownloadResource(&bvhFlagBuffer, &readback_flagBuffer, flags.data(), cmd); assert(download_success); for (auto& x : flags) { if (x > 2) { assert(0); // flagbuffer anomaly detected: node can't have more than two children (AABB propagation step)! break; } } } #endif // BVH_VALIDATE } void wiGPUBVH::Bind(SHADERSTAGE stage, CommandList cmd) const { GraphicsDevice* device = wiRenderer::GetDevice(); const GPUResource* res[] = { &globalMaterialBuffer, (globalMaterialAtlas.IsValid() ? &globalMaterialAtlas : wiTextureHelper::getWhite()), &primitiveCounterBuffer, &primitiveBuffer, &primitiveDataBuffer, &bvhNodeBuffer, }; device->BindResources(stage, res, TEXSLOT_ONDEMAND0, arraysize(res), cmd); } void wiGPUBVH::Clear() { primitiveCapacity = 0; primitiveCount = 0; materialArray.clear(); storedTextures.clear(); sceneTextures.clear(); } namespace wiGPUBVH_Internal { void LoadShaders() { string SHADERPATH = wiRenderer::GetShaderPath(); wiRenderer::LoadShader(CS, computeShaders[CSTYPE_BVH_PRIMITIVES], "bvh_primitivesCS.cso"); wiRenderer::LoadShader(CS, computeShaders[CSTYPE_BVH_HIERARCHY], "bvh_hierarchyCS.cso"); wiRenderer::LoadShader(CS, computeShaders[CSTYPE_BVH_PROPAGATEAABB], "bvh_propagateaabbCS.cso"); } } void wiGPUBVH::Initialize() { static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiGPUBVH_Internal::LoadShaders(); }); wiGPUBVH_Internal::LoadShaders(); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 GeoCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "wallet.h" #include "walletdb.h" #include "crypter.h" #include "ui_interface.h" #include "base58.h" using namespace std; ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey key; key.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); if (!AddKey(key)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return key.GetPubKey(); } bool CWallet::AddKey(const CKey& key) { if (!CCryptoKeyStore::AddKey(key)) return false; if (!fFileBacked) return true; if (!IsCrypted()) return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey()); return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); } return false; } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { if (!IsLocked()) return false; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a private-key-encrypted wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) wtx.nTimeReceived = GetAdjustedTime(); bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; #ifndef QT_GUI // If default receiving address gets used, replace it with a new one CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey, false)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } #endif // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } bool CWallet::EraseFromWallet(uint256 hash) { if (!fFileBacked) return false; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return true; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64 CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64 CWalletTx::GetTxTime() const { return nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived, list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const { nGeneratedImmature = nGeneratedMature = nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; if (IsCoinBase()) { if (GetBlocksToMaturity() > 0) nGeneratedImmature = pwallet->GetCredit(*this); else nGeneratedMature = GetCredit(); return; } // Compute fee: int64 nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64 nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { CTxDestination address; vector<unsigned char> vchPubKey; if (!ExtractDestination(txout.scriptPubKey, address)) { printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); } // Don't report 'change' txouts if (nDebit > 0 && pwallet->IsChange(txout)) continue; if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); if (pwallet->IsMine(txout)) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, int64& nSent, int64& nFee) const { nGenerated = nReceived = nSent = nFee = 0; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (strAccount == "") nGenerated = allGeneratedMature; if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (!fClient && txdb.ReadDiskTx(hash, tx)) { ; } else { printf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } int CWallet::ScanForWalletTransaction(const uint256& hashTx) { CTransaction tx; tx.ReadFromDisk(COutPoint(hashTx, 0)); if (AddToWalletIfInvolvingMe(tx, NULL, true, true)) return 1; return 0; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if (wtx.IsCoinBase() && wtx.IsSpent(0)) continue; CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Reaccept any txes of ours that aren't already in a block if (!wtx.IsCoinBase()) wtx.AcceptWalletTransaction(txdb, false); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do Reaccept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx); } } if (!IsCoinBase()) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str()); RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); } } } void CWalletTx::RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64 nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64 nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); // Rebroadcast any of our txes that aren't in a block yet printf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(txdb); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64 CWallet::GetBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsFinal() && pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetUnconfirmedBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetImmatureBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& pcoin = (*it).second; if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.GetDepthInMainChain() >= 2) nTotal += GetCredit(pcoin); } } return nTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const { vCoins.clear(); { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal()) continue; if (fOnlyConfirmed && !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; // If output is less than minimum value, then don't include transaction. // This is to help deal with dust spam clogging up create transactions. for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue) vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain())); } } } static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue, vector<char>& vfBest, int64& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64 nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { if (nPass == 0 ? rand() % 2 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; int64 nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; int64 n = pcoin->vout[i].nValue; pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64 nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } //// debug print printf("SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) printf("%s ", FormatMoney(vValue[i].first).c_str()); printf("total %s\n", FormatMoney(nBest).c_str()); } return true; } bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { vector<COutput> vCoins; AvailableCoins(vCoins); return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)); } bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); // transaction comment wtxNew.strTxComment = strTxComment; if (wtxNew.strTxComment.length() > MAX_TX_COMMENT_LEN) wtxNew.strTxComment.resize(MAX_TX_COMMENT_LEN); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = nTransactionFee; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn)) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } if (nChange > 0) { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address CScript scriptChange; scriptChange.SetDestination(vchPubKey.GetID()); // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000); bool fAllowFree = CTransaction::AllowFree(dPriority); int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment) { vector< pair<CScript, int64> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strTxComment); } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool()) { // This must not fail. The transaction has already been signed and recorded. printf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment) { CReserveKey reservekey(this); int64 nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strTxComment)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = _("Error: Transaction creation failed "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: 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."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee, strTxComment); } int CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return false; fFirstRunRet = false; int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } nLoadWalletRet = DB_NEED_REWRITE; } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); CreateThread(ThreadFlushWalletDB, &strWalletFile); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); mapAddressBook[address] = strName; NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { mapAddressBook.erase(address); NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } void CWallet::PrintWallet(const CBlock& block) { { LOCK(cs_wallet); if (mapWallet.count(block.vtx[0].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); } } printf("\n"); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) { if (!pwallet->fFileBacked) return false; strWalletFileOut = pwallet->strWalletFile; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64 nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64 nKeys = max(GetArg("-keypool", 100), (int64)0); for (int i = 0; i < nKeys; i++) { int64 nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool() { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL); while (setKeyPool.size() < (nTargetSize + 1)) { int64 nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); printf("keypool reserve %"PRI64d"\n", nIndex); } } int64 CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64 nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64 nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } printf("keypool keep %"PRI64d"\n", nIndex); } void CWallet::ReturnKey(int64 nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } printf("keypool return %"PRI64d"\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse) { int64 nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (fAllowReuse && vchDefaultKey.IsValid()) { result = vchDefaultKey; return true; } if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64 CWallet::GetOldestKeyPoolTime() { int64 nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } CPubKey CReserveKey::GetReservedKey() { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool."); vchPubKey = pwallet->vchDefaultKey; } } assert(vchPubKey.IsValid()); return vchPubKey; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } }
#include "../VM.hpp" #include "../../common/Instruction.hpp" namespace sbl::vm { bool VM::_performLogical(Instruction* instr) { switch (instr->mnemonic) { case Mnemonic::And_R_R: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) & _tryRead(Register{ instr->arg2 })); break; case Mnemonic::And_R_A: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) & _tryRead(Address{ instr->arg2 })); break; case Mnemonic::And_R_I: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) & _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::And_R_V: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) & _tryRead(Value{ instr->arg2 })); break; case Mnemonic::And_A_R: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) & _tryRead(Register{ instr->arg2 })); break; case Mnemonic::And_A_A: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) & _tryRead(Address{ instr->arg2 })); break; case Mnemonic::And_A_I: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) & _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::And_A_V: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) & _tryRead(Value{ instr->arg2 })); break; case Mnemonic::And_I_R: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) & _tryRead(Register{ instr->arg2 })); break; case Mnemonic::And_I_A: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) & _tryRead(Address{ instr->arg2 })); break; case Mnemonic::And_I_I: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) & _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::And_I_V: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) & _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Or_R_R: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) | _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Or_R_A: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) | _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Or_R_I: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) | _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Or_R_V: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) | _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Or_A_R: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) | _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Or_A_A: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) | _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Or_A_I: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) | _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Or_A_V: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) | _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Or_I_R: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) | _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Or_I_A: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) | _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Or_I_I: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) | _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Or_I_V: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) | _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Xor_R_R: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) ^ _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Xor_R_A: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) ^ _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Xor_R_I: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) ^ _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Xor_R_V: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, _forceRead(Register{ instr->arg1 }) ^ _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Xor_A_R: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) ^ _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Xor_A_A: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) ^ _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Xor_A_I: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) ^ _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Xor_A_V: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, _forceRead(Address{ instr->arg1 }) ^ _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Xor_I_R: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) ^ _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Xor_I_A: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) ^ _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Xor_I_I: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) ^ _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Xor_I_V: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, _forceRead(Indirect{ instr->arg1 }) ^ _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Eq_R_R: setControl(_tryRead(Register{ instr->arg1 }) == _tryRead(Register{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_R_A: setControl(_tryRead(Register{ instr->arg1 }) == _tryRead(Address{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_R_I: setControl(_tryRead(Register{ instr->arg1 }) == _tryRead(Indirect{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_R_V: setControl(_tryRead(Register{ instr->arg1 }) == _tryRead(Value{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_A_R: setControl(_tryRead(Address{ instr->arg1 }) == _tryRead(Register{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_A_A: setControl(_tryRead(Address{ instr->arg1 }) == _tryRead(Address{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_A_I: setControl(_tryRead(Address{ instr->arg1 }) == _tryRead(Indirect{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_A_V: setControl(_tryRead(Address{ instr->arg1 }) == _tryRead(Value{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_I_R: setControl(_tryRead(Indirect{ instr->arg1 }) == _tryRead(Register{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_I_A: setControl(_tryRead(Indirect{ instr->arg1 }) == _tryRead(Address{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_I_I: setControl(_tryRead(Indirect{ instr->arg1 }) == _tryRead(Indirect{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Eq_I_V: setControl(_tryRead(Indirect{ instr->arg1 }) == _tryRead(Value{ instr->arg2 }), TestEqual | TestBiggerEqual | TestSmallerEqual); break; case Mnemonic::Neq_R_R: setControl(_tryRead(Register{ instr->arg1 }) != _tryRead(Register{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_R_A: setControl(_tryRead(Register{ instr->arg1 }) != _tryRead(Address{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_R_I: setControl(_tryRead(Register{ instr->arg1 }) != _tryRead(Indirect{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_R_V: setControl(_tryRead(Register{ instr->arg1 }) != _tryRead(Value{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_A_R: setControl(_tryRead(Address{ instr->arg1 }) != _tryRead(Register{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_A_A: setControl(_tryRead(Address{ instr->arg1 }) != _tryRead(Address{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_A_I: setControl(_tryRead(Address{ instr->arg1 }) != _tryRead(Indirect{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_A_V: setControl(_tryRead(Address{ instr->arg1 }) != _tryRead(Value{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_I_R: setControl(_tryRead(Indirect{ instr->arg1 }) != _tryRead(Register{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_I_A: setControl(_tryRead(Indirect{ instr->arg1 }) != _tryRead(Address{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_I_I: setControl(_tryRead(Indirect{ instr->arg1 }) != _tryRead(Indirect{ instr->arg2 }), TestUnequal); break; case Mnemonic::Neq_I_V: setControl(_tryRead(Indirect{ instr->arg1 }) != _tryRead(Value{ instr->arg2 }), TestUnequal); break; case Mnemonic::Lt_R_R: setControl(_tryRead(Register{ instr->arg1 }) < _tryRead(Register{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_R_A: setControl(_tryRead(Register{ instr->arg1 }) < _tryRead(Address{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_R_I: setControl(_tryRead(Register{ instr->arg1 }) < _tryRead(Indirect{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_R_V: setControl(_tryRead(Register{ instr->arg1 }) < _tryRead(Value{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_A_R: setControl(_tryRead(Address{ instr->arg1 }) < _tryRead(Register{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_A_A: setControl(_tryRead(Address{ instr->arg1 }) < _tryRead(Address{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_A_I: setControl(_tryRead(Address{ instr->arg1 }) < _tryRead(Indirect{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_A_V: setControl(_tryRead(Address{ instr->arg1 }) < _tryRead(Value{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_I_R: setControl(_tryRead(Indirect{ instr->arg1 }) < _tryRead(Register{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_I_A: setControl(_tryRead(Indirect{ instr->arg1 }) < _tryRead(Address{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_I_I: setControl(_tryRead(Indirect{ instr->arg1 }) < _tryRead(Indirect{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Lt_I_V: setControl(_tryRead(Indirect{ instr->arg1 }) < _tryRead(Value{ instr->arg2 }), TestSmaller | TestUnequal | TestSmallerEqual); break; case Mnemonic::Bt_R_R: setControl(_tryRead(Register{ instr->arg1 }) > _tryRead(Register{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_R_A: setControl(_tryRead(Register{ instr->arg1 }) > _tryRead(Address{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_R_I: setControl(_tryRead(Register{ instr->arg1 }) > _tryRead(Indirect{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_R_V: setControl(_tryRead(Register{ instr->arg1 }) > _tryRead(Value{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_A_R: setControl(_tryRead(Address{ instr->arg1 }) > _tryRead(Register{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_A_A: setControl(_tryRead(Address{ instr->arg1 }) > _tryRead(Address{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_A_I: setControl(_tryRead(Address{ instr->arg1 }) > _tryRead(Indirect{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_A_V: setControl(_tryRead(Address{ instr->arg1 }) > _tryRead(Value{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_I_R: setControl(_tryRead(Indirect{ instr->arg1 }) > _tryRead(Register{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_I_A: setControl(_tryRead(Indirect{ instr->arg1 }) > _tryRead(Address{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_I_I: setControl(_tryRead(Indirect{ instr->arg1 }) > _tryRead(Indirect{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Bt_I_V: setControl(_tryRead(Indirect{ instr->arg1 }) > _tryRead(Value{ instr->arg2 }), TestBigger | TestUnequal | TestBiggerEqual); break; case Mnemonic::Not_R: _assertReadWrite(Register{ instr->arg1 }); _forceWrite(Register{ instr->arg1 }, ~_forceRead(Register{ instr->arg1 })); break; case Mnemonic::Not_A: _assertReadWrite(Address{ instr->arg1 }); _forceWrite(Address{ instr->arg1 }, ~_forceRead(Address{ instr->arg1 })); break; case Mnemonic::Not_I: _assertReadWrite(Indirect{ instr->arg1 }); _forceWrite(Indirect{ instr->arg1 }, ~_forceRead(Indirect{ instr->arg1 })); break; case Mnemonic::Test_R_R: setControl(_tryRead(Register{ instr->arg1 }), _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Test_R_A: setControl(_tryRead(Register{ instr->arg1 }), _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Test_R_I: setControl(_tryRead(Register{ instr->arg1 }), _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Test_R_V: setControl(_tryRead(Register{ instr->arg1 }), _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Test_A_R: setControl(_tryRead(Address{ instr->arg1 }), _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Test_A_A: setControl(_tryRead(Address{ instr->arg1 }), _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Test_A_I: setControl(_tryRead(Address{ instr->arg1 }), _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Test_A_V: setControl(_tryRead(Address{ instr->arg1 }), _tryRead(Value{ instr->arg2 })); break; case Mnemonic::Test_I_R: setControl(_tryRead(Indirect{ instr->arg1 }), _tryRead(Register{ instr->arg2 })); break; case Mnemonic::Test_I_A: setControl(_tryRead(Indirect{ instr->arg1 }), _tryRead(Address{ instr->arg2 })); break; case Mnemonic::Test_I_I: setControl(_tryRead(Indirect{ instr->arg1 }), _tryRead(Indirect{ instr->arg2 })); break; case Mnemonic::Test_I_V: setControl(_tryRead(Indirect{ instr->arg1 }), _tryRead(Value{ instr->arg2 })); break; } return true; } } //sbl::vm
/** * Height map generator implementation. * * @author Raoul Harel * @url github.com/rharel/cpp-diamond-square */ #include <diamond_square/HeightMapGenerator.hpp> namespace diamond_square { template <typename T> HeightMapGenerator<T>::HeightMapGenerator ( const unsigned int level_of_detail, NoiseGenerator<T>& noise_generator ) : map_(level_of_detail), noise_generator_(&noise_generator) {} template <typename T> void HeightMapGenerator<T>::Generate() { const unsigned int size = map_.width(); const unsigned int max_lod = map_.level_of_detail(); for (unsigned int i = 0; i < max_lod; ++i) { relative_level_of_detail_ = static_cast<float>(i) / static_cast<float>(max_lod); const unsigned int lod = max_lod - i; const unsigned int square_size = static_cast<unsigned int> ( std::pow(2, lod) + 1 ); const unsigned int square_radius = (square_size - 1) / 2; const unsigned int dx = square_size - 1; const unsigned int dy = dx; unsigned int y = dy / 2; while (y < size) { unsigned int x = dx / 2; while (x < size) { PerformDiamondStep(x, y, square_radius); PerformSquareStep(x, y, square_radius); x += dx; } y += dy; } } } template <typename T> void HeightMapGenerator<T>::PerformDiamondStep ( const unsigned int x, const unsigned int y, const unsigned int r // radius ) { map_.At(x, y) = AverageDiamondNeighbours(x, y, r) + noise_generator_->Generate(relative_level_of_detail_); } template <typename T> void HeightMapGenerator<T>::PerformSquareStep ( const unsigned int x, const unsigned int y, const unsigned int r // radius ) { map_.At(x - r, y) = AverageSquareNeighbours(x - r, y, r) + noise_generator_->Generate(relative_level_of_detail_); map_.At(x + r, y) = AverageSquareNeighbours(x + r, y, r) + noise_generator_->Generate(relative_level_of_detail_); map_.At(x, y - r) = AverageSquareNeighbours(x, y - r, r) + noise_generator_->Generate(relative_level_of_detail_); map_.At(x, y + r) = AverageSquareNeighbours(x, y + r, r) + noise_generator_->Generate(relative_level_of_detail_); } template <typename T> T HeightMapGenerator<T>::AverageDiamondNeighbours ( const unsigned int x, const unsigned int y, const unsigned int r // radius ) { const T sum = map_.At(x - r, y - r) + map_.At(x - r, y + r) + map_.At(x + r, y + r) + map_.At(x + r, y - r); return 0.25f * sum; } template <typename T> T HeightMapGenerator<T>::AverageSquareNeighbours ( const unsigned int x, const unsigned int y, const unsigned int r // radius ) { const T sum = map_.At(x - r, y) + map_.At(x + r, y) + map_.At(x, y - r) + map_.At(x, y + r); return 0.25f * sum; } template <typename T> const HeightMap<T>& HeightMapGenerator<T>::map() const { return map_; } template <typename T> HeightMap<T>& HeightMapGenerator<T>::map() { return map_; } }
/** * If not stated otherwise in this file or this component's LICENSE * file the following copyright and licenses apply: * * Copyright 2019 RDK Management * * 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 "ActivityMonitor.h" #include "utils.h" #define ACTIVITY_MONITOR_METHOD_GET_APPLICATION_MEMORY_USAGE "getApplicationMemoryUsage" #define ACTIVITY_MONITOR_METHOD_GET_ALL_MEMORY_USAGE "getAllMemoryUsage" #define ACTIVITY_MONITOR_METHOD_ENABLE_MONITORING "enableMonitoring" #define ACTIVITY_MONITOR_METHOD_DISABLE_MONITORING "disableMonitoring" #define ACTIVITY_MONITOR_EVT_ON_MEMORY_THRESHOLD "onMemoryThreshold" #define ACTIVITY_MONITOR_EVT_ON_CPU_THRESHOLD "onCPUThreshold" #define VERSION_TXT_FILE "/version.txt" #define REGISTRY_FILENAME "/home/root/waylandregistryreceiver.conf" #define REGISTRY_FILENAME_RNE "/home/root/waylandregistryrne.conf" #define REGISTRY_FILENAME_DEV "/opt/waylandregistry.conf" namespace WPEFramework { namespace Plugin { SERVICE_REGISTRATION(ActivityMonitor, 1, 0); ActivityMonitor* ActivityMonitor::_instance = nullptr; struct AppConfig { AppConfig() { pid = memoryThresholdsMB = cpuThresholdPercent = cpuThresholdSeconds = 0; state = STATE_NORMAL; cpuUsage = 0; memExceeded = cpuExceededPercent = 0; eventSent = false; } enum { STATE_NORMAL, STATE_EXCEEDED, STATE_RECEDED, }; unsigned int pid; unsigned int memoryThresholdsMB; unsigned int cpuThresholdPercent; unsigned int cpuThresholdSeconds; int state; long long unsigned int cpuUsage; std::chrono::system_clock::time_point cpuThreshold; unsigned int memExceeded; unsigned int cpuExceededPercent; bool eventSent; }; struct MonitorParams { double memoryIntervalSeconds; double cpuIntervalSeconds; std::list <AppConfig> config; long long unsigned int totalCpuUsage; std::chrono::system_clock::time_point lastMemCheck; std::chrono::system_clock::time_point lastCpuCheck; }; class MemoryInfo { public: static bool isDevOrVBNImage(); static void initRegistry(); static long long unsigned int getTotalCpuUsage(); static unsigned int parseLine(const char *line); static unsigned int getFreeMemory(); static void readSmaps(const char *pid, unsigned int &pvtOut, unsigned int &sharedOut); static void getProcStat(const char *dirName, std::string &cmdName, unsigned int &ppid, bool calcCpu, long long unsigned int &cpuTicks); static void getProcInfo(bool calcMem, bool calcCpu, std::vector<unsigned int> &pidsOut, std::vector <std::string> &cmdsOut, std::vector <unsigned int> &memUsageOut, std::vector <long long unsigned int> &cpuUsageOut); private: static std::map <std::string, std::string> registry; }; std::map <std::string, std::string> MemoryInfo::registry; ActivityMonitor::ActivityMonitor() : AbstractPlugin() , m_monitorParams(NULL) , m_stopMonitoring(false) { ActivityMonitor::_instance = this; registerMethod(ACTIVITY_MONITOR_METHOD_GET_APPLICATION_MEMORY_USAGE, &ActivityMonitor::getApplicationMemoryUsage, this); registerMethod(ACTIVITY_MONITOR_METHOD_GET_ALL_MEMORY_USAGE, &ActivityMonitor::getAllMemoryUsage, this); registerMethod(ACTIVITY_MONITOR_METHOD_ENABLE_MONITORING, &ActivityMonitor::enableMonitoring, this); registerMethod(ACTIVITY_MONITOR_METHOD_DISABLE_MONITORING, &ActivityMonitor::disableMonitoring, this); } ActivityMonitor::~ActivityMonitor() { } void ActivityMonitor::Deinitialize(PluginHost::IShell* /* service */) { ActivityMonitor::_instance = nullptr; if (m_monitor.joinable()) m_monitor.join(); delete m_monitorParams; } uint32_t ActivityMonitor::getApplicationMemoryUsage(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); if (parameters.HasLabel("pid")) { unsigned int pidToFind = 0; getNumberParameter("pid", pidToFind); if (pidToFind > 0) { std::vector<unsigned int> pids; std::vector <std::string> cmds; std::vector <unsigned int> memUsage; std::vector <long long unsigned int> cpuUsage; MemoryInfo::getProcInfo(true, false, pids, cmds, memUsage, cpuUsage); for (unsigned int n = 0; n < pids.size(); n++) { if (pids[n] == pidToFind) { JsonObject h; h["appPid"] = pidToFind; h["appName"] = cmds[n]; h["memoryMB"] = memUsage[n]; response["applicationMemory"] = h; returnResponse(true); } } } } returnResponse(false); } uint32_t ActivityMonitor::getAllMemoryUsage(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); response["freeMemoryMB"] = MemoryInfo::getFreeMemory(); JsonArray sl; std::vector<unsigned int> pids; std::vector <std::string> cmds; std::vector <unsigned int> memUsage; std::vector <long long unsigned int> cpuUsage; MemoryInfo::getProcInfo(true, false, pids, cmds, memUsage, cpuUsage); for (unsigned int n = 0; n < pids.size(); n++) { JsonObject h; h["appPid"] = pids[n]; h["appName"] = cmds[n]; h["memoryMB"] = memUsage[n]; sl.Add(h); } response["applicationMemory"] = sl; returnResponse(true); } uint32_t ActivityMonitor::enableMonitoring(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); { std::lock_guard<std::mutex> lock(m_monitoringMutex); m_stopMonitoring = true; } if (m_monitor.joinable()) { LOGWARN("Terminating monitor thread"); m_monitor.join(); } JsonArray configArray = parameters["config"].Array(); if (0 == configArray.Length()) { LOGWARN("Got empty list of processes to monitor"); returnResponse(false); } float memoryIntervalSeconds = 0; float cpuIntervalSeconds = 0; try { memoryIntervalSeconds = std::stof(parameters["memoryIntervalSeconds"] .String()); cpuIntervalSeconds = std::stof(parameters["cpuIntervalSeconds"].String()); } catch (...) {} if (0 == memoryIntervalSeconds && 0 == cpuIntervalSeconds) { LOGWARN("Interval for both CPU and Memory usage monitoring can't be 0"); returnResponse(false); } delete m_monitorParams; m_monitorParams = new MonitorParams(); m_monitorParams->totalCpuUsage = 0; m_monitorParams->lastMemCheck = std::chrono::system_clock::now(); m_monitorParams->lastCpuCheck = std::chrono::system_clock::now(); m_monitorParams->memoryIntervalSeconds = memoryIntervalSeconds; m_monitorParams->cpuIntervalSeconds = cpuIntervalSeconds; JsonArray::Iterator index(configArray.Elements()); while (index.Next() == true) { if (Core::JSON::Variant::type::OBJECT == index.Current().Content()) { JsonObject m = index.Current().Object(); AppConfig conf; getNumberParameterObject(m, "appPid", conf.pid); getNumberParameterObject(m, "memoryThresholdMB", conf.memoryThresholdsMB); getNumberParameterObject(m, "cpuThresholdPercent", conf.cpuThresholdPercent); getNumberParameterObject(m, "cpuThresholdSeconds", conf.cpuThresholdSeconds); m_monitorParams->config.push_back(conf); } else LOGWARN("Unexpected variant type"); } if (m_monitor.joinable()) m_monitor.join(); { std::lock_guard<std::mutex> lock(m_monitoringMutex); m_stopMonitoring = false; } m_monitor = std::thread(threadRun, this); returnResponse(true); } uint32_t ActivityMonitor::disableMonitoring(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); { std::lock_guard<std::mutex> lock(m_monitoringMutex); m_stopMonitoring = true; } if (m_monitor.joinable()) m_monitor.join(); else LOGWARN("Monitoring is already disabled"); delete m_monitorParams; m_monitorParams = NULL; returnResponse(true); } bool MemoryInfo::isDevOrVBNImage() { std::vector <char> buf; buf.resize(1024); FILE *f = fopen(VERSION_TXT_FILE, "r"); if (!f) { LOGERR("Failed to open %s: %s", VERSION_TXT_FILE, strerror(errno)); return false; } if (!fgets(buf.data(), buf.size(), f)) { LOGERR("Failed to read from %s: %s", VERSION_TXT_FILE, strerror(errno)); fclose(f); return false; } fclose(f); std::string s(buf.data()); size_t pos = s.find("imagename:"); if (pos != std::string::npos) { s = s.substr(pos + strlen("imagename:")); s = s.substr(0, s.find_first_of("\r\n")); } else s = ""; return s.find("PROD") == std::string::npos && (s.find("DEV") != std::string::npos || s.find("VBN") != std::string::npos); } void MemoryInfo::initRegistry() { const char *registryFilename = REGISTRY_FILENAME; if (0 == access(REGISTRY_FILENAME_DEV, R_OK) && isDevOrVBNImage()) registryFilename = REGISTRY_FILENAME_DEV; else if (0 == access(REGISTRY_FILENAME_RNE, R_OK)) registryFilename = REGISTRY_FILENAME_RNE; JsonObject regObj; Core::File file; file = registryFilename; LOGINFO("Loading registry from %s", registryFilename); file.Open(); regObj.IElement::FromFile(file); file.Close(); if (regObj.HasLabel("waylandapps") && Core::JSON::Variant::type::ARRAY == regObj["waylandapps"].Content()) { JsonArray apps = regObj["waylandapps"].Array(); JsonArray::Iterator index(apps.Elements()); int cnt = 0; while (index.Next() == true) { if (Core::JSON::Variant::type::OBJECT == index.Current().Content()) { JsonObject appEntry = index.Current().Object(); std::string binary = appEntry["binary"].String(); if (binary.size() > 0 && binary[binary.size() - 1] == '%') binary = binary.substr(0, binary.size() - 1); size_t li = binary.find_last_of('/'); if (std::string::npos != li) binary = binary.substr(li + 1, binary.size() - li - 1); registry[binary.c_str()] = appEntry["name"].String(); cnt++; } else LOGWARN("Unexpected variant type"); } LOGINFO("Loaded registry, %d entries", registry.size()); } else LOGERR("Didn't find registry data"); } long long unsigned int MemoryInfo::getTotalCpuUsage() { FILE *f = fopen("/proc/stat", "r"); std::vector <char> buf; buf.resize(1024); if (NULL == fgets(buf.data(), buf.size(), f)) { LOGERR("Failed to read stat, buffer is too small"); return 0; } fclose(f); long long unsigned int user = 0, nice = 0, system = 0, idle = 0; int vc = sscanf(buf.data(), "%*s %llu %llu %llu %llu", &user, &nice, &system, &idle); if (4 != vc) LOGERR("Failed to parse /proc/stat, number of items matched: %d", vc); return user + nice + system + idle; } unsigned int MemoryInfo::parseLine(const char *line) { std::string s(line); unsigned int val; size_t begin = s.find_first_of("0123456789"); size_t end = std::string::npos; if (std::string::npos != begin) end = s.find_first_not_of("0123456789", begin); if (std::string::npos != begin && std::string::npos != end) { s = s.substr(begin, end); val = strtoul(s.c_str(), NULL, 10); return val; } else LOGERR("Failed to parse value from %s", line); return 0; } unsigned int MemoryInfo::getFreeMemory() { FILE *f = fopen("/proc/meminfo", "r"); if (NULL == f) { LOGERR("Failed to open /proc/meminfo:%s", strerror(errno)); return 0; } std::vector <char> buf; buf.resize(1024); unsigned int total = 0; while (fgets(buf.data(), buf.size(), f)) { if (strstr(buf.data(), "MemFree:") == buf.data() || strstr(buf.data(), "Buffers:") == buf.data() || strstr(buf.data(), "Cached:") == buf.data()) total += parseLine(buf.data()); } fclose(f); return total / 1024; // From KB to MB } void MemoryInfo::readSmaps(const char *pid, unsigned int &pvtOut, unsigned int &sharedOut) { std::string smapsName = "/proc/"; smapsName += pid; smapsName += "/smaps"; FILE *f = fopen(smapsName.c_str(), "r"); if (NULL == f) { pvtOut = sharedOut = 0; return; } std::vector <char> buf; buf.resize(1024); size_t shared = 0; size_t pvt = 0; size_t pss = 0; bool withPss = false; while (fgets(buf.data(), buf.size(), f)) { if (strstr(buf.data(), "Shared") == buf.data()) { shared += parseLine(buf.data()); } else if (strstr(buf.data(), "Private") == buf.data()) { pvt += parseLine(buf.data()); } else if (strstr(buf.data(), "Pss") == buf.data()) { withPss = true; pss += parseLine(buf.data()); } } fclose(f); if (withPss) shared = pss - pvt; pvtOut = pvt; sharedOut = shared; } void MemoryInfo::getProcStat(const char *dirName, std::string &cmdName, unsigned int &ppid, bool calcCpu, long long unsigned int &cpuTicks) { std::string statName = "/proc/"; statName += dirName; statName += "/stat"; std::vector <char> buf; buf.resize(1024); size_t r = 0; FILE *f = fopen(statName.c_str(), "r"); if (f) { r = fread(buf.data(), 1, buf.size(), f); if (buf.size() == r) { LOGERR("Failed to read stat, buffer is too small"); } fclose(f); } std::string stat(buf.data(), r); std::size_t p1 = stat.find_first_of("("); std::size_t p2 = stat.find_first_of(")"); if (std::string::npos == p1 || std::string::npos == p2) { //LOGINFO("Failed to parse command name from stat file '%s', '%s'", statName.c_str(), stat.c_str()); return; } cmdName = stat.substr(p1 + 1, p2 - p1 - 1); size_t pos = p2, cnt = 0; while ((pos = stat.find_first_of(" ", pos + 1)) != std::string::npos) { cnt++; if (2 == cnt) break; } ppid = 0; int vc = sscanf(buf.data() + pos, "%d", &ppid); if (1 != vc) LOGERR("Failed to parse parent pid from '%s'", stat.c_str()); if (calcCpu) { while ((pos = stat.find_first_of(" ", pos + 1)) != std::string::npos) { cnt++; if (12 == cnt) break; } long long unsigned int utime = 0, stime = 0, cutime = 0, cstime = 0; vc = sscanf(buf.data() + pos, "%llu %llu " //utime, stime "%llu %llu ", //cutime, cstime &utime, &stime, &cutime, &cstime); if (4 != vc) { LOGERR("Failed to parse parent cpu ticks from '%s', number of items matched: %d", stat.c_str(), vc); } cpuTicks = utime + stime + cutime + cstime; } } void MemoryInfo::getProcInfo(bool calcMem, bool calcCpu, std::vector<unsigned int> &pidsOut, std::vector <std::string> &cmdsOut, std::vector <unsigned int> &memUsageOut, std::vector <long long unsigned int> &cpuUsageOut) { if (0 == registry.size()) MemoryInfo::initRegistry(); if (!calcMem && !calcCpu) { LOGERR("Nothing to do"); return; } std::vector<std::string> cmds; std::vector<unsigned int> pids; std::vector<unsigned int> ppids; std::vector<long long unsigned int> cpuUsage; DIR *d = opendir("/proc"); struct dirent *de; while ((de = readdir(d))) { if (0 == de->d_name[0]) continue; char *end; pid_t pid = strtoul(de->d_name, &end, 10); if (0 != *end) continue; std::string cmdName; unsigned int ppid = 0; long long unsigned int cpuTicks = 0; MemoryInfo::getProcStat(de->d_name, cmdName, ppid, calcCpu, cpuTicks); cmds.push_back(cmdName); pids.push_back(pid); ppids.push_back(ppid); cpuUsage.push_back(cpuTicks); } std::map <unsigned int, unsigned int> pidMap; for (unsigned int n = 0; n < pids.size(); n++) pidMap[pids[n]] = n; std::map <unsigned int, std::vector <unsigned int>> cmdMap; for (unsigned int n = 0; n < cmds.size(); n++) { unsigned int lastIdx = cmds.size(); for (unsigned int pid = pids[n],idx,cnt = 0; pid != 0; pid = ppids[idx],cnt++) { idx = pidMap[pid]; std::string cmd = cmds[idx]; if (registry.find(cmd) != registry.end()) { lastIdx = idx; } if (cnt >= 100) { LOGERR("Too many iterations for process tree"); lastIdx = cmds.size(); break; } } if (lastIdx < cmds.size()) cmdMap[lastIdx].push_back(n); } std::map <std::string, unsigned int> cmdCount; if (calcMem) { for (unsigned int n = 0; n < cmds.size(); n++) cmdCount[cmds[n]]++; } for (std::map <unsigned int, std::vector <unsigned int>>::const_iterator it = cmdMap.cbegin(); it != cmdMap.cend(); it++) { unsigned int memUsage = 0; if (calcMem) { for (unsigned int n = 0; n < it->second.size(); n++) { char s[256]; snprintf(s, sizeof(s), "%u", pids[it->second[n]]); unsigned int pvt, shared; readSmaps(s, pvt, shared); unsigned int cnt = cmdCount[cmds[it->second[n]]]; if (0 == cnt) { LOGERR("Commnd count for %s was 0", cmds[n].c_str()); cnt = 1; } unsigned int usage = (pvt + shared / cnt) / 1024; if (it->first != it->second[n]) { pidsOut.push_back(pids[it->second[n]]); cmdsOut.push_back(cmds[it->second[n]]); memUsageOut.push_back(usage); } memUsage += usage; } } long long unsigned int cpu_usage = 0; if (calcCpu) { for (unsigned int n = 0; n < it->second.size(); n++) { if (it->first != it->second[n]) { if (!calcMem) // If calcMem was disabled, pid and cmd should be added here. { pidsOut.push_back(pids[it->second[n]]); cmdsOut.push_back(cmds[it->second[n]]); } cpuUsageOut.push_back(cpuUsage[it->second[n]]); } cpu_usage += cpuUsage[it->second[n]]; } } pidsOut.push_back(pids[it->first]); cmdsOut.push_back(cmds[it->first]); memUsageOut.push_back(memUsage); cpuUsageOut.push_back(cpu_usage); } } void ActivityMonitor::threadRun(ActivityMonitor *am) { am->monitoring(); } void ActivityMonitor::monitoring() { if (0 == m_monitorParams->config.size()) { LOGERR("Empty app list to monitor"); return; } while (1) { { std::lock_guard<std::mutex> lock(m_monitoringMutex); if (m_stopMonitoring) break; } std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - m_monitorParams->lastMemCheck; bool memCheck = m_monitorParams->memoryIntervalSeconds > 0 && elapsed.count() > m_monitorParams->memoryIntervalSeconds - 0.01; elapsed = std::chrono::system_clock::now() - m_monitorParams->lastCpuCheck; bool cpuCheck = m_monitorParams->cpuIntervalSeconds > 0 && elapsed.count() > m_monitorParams->cpuIntervalSeconds - 0.01; std::vector<unsigned int> pids; std::vector <std::string> cmds; std::vector <unsigned int> memUsage; std::vector <long long unsigned int> cpuUsage; MemoryInfo::getProcInfo(memCheck, cpuCheck, pids, cmds, memUsage, cpuUsage); long long unsigned int totalCpuUsage = 0; if (cpuCheck) { totalCpuUsage = MemoryInfo::getTotalCpuUsage(); } for (std::list <AppConfig>::iterator it = m_monitorParams->config.begin(); it != m_monitorParams->config.end(); it++) { unsigned int pid = it->pid; unsigned int memoryUsed = 0; if (memCheck) { for (unsigned int n = 0; n < pids.size(); n++) { if (pids[n] == pid) { memoryUsed = memUsage[n]; break; } } if (0 == memoryUsed) { LOGERR("Failed to determine memory usage for %u", pid); } if (memoryUsed >= it->memoryThresholdsMB) { if (0 == it->memExceeded) { it->memExceeded = memoryUsed; JsonObject memResult; memResult["appPid"] = pid; memResult["threshold"] = "exceeded"; memResult["memoryMB"] = memoryUsed; LOGWARN("MemoryThreshold event appPid = %u, threshold = exceeded, memoryMB = %u", pid, memoryUsed); onMemoryThresholdOccurred(memResult); } } else { if (0 != it->memExceeded && memoryUsed < it->memExceeded - it->memExceeded / 20) { it->memExceeded = 0; JsonObject memResult; memResult["appPid"] = pid; memResult["threshold"] = "receded"; memResult["memoryMB"] = memoryUsed; LOGWARN("MemoryThreshold event appPid = %u, threshold = receded, memoryMB = %u", pid, memoryUsed); onMemoryThresholdOccurred(memResult); } } } if (cpuCheck) { long long unsigned int usage = 0; if (0 != m_monitorParams->totalCpuUsage) { for (unsigned int n = 0; n < pids.size(); n++) { if (pids[n] == pid) { usage = cpuUsage[n]; break; } } if (0 != it->cpuUsage) { unsigned int percents = 0; if (usage < it->cpuUsage) { LOGERR("Wrong values for previous and current cpu usage %llu:%llu for pid: %u", usage, it->cpuUsage, pid); } else if (totalCpuUsage <= m_monitorParams->totalCpuUsage) { LOGERR("Wrong values for previous and current total cpu ticks %llu:%llu", totalCpuUsage, m_monitorParams->totalCpuUsage); } else { percents = 100 * ( usage - it->cpuUsage) / (totalCpuUsage - m_monitorParams->totalCpuUsage); } if (percents >= it->cpuThresholdPercent) { if (AppConfig::STATE_NORMAL == it->state) { it->state = AppConfig::STATE_EXCEEDED; it->cpuThreshold = std::chrono::system_clock::now(); it->cpuExceededPercent = percents; it->eventSent = false; } else if (AppConfig::STATE_EXCEEDED == it->state) { std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - it->cpuThreshold; if (elapsed.count() >= it->cpuThresholdSeconds && !it->eventSent) { JsonObject cpuResult; cpuResult["appPid"] = pid; cpuResult["threshold"] = "exceeded"; cpuResult["cpuPercent"] = percents; LOGWARN("CPUThreshold event appPid = %u, threshold = exceeded, cpuPercent = %u", pid, percents); onCPUThresholdOccurred(cpuResult); it->eventSent = true; } } else if (AppConfig::STATE_RECEDED == it->state) { it->state = AppConfig::STATE_EXCEEDED; } } else { if (AppConfig::STATE_EXCEEDED == it->state) { if (!it->eventSent) { it->state = AppConfig::STATE_NORMAL; } else if (percents < it->cpuExceededPercent - it->cpuExceededPercent / 20) { it->state = AppConfig::STATE_RECEDED; it->cpuThreshold = std::chrono::system_clock::now(); } } else if (AppConfig::STATE_RECEDED == it->state) { if (percents < it->cpuExceededPercent - it->cpuExceededPercent / 20) { std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - it->cpuThreshold; if (elapsed.count() >= it->cpuThresholdSeconds) { JsonObject cpuResult; cpuResult["type"] = "CPU"; cpuResult["appPid"] = pid; cpuResult["threshold"] = "receded"; cpuResult["cpuPercent"] = percents; LOGWARN("CPUThreshold event appPid = %u, threshold = receded, cpuPercent = %u", pid, percents); onCPUThresholdOccurred(cpuResult); it->state = AppConfig::STATE_NORMAL; } } else { it->state = AppConfig::STATE_EXCEEDED; } } } } } it->cpuUsage = usage; } } if (memCheck) m_monitorParams->lastMemCheck = std::chrono::system_clock::now(); if (cpuCheck) { m_monitorParams->lastCpuCheck = std::chrono::system_clock::now(); m_monitorParams->totalCpuUsage = totalCpuUsage; } elapsed = std::chrono::system_clock::now() - m_monitorParams->lastMemCheck; double sleepTime = m_monitorParams->memoryIntervalSeconds > 0 ? m_monitorParams->memoryIntervalSeconds - elapsed.count() : 10000; elapsed = std::chrono::system_clock::now() - m_monitorParams->lastCpuCheck; if (m_monitorParams->cpuIntervalSeconds > 0 && m_monitorParams->cpuIntervalSeconds - elapsed.count() < sleepTime) sleepTime = m_monitorParams->cpuIntervalSeconds - elapsed.count(); if (sleepTime < 0.01) { LOGERR("SleepTime is too low, using 0.01 seconds"); sleepTime = 0.01; } usleep(int(sleepTime * 1000000)); } } void ActivityMonitor::onMemoryThresholdOccurred(const JsonObject& result) { sendNotify(ACTIVITY_MONITOR_EVT_ON_MEMORY_THRESHOLD, result); } void ActivityMonitor::onCPUThresholdOccurred(const JsonObject& result) { sendNotify(ACTIVITY_MONITOR_EVT_ON_CPU_THRESHOLD, result); } } // namespace Plugin } // namespace WPEFramework
#include "common.h" #include "rosflight.h" #include "test_board.h" #include "mavlink.h" #include "cmath" #define CHN_LOW 1100 #define CHN_HIGH 1900 #define OFFBOARD_X -1.0 #define OFFBOARD_Y 0.5 #define OFFBOARD_Z -0.7 #define OFFBOARD_F 0.9 #define RC_X_PWM 1800 #define RC_X ((RC_X_PWM - 1500)/500.0 * rf.params_.get_param_float(PARAM_RC_MAX_ROLL)) using namespace rosflight_firmware; class CommandManagerTest : public ::testing::Test { public: testBoard board; Mavlink mavlink; ROSflight rf; uint16_t rc_values[8]; float max_roll, max_pitch, max_yawrate; control_t offboard_command = { 20000, {true, ANGLE, OFFBOARD_X}, {true, ANGLE, OFFBOARD_Y}, {true, RATE, OFFBOARD_Z}, {true, THROTTLE, OFFBOARD_F} }; CommandManagerTest() : mavlink(board), rf(board,mavlink) {} void SetUp() override { rf.init(); rf.state_manager_.clear_error(rf.state_manager_.state().error_codes); // Clear All Errors to Start rf.params_.set_param_int(PARAM_CALIBRATE_GYRO_ON_ARM, false); for (int i = 0; i < 8; i++) { rc_values[i] = 1500; } rc_values[2] = 1000; rf.params_.set_param_int(PARAM_MIXER, Mixer::PASSTHROUGH); max_roll = rf.params_.get_param_float(PARAM_RC_MAX_ROLL); max_pitch = rf.params_.get_param_float(PARAM_RC_MAX_PITCH); max_yawrate = rf.params_.get_param_float(PARAM_RC_MAX_YAWRATE); } void setOffboard(control_t& command) { command.stamp_ms = rf.board_.clock_millis(); rf.command_manager_.set_new_offboard_command(command); } void stepFirmware(uint32_t us) { uint64_t start_time_us = board.clock_micros(); float dummy_acc[3] = {0, 0, -9.80665}; float dummy_gyro[3] = {0, 0, 0}; while (board.clock_micros() < start_time_us + us) { board.set_imu(dummy_acc, dummy_gyro, board.clock_micros() + 1000); rf.run(); } } }; TEST_F (CommandManagerTest, Default) { board.set_rc(rc_values); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, 0.0); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, 0.0); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, 0.0); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, RCCommands) { rc_values[0] = 2000; rc_values[1] = 1000; rc_values[2] = 1500; rc_values[3] = 1250; board.set_rc(rc_values); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, 1.0*max_roll); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, -1.0*max_pitch); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, -0.5*max_yawrate); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, 0.5); } TEST_F (CommandManagerTest, ArmWithSticksByDefault) { EXPECT_EQ(rf.state_manager_.state().armed, false); rc_values[2] = 1000; rc_values[3] = 2000; board.set_rc(rc_values); stepFirmware(500000); EXPECT_EQ(rf.state_manager_.state().armed, false); // need to wait 1 second, shouldn't be armed yet stepFirmware(600000); EXPECT_EQ(rf.state_manager_.state().armed, true); } TEST_F (CommandManagerTest, DontArmWithSticksWhenUsingSwitch) { rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rc_values[2] = 1000; // throttle low rc_values[3] = 2000; // yaw right board.set_rc(rc_values); stepFirmware(1100000); EXPECT_EQ(rf.state_manager_.state().armed, false); } TEST_F (CommandManagerTest, DisarmWithSticksByDefault) { rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); EXPECT_EQ(rf.state_manager_.state().armed, true); rc_values[2] = 1000; // throttle low rc_values[3] = 1000; // yaw left board.set_rc(rc_values); stepFirmware(1100000); EXPECT_EQ(rf.state_manager_.state().armed, false); } TEST_F (CommandManagerTest, ArmWithSwitch) { rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rc_values[2] = 1000; // throttle low rc_values[4] = CHN_HIGH; // switch on board.set_rc(rc_values); stepFirmware(50000); // Immediate EXPECT_EQ(rf.state_manager_.state().armed, true); } TEST_F (CommandManagerTest, DisarmWithStick) { rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); rc_values[4] = CHN_LOW; // throttle low board.set_rc(rc_values); stepFirmware(50000); // Immediate EXPECT_EQ(rf.state_manager_.state().armed, false); } TEST_F (CommandManagerTest, DontDisarmWithSticksWhenUsingSwitch) { rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rc_values[4] = CHN_HIGH; // switch on rc_values[2] = 1000; // throttle low rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); board.set_rc(rc_values); stepFirmware(50000); EXPECT_EQ(rf.state_manager_.state().armed, true); rc_values[2] = 1000; // throttle low rc_values[3] = 1000; // yaw left stepFirmware(1100000); EXPECT_EQ(rf.state_manager_.state().armed, true); // don't disarm } TEST_F (CommandManagerTest, ArmStickReversed) { rf.params_.set_param_int(PARAM_RC_SWITCH_5_DIRECTION, -1); rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rc_values[2] = 1000; // throttle low rc_values[4] = CHN_LOW; // switch on board.set_rc(rc_values); stepFirmware(50000); // Immediate EXPECT_EQ(rf.state_manager_.state().armed, true); } TEST_F (CommandManagerTest, DisarmStickReversed) { rf.params_.set_param_int(PARAM_RC_SWITCH_5_DIRECTION, -1); rf.params_.set_param_int(PARAM_RC_ARM_CHANNEL, 4); rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); EXPECT_EQ(rf.state_manager_.state().armed, true); rc_values[2] = 1000; // throttle low rc_values[4] = CHN_HIGH; // switch on board.set_rc(rc_values); stepFirmware(50000); // Immediate EXPECT_EQ(rf.state_manager_.state().armed, false); } TEST_F (CommandManagerTest, DefaultRCOutputd) { board.set_rc(rc_values); stepFirmware(600000); // Check the output control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, 0.0); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, 0.0); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, 0.0); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, RCOutput) { rc_values[0] = 1250; rc_values[1] = 1750; rc_values[2] = 1500; rc_values[3] = 2000; board.set_rc(rc_values); stepFirmware(600000); // Check the output EXPECT_EQ(rf.state_manager_.state().armed, false); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, max_roll * -0.5); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, max_pitch * 0.5); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, max_yawrate); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, 0.5); } TEST_F (CommandManagerTest, LoseRCDisarmed) { board.set_pwm_lost(true); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, 0.0*max_roll); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, 0.0*max_pitch); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, 0.0*max_yawrate); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, 0.0); // We should also be disarmed and in error EXPECT_EQ(rf.state_manager_.state().armed, false); EXPECT_EQ(rf.state_manager_.state().failsafe, false); EXPECT_EQ(rf.state_manager_.state().error, true); EXPECT_EQ(rf.state_manager_.state().error_codes, StateManager::ERROR_RC_LOST); } TEST_F (CommandManagerTest, RegainRCDisarmed) { board.set_pwm_lost(true); stepFirmware(40000); board.set_pwm_lost(false); stepFirmware(40000); EXPECT_EQ(rf.state_manager_.state().error, false); EXPECT_EQ(rf.state_manager_.state().error_codes, StateManager::ERROR_NONE); } TEST_F (CommandManagerTest, LoseRCArmed) { board.set_rc(rc_values); stepFirmware(50000); rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); EXPECT_EQ(rf.state_manager_.state().armed, true); board.set_pwm_lost(true); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, ANGLE); EXPECT_CLOSE(output.x.value, 0.0*max_roll); EXPECT_EQ(output.y.type, ANGLE); EXPECT_CLOSE(output.y.value, 0.0*max_pitch); EXPECT_EQ(output.z.type, RATE); EXPECT_CLOSE(output.z.value, 0.0*max_yawrate); EXPECT_EQ(output.F.type, THROTTLE); EXPECT_CLOSE(output.F.value, rf.params_.get_param_float(PARAM_FAILSAFE_THROTTLE)); // We should also be disarmed and in error EXPECT_EQ(rf.state_manager_.state().armed, true); EXPECT_EQ(rf.state_manager_.state().failsafe, true); EXPECT_EQ(rf.state_manager_.state().error, true); EXPECT_EQ(rf.state_manager_.state().error_codes, StateManager::ERROR_RC_LOST); } TEST_F (CommandManagerTest, RegainRCArmed) { board.set_rc(rc_values); stepFirmware(50000); rf.state_manager_.set_event(StateManager::EVENT_REQUEST_ARM); board.set_pwm_lost(true); stepFirmware(20000); board.set_pwm_lost(false); stepFirmware(20000); EXPECT_EQ(rf.state_manager_.state().armed, true); EXPECT_EQ(rf.state_manager_.state().error, false); EXPECT_EQ(rf.state_manager_.state().error_codes, StateManager::ERROR_NONE); } TEST_F (CommandManagerTest, OffboardCommandMuxNoMinThrottle) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, false); // set the new offboard command offboard_command.stamp_ms = board.clock_millis(); rf.command_manager_.set_new_offboard_command(offboard_command); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, OFFBOARD_X); EXPECT_CLOSE(output.y.value, OFFBOARD_Y); EXPECT_CLOSE(output.z.value, OFFBOARD_Z); EXPECT_CLOSE(output.F.value, OFFBOARD_F); } TEST_F (CommandManagerTest, OffboardCommandMuxMinThrottle) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); // set the new offboard command offboard_command.stamp_ms = board.clock_millis(); rf.command_manager_.set_new_offboard_command(offboard_command); stepFirmware(20000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, OFFBOARD_X); EXPECT_CLOSE(output.y.value, OFFBOARD_Y); EXPECT_CLOSE(output.z.value, OFFBOARD_Z); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, OffboardCommandMuxRollDeviation) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); rc_values[0] = 1250; board.set_rc(rc_values); rf.command_manager_.set_new_offboard_command(offboard_command); stepFirmware(40000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, -0.5 * rf.params_.get_param_float(PARAM_RC_MAX_ROLL)); EXPECT_CLOSE(output.y.value, OFFBOARD_Y); EXPECT_CLOSE(output.z.value, OFFBOARD_Z); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, OffboardCommandMuxPitchDeviation) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); rc_values[1] = 1750; board.set_rc(rc_values); rf.command_manager_.set_new_offboard_command(offboard_command); stepFirmware(40000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, OFFBOARD_X); EXPECT_CLOSE(output.y.value, 0.5 * rf.params_.get_param_float(PARAM_RC_MAX_PITCH)); EXPECT_CLOSE(output.z.value, OFFBOARD_Z); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, OffboardCommandMuxYawrateDeviation) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); rc_values[3] = 1250; board.set_rc(rc_values); rf.command_manager_.set_new_offboard_command(offboard_command); stepFirmware(40000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, OFFBOARD_X); EXPECT_CLOSE(output.y.value, OFFBOARD_Y); EXPECT_CLOSE(output.z.value, -0.5 * rf.params_.get_param_float(PARAM_RC_MAX_YAWRATE)); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, OffboardCommandMuxLag) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); rc_values[0] = 1250; board.set_rc(rc_values); setOffboard(offboard_command); stepFirmware(40000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, -0.5 * rf.params_.get_param_float(PARAM_RC_MAX_ROLL)); rc_values[0] = 1500; // return stick to center board.set_rc(rc_values); stepFirmware(500000); setOffboard(offboard_command); output=rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, 0.0); // lag stepFirmware(600000); setOffboard(offboard_command); output=rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, 0.0); // lag setOffboard(offboard_command); stepFirmware(20000); output=rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, OFFBOARD_X); } TEST_F (CommandManagerTest, StaleOffboardCommand) { stepFirmware(1100000); // Get past LAG_TIME rf.params_.set_param_int(PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE, true); setOffboard(offboard_command); int timeout_us = rf.params_.get_param_int(PARAM_OFFBOARD_TIMEOUT)*1000; stepFirmware(timeout_us + 40000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, 0.0); } TEST_F (CommandManagerTest, PartialMux) { offboard_command.x.active = false; stepFirmware(1000000); setOffboard(offboard_command); stepFirmware(30000); control_t output = rf.command_manager_.combined_control(); EXPECT_CLOSE(output.x.value, 0.0); EXPECT_CLOSE(output.y.value, OFFBOARD_Y); EXPECT_CLOSE(output.z.value, OFFBOARD_Z); EXPECT_CLOSE(output.F.value, 0.0); } TEST_F (CommandManagerTest, MixedTypes) { offboard_command.x.type = RATE; stepFirmware(1000000); setOffboard(offboard_command); stepFirmware(30000); control_t output = rf.command_manager_.combined_control(); EXPECT_EQ(output.x.type, RATE); EXPECT_EQ(output.y.type, ANGLE); EXPECT_EQ(output.z.type, RATE); EXPECT_EQ(output.F.type, THROTTLE); }
#include<Game/Strategy/cStrategyObjectBase.h> namespace Game { namespace Strategy { cStrategyObjectBase::cStrategyObjectBase() { }; cStrategyObjectBase::~cStrategyObjectBase() { } ci::vec3 cStrategyObjectBase::getScale() { return scale; } int cStrategyObjectBase::getId() { return id; } bool cStrategyObjectBase::getIsSetting() { return issetting; } } }
#include "group_3d.h" Group3D::Group3D(const QString &name) { setName( name ); } Group3D::~Group3D() { // IObject3D::~IObject3D(); } void Group3D::draw(QOpenGLShaderProgram *program, QOpenGLFunctions *functions) { QMatrix4x4 modelMatrix = createModelMatrix(); for ( const Object3D &obj: __objects ) { obj.get()->setGlobalTransform( modelMatrix ); obj.get()->draw( program, functions ); } } void Group3D::addObject(const Object3D obj) { __objects << obj; } void Group3D::removeObject(const Object3D obj) { __objects.removeOne( obj ); }
#include <iostream> #include <string> #include <vector> #include <fstream> #include "unit_cost_model.h" #include "string_label.h" #include "node.h" #include "bracket_notation_parser.h" #include "lgm_tree_index.h" #include "to_string_converters.h" int main() { // Type aliases. using Label = label::StringLabel; using CostModel = cost_model::UnitCostModelLD<Label>; using LabelDictionary = label::LabelDictionary<Label>; // Initialise label dictionary - separate dictionary for each test tree // becuse it is easier to keep track of label ids. LabelDictionary ld; // Initialise cost model. CostModel ucm(ld); // Parse test cases from file. std::ifstream test_cases_file("lgm_ub_lb_mapping_test_data.txt"); if (!test_cases_file.is_open()) { std::cerr << "Error while opening file." << std::endl; return -1; } // Initialise String Edit Distance algorithm. ted_ub::LGMTreeIndex<CostModel, node::TreeIndexLGM> lgm_algorithm(ucm); // Initialise two tree indexes. // Use TreeIndexAll that is a superset of all algorithms' indexes. node::TreeIndexLGM ti1; node::TreeIndexLGM ti2; parser::BracketNotationParser bnp; // Fixed test cases. std::cout << "--- FIXED TEST ---" << std::endl; // Read test cases from a file line by line. for (std::string line; std::getline( test_cases_file, line);) { if (line[0] == '#') { std::cout << "--- TEST CASE ---" << std::endl; std::cout << line << std::endl; // Read the single test case. std::getline(test_cases_file, line); std::string input_tree_1_string = line; std::getline(test_cases_file, line); std::string input_tree_2_string = line; std::getline(test_cases_file, line); int k = std::stoi(line); std::getline(test_cases_file, line); std::string correct_result = line; // Validate test trees. if (!bnp.validate_input(input_tree_1_string)) { std::cerr << "Incorrect format of source tree: '" << input_tree_1_string << "'. Is the number of opening and closing brackets equal?" << std::endl; return -1; } if (!bnp.validate_input(input_tree_2_string)) { std::cerr << "Incorrect format of destination tree: '" << input_tree_2_string << "'. Is the number of opening and closing brackets equal?" << std::endl; return -1; } // Parse test tree. node::Node<Label> t1 = bnp.parse_single(input_tree_1_string); node::Node<Label> t2 = bnp.parse_single(input_tree_2_string); // Index input trees. node::index_tree(ti1, t1, ld, ucm); node::index_tree(ti2, t2, ld, ucm); std::string computed_results; try { // Internals of LGM need to be initialized between test cases because // `ted_k` is not executed. lgm_algorithm.init(ti2); computed_results = common::vector_to_string(lgm_algorithm.lb_mapping(ti1, ti2, k)); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } if (correct_result != computed_results) { std::cerr << "Incorrect revised mapping: " << computed_results << " instead of " << correct_result << std::endl; std::cerr << "T1: " << input_tree_1_string << std::endl; std::cerr << "T2: " << input_tree_2_string << std::endl; std::cerr << "k: " << k << std::endl; return -1; } } } return 0; }
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Kelidan_The_Breaker SD%Complete: 100 SDComment: SDCategory: Hellfire Citadel, Blood Furnace EndScriptData */ /* ContentData boss_kelidan_the_breaker mob_shadowmoon_channeler EndContentData */ #include "ScriptPCH.h" #include "blood_furnace.h" enum eKelidan { SAY_WAKE = -1542000, SAY_ADD_AGGRO_1 = -1542001, SAY_ADD_AGGRO_2 = -1542002, SAY_ADD_AGGRO_3 = -1542003, SAY_KILL_1 = -1542004, SAY_KILL_2 = -1542005, SAY_NOVA = -1542006, SAY_DIE = -1542007, SPELL_CORRUPTION = 30938, SPELL_EVOCATION = 30935, SPELL_FIRE_NOVA = 33132, H_SPELL_FIRE_NOVA = 37371, SPELL_SHADOW_BOLT_VOLLEY = 28599, H_SPELL_SHADOW_BOLT_VOLLEY = 40070, SPELL_BURNING_NOVA = 30940, SPELL_VORTEX = 37370, ENTRY_KELIDAN = 17377, ENTRY_CHANNELER = 17653 }; const float ShadowmoonChannelers[5][4]= { {302.0f, -87.0f, -24.4f, 0.157f}, {321.0f, -63.5f, -24.6f, 4.887f}, {346.0f, -74.5f, -24.6f, 3.595f}, {344.0f, -103.5f, -24.5f, 2.356f}, {316.0f, -109.0f, -24.6f, 1.257f} }; class boss_kelidan_the_breaker : public CreatureScript { public: boss_kelidan_the_breaker() : CreatureScript("boss_kelidan_the_breaker") { } struct boss_kelidan_the_breakerAI : public ScriptedAI { boss_kelidan_the_breakerAI(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceScript(); for (uint8 i=0; i<5; ++i) Channelers[i] = 0; } InstanceScript* pInstance; uint32 ShadowVolley_Timer; uint32 BurningNova_Timer; uint32 Firenova_Timer; uint32 Corruption_Timer; uint32 check_Timer; bool Firenova; bool addYell; uint64 Channelers[5]; void Reset() { ShadowVolley_Timer = 1000; BurningNova_Timer = 15000; Corruption_Timer = 5000; check_Timer = 0; Firenova = false; addYell = false; SummonChannelers(); if (pInstance) pInstance->SetData(TYPE_KELIDAN_THE_BREAKER_EVENT, NOT_STARTED); } void EnterCombat(Unit* who) { DoScriptText(SAY_WAKE, me); if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(true); DoStartMovement(who); if (pInstance) pInstance->SetData(TYPE_KELIDAN_THE_BREAKER_EVENT, IN_PROGRESS); } void KilledUnit(Unit* /*victim*/) { if (rand()%2) return; DoScriptText(RAND(SAY_KILL_1, SAY_KILL_2), me); } void ChannelerEngaged(Unit* who) { if (who && !addYell) { addYell = true; DoScriptText(RAND(SAY_ADD_AGGRO_1, SAY_ADD_AGGRO_2, SAY_ADD_AGGRO_3), me); } for (uint8 i=0; i<5; ++i) { Creature *channeler = Unit::GetCreature(*me, Channelers[i]); if (who && channeler && !channeler->isInCombat()) channeler->AI()->AttackStart(who); } } void ChannelerDied(Unit* killer) { for (uint8 i=0; i<5; ++i) { Creature *channeler = Unit::GetCreature(*me, Channelers[i]); if (channeler && channeler->isAlive()) return; } if (killer) me->AI()->AttackStart(killer); } uint64 GetChanneled(Creature *channeler1) { SummonChannelers(); if (!channeler1) return NULL; uint8 i; for (i=0; i<5; ++i) { Creature *channeler = Unit::GetCreature(*me, Channelers[i]); if (channeler && channeler->GetGUID() == channeler1->GetGUID()) break; } return Channelers[(i+2)%5]; } void SummonChannelers() { for (uint8 i=0; i<5; ++i) { Creature *channeler = Unit::GetCreature(*me, Channelers[i]); if (!channeler || channeler->isDead()) channeler = me->SummonCreature(ENTRY_CHANNELER, ShadowmoonChannelers[i][0], ShadowmoonChannelers[i][1], ShadowmoonChannelers[i][2], ShadowmoonChannelers[i][3], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 300000); if (channeler) Channelers[i] = channeler->GetGUID(); else Channelers[i] = 0; } } void JustDied(Unit* /*Killer*/) { DoScriptText(SAY_DIE, me); if (!pInstance) return; pInstance->SetData(TYPE_KELIDAN_THE_BREAKER_EVENT, DONE); pInstance->HandleGameObject(pInstance->GetData64(DATA_DOOR1), true); pInstance->HandleGameObject(pInstance->GetData64(DATA_DOOR6), true); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) { if (check_Timer <= diff) { if (!me->IsNonMeleeSpellCasted(false)) DoCast(me, SPELL_EVOCATION); check_Timer = 5000; } else check_Timer -= diff; return; } if (Firenova) { if (Firenova_Timer <= diff) { DoCast(me, SPELL_FIRE_NOVA, true); Firenova = false; ShadowVolley_Timer = 2000; } else Firenova_Timer -=diff; return; } if (ShadowVolley_Timer <= diff) { DoCast(me, SPELL_SHADOW_BOLT_VOLLEY); ShadowVolley_Timer = 5000+rand()%8000; } else ShadowVolley_Timer -=diff; if (Corruption_Timer <= diff) { DoCast(me, SPELL_CORRUPTION); Corruption_Timer = 30000+rand()%20000; } else Corruption_Timer -=diff; if (BurningNova_Timer <= diff) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(true); DoScriptText(SAY_NOVA, me); if (SpellEntry *nova = GET_SPELL(SPELL_BURNING_NOVA)) { if (Aura * aura = Aura::TryCreate(nova, me, me)) aura->ApplyForTargets(); } if (IsHeroic()) DoTeleportAll(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()); BurningNova_Timer = 20000+rand()%8000; Firenova_Timer= 5000; Firenova = true; } else BurningNova_Timer -=diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* Creature) const { return new boss_kelidan_the_breakerAI (Creature); } }; /*###### ## mob_shadowmoon_channeler ######*/ enum eShadowmoon { SPELL_SHADOW_BOLT = 12739, H_SPELL_SHADOW_BOLT = 15472, SPELL_MARK_OF_SHADOW = 30937, SPELL_CHANNELING = 39123 }; class mob_shadowmoon_channeler : public CreatureScript { public: mob_shadowmoon_channeler() : CreatureScript("mob_shadowmoon_channeler") { } struct mob_shadowmoon_channelerAI : public ScriptedAI { mob_shadowmoon_channelerAI(Creature* pCreature) : ScriptedAI(pCreature) { } uint32 ShadowBolt_Timer; uint32 MarkOfShadow_Timer; uint32 check_Timer; void Reset() { ShadowBolt_Timer = 1000+rand()%1000; MarkOfShadow_Timer = 5000+rand()%2000; check_Timer = 0; if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(true); } void EnterCombat(Unit* who) { if (Creature *Kelidan = me->FindNearestCreature(ENTRY_KELIDAN, 100)) CAST_AI(boss_kelidan_the_breaker::boss_kelidan_the_breakerAI, Kelidan->AI())->ChannelerEngaged(who); if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(true); DoStartMovement(who); } void JustDied(Unit* Killer) { if (Creature *Kelidan = me->FindNearestCreature(ENTRY_KELIDAN, 100)) CAST_AI(boss_kelidan_the_breaker::boss_kelidan_the_breakerAI, Kelidan->AI())->ChannelerDied(Killer); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) { if (check_Timer <= diff) { if (!me->IsNonMeleeSpellCasted(false)) if (Creature *Kelidan = me->FindNearestCreature(ENTRY_KELIDAN, 100)) { uint64 channeler = CAST_AI(boss_kelidan_the_breaker::boss_kelidan_the_breakerAI, Kelidan->AI())->GetChanneled(me); if (Unit *channeled = Unit::GetUnit(*me, channeler)) DoCast(channeled, SPELL_CHANNELING); } check_Timer = 5000; } else check_Timer -= diff; return; } if (MarkOfShadow_Timer <= diff) { if (Unit *pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0)) DoCast(pTarget, SPELL_MARK_OF_SHADOW); MarkOfShadow_Timer = 15000+rand()%5000; } else MarkOfShadow_Timer -=diff; if (ShadowBolt_Timer <= diff) { DoCast(me->getVictim(), SPELL_SHADOW_BOLT); ShadowBolt_Timer = 5000+rand()%1000; } else ShadowBolt_Timer -=diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* Creature) const { return new mob_shadowmoon_channelerAI (Creature); } }; void AddSC_boss_kelidan_the_breaker() { new boss_kelidan_the_breaker(); new mob_shadowmoon_channeler(); }
// RUN: rm -f %t // RUN: %clang_cc1 -analyze -analyzer-checker=debug.DumpCFG -analyzer-config cfg-temporary-dtors=true %s > %t 2>&1 // RUN: FileCheck --input-file=%t %s // XPASS: * class A { public: A() {} ~A() {} static A make() { return A(); } operator bool() { return false; } operator int() { return 0; } }; class B { public: B() {} ~B() {} operator bool() { return true; } operator int() { return 1; } operator A() { return A(); } }; void foo(int); void foo(bool); void foo(const A&); void test_binary() { int a = int(A()) + int(B()); foo(int(A()) + int(B())); int b; } void test_and() { bool a = A() && B(); foo(A() && B()); int b; } void test_or() { bool a = A() || B(); foo(A() || B()); int b; } void test_cond() { A a = B() ? A() : A(B()); if (B()) { foo(0); } else { foo(0); } int b; } void test_cond_cref() { const A& a = B() ? A() : A(B()); foo(B() ? A() : A(B())); int b; } void test_cond_implicit() { A a = A() ?: A(); int b; } void test_cond_implicit_cref() { const A& a = A() ?: A(); foo(A() ?: A()); int b; } void test_copy_init() { A a = A(); int b; } void test_cref_init() { const A& a = A(); foo(A()); int b; } void test_call_copy_init() { A a = A::make(); int b; } void test_call_cref_init() { const A& a = A::make(); foo(A::make()); int b; } void test_assign() { int a; a = A(); int b; } class TestCtorInits { int a; int b; public: TestCtorInits(); }; TestCtorInits::TestCtorInits() : a(int(A()) + int(B())) , b() {} class NoReturn { public: ~NoReturn() __attribute__((noreturn)); void f(); }; void test_noreturn1() { int a; NoReturn().f(); int b; } void test_noreturn2() { int a; NoReturn(), 47; int b; } // CHECK: [B1 (ENTRY)] // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B1 (ENTRY)] // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B1.3] // CHECK: 5: [B1.4] (CXXConstructExpr, class A) // CHECK: 6: ~A() (Temporary object destructor) // CHECK: 7: return [B1.5]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: false // CHECK: 2: return [B1.1]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: 0 // CHECK: 2: return [B1.1]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B1 (ENTRY)] // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B1 (ENTRY)] // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: true // CHECK: 2: return [B1.1]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: 1 // CHECK: 2: return [B1.1]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B1.3] // CHECK: 5: [B1.4] (CXXConstructExpr, class A) // CHECK: 6: ~A() (Temporary object destructor) // CHECK: 7: return [B1.5]; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2].operator int // CHECK: 4: [B1.3]() // CHECK: 5: [B1.4] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 6: int([B1.5]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 7: B() (CXXConstructExpr, class B) // CHECK: 8: [B1.7] (BindTemporary) // CHECK: 9: [B1.8].operator int // CHECK: 10: [B1.9]() // CHECK: 11: [B1.10] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 12: int([B1.11]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 13: [B1.6] + [B1.12] // CHECK: 14: int a = int(A().operator int()) + int(B().operator int()); // CHECK: 15: ~B() (Temporary object destructor) // CHECK: 16: ~A() (Temporary object destructor) // CHECK: 17: foo // CHECK: 18: [B1.17] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int)) // CHECK: 19: A() (CXXConstructExpr, class A) // CHECK: 20: [B1.19] (BindTemporary) // CHECK: 21: [B1.20].operator int // CHECK: 22: [B1.21]() // CHECK: 23: [B1.22] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 24: int([B1.23]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 25: B() (CXXConstructExpr, class B) // CHECK: 26: [B1.25] (BindTemporary) // CHECK: 27: [B1.26].operator int // CHECK: 28: [B1.27]() // CHECK: 29: [B1.28] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 30: int([B1.29]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 31: [B1.24] + [B1.30] // CHECK: 32: [B1.18]([B1.31]) // CHECK: 33: ~B() (Temporary object destructor) // CHECK: 34: ~A() (Temporary object destructor) // CHECK: 35: int b; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B10 (ENTRY)] // CHECK: Succs (1): B9 // CHECK: [B1] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: int b; // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: Preds (1): B3 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: [B5.8] && [B4.5] // CHECK: 2: [B5.3]([B3.1]) // CHECK: T: [B5.8] && ... // CHECK: Preds (2): B4 B5 // CHECK: Succs (2): B2 B1 // CHECK: [B4] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B4.1] (BindTemporary) // CHECK: 3: [B4.2].operator _Bool // CHECK: 4: [B4.3]() // CHECK: 5: [B4.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: Preds (1): B5 // CHECK: Succs (1): B3 // CHECK: [B5] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: foo // CHECK: 3: [B5.2] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(_Bool)) // CHECK: 4: A() (CXXConstructExpr, class A) // CHECK: 5: [B5.4] (BindTemporary) // CHECK: 6: [B5.5].operator _Bool // CHECK: 7: [B5.6]() // CHECK: 8: [B5.7] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B5.8] && ... // CHECK: Preds (2): B6 B7 // CHECK: Succs (2): B4 B3 // CHECK: [B6] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: Preds (1): B7 // CHECK: Succs (1): B5 // CHECK: [B7] // CHECK: 1: [B9.5] && [B8.5] // CHECK: 2: bool a = A().operator _Bool() && B().operator _Bool(); // CHECK: T: [B9.5] && ... // CHECK: Preds (2): B8 B9 // CHECK: Succs (2): B6 B5 // CHECK: [B8] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B8.1] (BindTemporary) // CHECK: 3: [B8.2].operator _Bool // CHECK: 4: [B8.3]() // CHECK: 5: [B8.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: Preds (1): B9 // CHECK: Succs (1): B7 // CHECK: [B9] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B9.1] (BindTemporary) // CHECK: 3: [B9.2].operator _Bool // CHECK: 4: [B9.3]() // CHECK: 5: [B9.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B9.5] && ... // CHECK: Preds (1): B10 // CHECK: Succs (2): B8 B7 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B10 (ENTRY)] // CHECK: Succs (1): B9 // CHECK: [B1] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: int b; // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: Preds (1): B3 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: [B5.8] || [B4.5] // CHECK: 2: [B5.3]([B3.1]) // CHECK: T: [B5.8] || ... // CHECK: Preds (2): B4 B5 // CHECK: Succs (2): B1 B2 // CHECK: [B4] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B4.1] (BindTemporary) // CHECK: 3: [B4.2].operator _Bool // CHECK: 4: [B4.3]() // CHECK: 5: [B4.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: Preds (1): B5 // CHECK: Succs (1): B3 // CHECK: [B5] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: foo // CHECK: 3: [B5.2] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(_Bool)) // CHECK: 4: A() (CXXConstructExpr, class A) // CHECK: 5: [B5.4] (BindTemporary) // CHECK: 6: [B5.5].operator _Bool // CHECK: 7: [B5.6]() // CHECK: 8: [B5.7] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B5.8] || ... // CHECK: Preds (2): B6 B7 // CHECK: Succs (2): B3 B4 // CHECK: [B6] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: Preds (1): B7 // CHECK: Succs (1): B5 // CHECK: [B7] // CHECK: 1: [B9.5] || [B8.5] // CHECK: 2: bool a = A().operator _Bool() || B().operator _Bool(); // CHECK: T: [B9.5] || ... // CHECK: Preds (2): B8 B9 // CHECK: Succs (2): B5 B6 // CHECK: [B8] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B8.1] (BindTemporary) // CHECK: 3: [B8.2].operator _Bool // CHECK: 4: [B8.3]() // CHECK: 5: [B8.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: Preds (1): B9 // CHECK: Succs (1): B7 // CHECK: [B9] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B9.1] (BindTemporary) // CHECK: 3: [B9.2].operator _Bool // CHECK: 4: [B9.3]() // CHECK: 5: [B9.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B9.5] || ... // CHECK: Preds (1): B10 // CHECK: Succs (2): B7 B8 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B11 (ENTRY)] // CHECK: Succs (1): B10 // CHECK: [B1] // CHECK: 1: int b; // CHECK: 2: [B7.5].~A() (Implicit destructor) // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: foo // CHECK: 2: [B2.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int)) // CHECK: 3: 0 // CHECK: 4: [B2.2]([B2.3]) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: foo // CHECK: 2: [B3.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int)) // CHECK: 3: 0 // CHECK: 4: [B3.2]([B3.3]) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B4] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: 2: B() (CXXConstructExpr, class B) // CHECK: 3: [B4.2] (BindTemporary) // CHECK: 4: [B4.3].operator _Bool // CHECK: 5: [B4.4]() // CHECK: 6: [B4.5] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: 7: ~B() (Temporary object destructor) // CHECK: T: if [B4.6] // CHECK: Preds (2): B5 B6 // CHECK: Succs (2): B3 B2 // CHECK: [B5] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B6] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: 3: ~A() (Temporary object destructor) // CHECK: 4: ~B() (Temporary object destructor) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B7] // CHECK: 1: [B10.5] ? [B8.6] : [B9.15] // CHECK: 2: [B7.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B7.2] // CHECK: 4: [B7.3] (CXXConstructExpr, class A) // CHECK: 5: A a = B().operator _Bool() ? A() : A(B().operator A()); // CHECK: T: [B10.5] ? ... : ... // CHECK: Preds (2): B8 B9 // CHECK: Succs (2): B5 B6 // CHECK: [B8] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B8.1] (BindTemporary) // CHECK: 3: [B8.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B8.3] // CHECK: 5: [B8.4] (CXXConstructExpr, class A) // CHECK: 6: [B8.5] (BindTemporary) // CHECK: Preds (1): B10 // CHECK: Succs (1): B7 // CHECK: [B9] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B9.1] (BindTemporary) // CHECK: 3: [B9.2].operator A // CHECK: 4: [B9.3]() // CHECK: 5: [B9.4] (ImplicitCastExpr, UserDefinedConversion, class A) // CHECK: 6: [B9.5] (BindTemporary) // CHECK: 7: [B9.6] (ImplicitCastExpr, NoOp, const class A) // CHECK: 8: [B9.7] // CHECK: 9: [B9.8] (CXXConstructExpr, class A) // CHECK: 10: [B9.9] (BindTemporary) // CHECK: 11: A([B9.10]) (CXXFunctionalCastExpr, ConstructorConversion, class A) // CHECK: 12: [B9.11] (ImplicitCastExpr, NoOp, const class A) // CHECK: 13: [B9.12] // CHECK: 14: [B9.13] (CXXConstructExpr, class A) // CHECK: 15: [B9.14] (BindTemporary) // CHECK: Preds (1): B10 // CHECK: Succs (1): B7 // CHECK: [B10] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B10.1] (BindTemporary) // CHECK: 3: [B10.2].operator _Bool // CHECK: 4: [B10.3]() // CHECK: 5: [B10.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B10.5] ? ... : ... // CHECK: Preds (1): B11 // CHECK: Succs (2): B8 B9 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B14 (ENTRY)] // CHECK: Succs (1): B13 // CHECK: [B1] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: 2: int b; // CHECK: 3: [B10.4].~A() (Implicit destructor) // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: 3: ~A() (Temporary object destructor) // CHECK: 4: ~B() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B4] // CHECK: 1: [B7.8] ? [B5.6] : [B6.15] // CHECK: 2: [B4.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B4.2] // CHECK: 4: [B7.3]([B4.3]) // CHECK: T: [B7.8] ? ... : ... // CHECK: Preds (2): B5 B6 // CHECK: Succs (2): B2 B3 // CHECK: [B5] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B5.1] (BindTemporary) // CHECK: 3: [B5.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B5.3] // CHECK: 5: [B5.4] (CXXConstructExpr, class A) // CHECK: 6: [B5.5] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B6] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B6.1] (BindTemporary) // CHECK: 3: [B6.2].operator A // CHECK: 4: [B6.3]() // CHECK: 5: [B6.4] (ImplicitCastExpr, UserDefinedConversion, class A) // CHECK: 6: [B6.5] (BindTemporary) // CHECK: 7: [B6.6] (ImplicitCastExpr, NoOp, const class A) // CHECK: 8: [B6.7] // CHECK: 9: [B6.8] (CXXConstructExpr, class A) // CHECK: 10: [B6.9] (BindTemporary) // CHECK: 11: A([B6.10]) (CXXFunctionalCastExpr, ConstructorConversion, class A) // CHECK: 12: [B6.11] (ImplicitCastExpr, NoOp, const class A) // CHECK: 13: [B6.12] // CHECK: 14: [B6.13] (CXXConstructExpr, class A) // CHECK: 15: [B6.14] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B7] // CHECK: 1: ~B() (Temporary object destructor) // CHECK: 2: foo // CHECK: 3: [B7.2] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(const class A &)) // CHECK: 4: B() (CXXConstructExpr, class B) // CHECK: 5: [B7.4] (BindTemporary) // CHECK: 6: [B7.5].operator _Bool // CHECK: 7: [B7.6]() // CHECK: 8: [B7.7] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B7.8] ? ... : ... // CHECK: Preds (2): B8 B9 // CHECK: Succs (2): B5 B6 // CHECK: [B8] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: Preds (1): B10 // CHECK: Succs (1): B7 // CHECK: [B9] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: 3: ~B() (Temporary object destructor) // CHECK: Preds (1): B10 // CHECK: Succs (1): B7 // CHECK: [B10] // CHECK: 1: [B13.5] ? [B11.6] : [B12.15] // CHECK: 2: [B10.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B10.2] // CHECK: 4: const A &a = B().operator _Bool() ? A() : A(B().operator A()); // CHECK: T: [B13.5] ? ... : ... // CHECK: Preds (2): B11 B12 // CHECK: Succs (2): B8 B9 // CHECK: [B11] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B11.1] (BindTemporary) // CHECK: 3: [B11.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B11.3] // CHECK: 5: [B11.4] (CXXConstructExpr, class A) // CHECK: 6: [B11.5] (BindTemporary) // CHECK: Preds (1): B13 // CHECK: Succs (1): B10 // CHECK: [B12] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B12.1] (BindTemporary) // CHECK: 3: [B12.2].operator A // CHECK: 4: [B12.3]() // CHECK: 5: [B12.4] (ImplicitCastExpr, UserDefinedConversion, class A) // CHECK: 6: [B12.5] (BindTemporary) // CHECK: 7: [B12.6] (ImplicitCastExpr, NoOp, const class A) // CHECK: 8: [B12.7] // CHECK: 9: [B12.8] (CXXConstructExpr, class A) // CHECK: 10: [B12.9] (BindTemporary) // CHECK: 11: A([B12.10]) (CXXFunctionalCastExpr, ConstructorConversion, class A) // CHECK: 12: [B12.11] (ImplicitCastExpr, NoOp, const class A) // CHECK: 13: [B12.12] // CHECK: 14: [B12.13] (CXXConstructExpr, class A) // CHECK: 15: [B12.14] (BindTemporary) // CHECK: Preds (1): B13 // CHECK: Succs (1): B10 // CHECK: [B13] // CHECK: 1: B() (CXXConstructExpr, class B) // CHECK: 2: [B13.1] (BindTemporary) // CHECK: 3: [B13.2].operator _Bool // CHECK: 4: [B13.3]() // CHECK: 5: [B13.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B13.5] ? ... : ... // CHECK: Preds (1): B14 // CHECK: Succs (2): B11 B12 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B8 (ENTRY)] // CHECK: Succs (1): B7 // CHECK: [B1] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: int b; // CHECK: 3: [B4.5].~A() (Implicit destructor) // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B4] // CHECK: 1: [B7.2] ?: [B6.6] // CHECK: 2: [B4.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B4.2] // CHECK: 4: [B4.3] (CXXConstructExpr, class A) // CHECK: 5: A a = A() ?: A(); // CHECK: T: [B7.5] ? ... : ... // CHECK: Preds (2): B5 B6 // CHECK: Succs (2): B2 B3 // CHECK: [B5] // CHECK: 1: [B7.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 2: [B5.1] // CHECK: 3: [B5.2] (CXXConstructExpr, class A) // CHECK: 4: [B5.3] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B6] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B6.1] (BindTemporary) // CHECK: 3: [B6.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B6.3] // CHECK: 5: [B6.4] (CXXConstructExpr, class A) // CHECK: 6: [B6.5] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B7] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B7.1] (BindTemporary) // CHECK: 3: [B7.2].operator _Bool // CHECK: 4: [B7.3]() // CHECK: 5: [B7.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B7.5] ? ... : ... // CHECK: Preds (1): B8 // CHECK: Succs (2): B5 B6 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B13 (ENTRY)] // CHECK: Succs (1): B12 // CHECK: [B1] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: int b; // CHECK: 3: [B9.4].~A() (Implicit destructor) // CHECK: Preds (2): B2 B3 // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B3] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: ~A() (Temporary object destructor) // CHECK: Preds (1): B4 // CHECK: Succs (1): B1 // CHECK: [B4] // CHECK: 1: [B7.5] ?: [B6.6] // CHECK: 2: [B4.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B4.2] // CHECK: 4: [B7.3]([B4.3]) // CHECK: T: [B7.8] ? ... : ... // CHECK: Preds (2): B5 B6 // CHECK: Succs (2): B2 B3 // CHECK: [B5] // CHECK: 1: [B7.5] (ImplicitCastExpr, NoOp, const class A) // CHECK: 2: [B5.1] // CHECK: 3: [B5.2] (CXXConstructExpr, class A) // CHECK: 4: [B5.3] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B6] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B6.1] (BindTemporary) // CHECK: 3: [B6.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B6.3] // CHECK: 5: [B6.4] (CXXConstructExpr, class A) // CHECK: 6: [B6.5] (BindTemporary) // CHECK: Preds (1): B7 // CHECK: Succs (1): B4 // CHECK: [B7] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: 2: foo // CHECK: 3: [B7.2] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(const class A &)) // CHECK: 4: A() (CXXConstructExpr, class A) // CHECK: 5: [B7.4] (BindTemporary) // CHECK: 6: [B7.5].operator _Bool // CHECK: 7: [B7.6]() // CHECK: 8: [B7.7] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B7.8] ? ... : ... // CHECK: Preds (2): B9 B8 // CHECK: Succs (2): B5 B6 // CHECK: [B8] // CHECK: 1: ~A() (Temporary object destructor) // CHECK: Preds (1): B9 // CHECK: Succs (1): B7 // CHECK: [B9] // CHECK: 1: [B12.2] ?: [B11.6] // CHECK: 2: [B9.1] (ImplicitCastExpr, NoOp, const class A) // CHECK: 3: [B9.2] // CHECK: 4: const A &a = A() ?: A(); // CHECK: T: [B12.5] ? ... : ... // CHECK: Preds (2): B10 B11 // CHECK: Succs (2): B7 B8 // CHECK: [B10] // CHECK: 1: [B12.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 2: [B10.1] // CHECK: 3: [B10.2] (CXXConstructExpr, class A) // CHECK: 4: [B10.3] (BindTemporary) // CHECK: Preds (1): B12 // CHECK: Succs (1): B9 // CHECK: [B11] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B11.1] (BindTemporary) // CHECK: 3: [B11.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B11.3] // CHECK: 5: [B11.4] (CXXConstructExpr, class A) // CHECK: 6: [B11.5] (BindTemporary) // CHECK: Preds (1): B12 // CHECK: Succs (1): B9 // CHECK: [B12] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B12.1] (BindTemporary) // CHECK: 3: [B12.2].operator _Bool // CHECK: 4: [B12.3]() // CHECK: 5: [B12.4] (ImplicitCastExpr, UserDefinedConversion, _Bool) // CHECK: T: [B12.5] ? ... : ... // CHECK: Preds (1): B13 // CHECK: Succs (2): B10 B11 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B1.3] // CHECK: 5: [B1.4] (CXXConstructExpr, class A) // CHECK: 6: A a = A(); // CHECK: 7: ~A() (Temporary object destructor) // CHECK: 8: int b; // CHECK: 9: [B1.6].~A() (Implicit destructor) // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2] (ImplicitCastExpr, NoOp, const class A) // CHECK: 4: [B1.3] // CHECK: 5: const A &a = A(); // CHECK: 6: foo // CHECK: 7: [B1.6] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(const class A &)) // CHECK: 8: A() (CXXConstructExpr, class A) // CHECK: 9: [B1.8] (BindTemporary) // CHECK: 10: [B1.9] (ImplicitCastExpr, NoOp, const class A) // CHECK: 11: [B1.10] // CHECK: 12: [B1.7]([B1.11]) // CHECK: 13: ~A() (Temporary object destructor) // CHECK: 14: int b; // CHECK: 15: [B1.5].~A() (Implicit destructor) // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A::make // CHECK: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, class A (*)(void)) // CHECK: 3: [B1.2]() // CHECK: 4: [B1.3] (BindTemporary) // CHECK: 5: [B1.4] (ImplicitCastExpr, NoOp, const class A) // CHECK: 6: [B1.5] // CHECK: 7: [B1.6] (CXXConstructExpr, class A) // CHECK: 8: A a = A::make(); // CHECK: 9: ~A() (Temporary object destructor) // CHECK: 10: int b; // CHECK: 11: [B1.8].~A() (Implicit destructor) // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A::make // CHECK: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, class A (*)(void)) // CHECK: 3: [B1.2]() // CHECK: 4: [B1.3] (BindTemporary) // CHECK: 5: [B1.4] (ImplicitCastExpr, NoOp, const class A) // CHECK: 6: [B1.5] // CHECK: 7: const A &a = A::make(); // CHECK: 8: foo // CHECK: 9: [B1.8] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(const class A &)) // CHECK: 10: A::make // CHECK: 11: [B1.10] (ImplicitCastExpr, FunctionToPointerDecay, class A (*)(void)) // CHECK: 12: [B1.11]() // CHECK: 13: [B1.12] (BindTemporary) // CHECK: 14: [B1.13] (ImplicitCastExpr, NoOp, const class A) // CHECK: 15: [B1.14] // CHECK: 16: [B1.9]([B1.15]) // CHECK: 17: ~A() (Temporary object destructor) // CHECK: 18: int b; // CHECK: 19: [B1.7].~A() (Implicit destructor) // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: int a; // CHECK: 2: A() (CXXConstructExpr, class A) // CHECK: 3: [B1.2] (BindTemporary) // CHECK: 4: [B1.3].operator int // CHECK: 5: [B1.4]() // CHECK: 6: [B1.5] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 7: a // CHECK: 8: [B1.7] = [B1.6] // CHECK: 9: ~A() (Temporary object destructor) // CHECK: 10: int b; // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B2 (ENTRY)] // CHECK: Succs (1): B1 // CHECK: [B1] // CHECK: 1: A() (CXXConstructExpr, class A) // CHECK: 2: [B1.1] (BindTemporary) // CHECK: 3: [B1.2].operator int // CHECK: 4: [B1.3]() // CHECK: 5: [B1.4] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 6: int([B1.5]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 7: B() (CXXConstructExpr, class B) // CHECK: 8: [B1.7] (BindTemporary) // CHECK: 9: [B1.8].operator int // CHECK: 10: [B1.9]() // CHECK: 11: [B1.10] (ImplicitCastExpr, UserDefinedConversion, int) // CHECK: 12: int([B1.11]) (CXXFunctionalCastExpr, NoOp, int) // CHECK: 13: [B1.6] + [B1.12] // CHECK: 14: a([B1.13]) (Member initializer) // CHECK: 15: ~B() (Temporary object destructor) // CHECK: 16: ~A() (Temporary object destructor) // CHECK: 17: /*implicit*/int() // CHECK: 18: b([B1.17]) (Member initializer) // CHECK: Preds (1): B2 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (1): B1 // CHECK: [B3 (ENTRY)] // CHECK: Succs (1): B2 // CHECK: [B1] // CHECK: 1: int b; // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: int a; // CHECK: 2: NoReturn() (CXXConstructExpr, class NoReturn) // CHECK: 3: [B2.2] (BindTemporary) // CHECK: 4: [B2.3].f // CHECK: 5: [B2.4]() // CHECK: 6: ~NoReturn() (Temporary object destructor) // CHECK: Preds (1): B3 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (2): B1 B2 // CHECK: [B3 (ENTRY)] // CHECK: Succs (1): B2 // CHECK: [B1] // CHECK: 1: int b; // CHECK: Succs (1): B0 // CHECK: [B2] // CHECK: 1: int a; // CHECK: 2: NoReturn() (CXXConstructExpr, class NoReturn) // CHECK: 3: [B2.2] (BindTemporary) // CHECK: 4: 47 // CHECK: 5: ... , [B2.4] // CHECK: 6: ~NoReturn() (Temporary object destructor) // CHECK: Preds (1): B3 // CHECK: Succs (1): B0 // CHECK: [B0 (EXIT)] // CHECK: Preds (2): B1 B2
#include <vector> using namespace std; int maxSequence(const std::vector<int>& arr){ //... if(arr.size() == 0){ return 0; } bool negArray = true; for(int i=0; i<arr.size(); i++){ if(arr.at(i) > 0){ negArray = false; } } if(negArray == true){ return 0; } vector<int> vec; for(int i=0;i<arr.size();i++){ vec.push_back(arr.at(i)); int localSum = arr.at(i); for(int j=0;j<arr.size();j++){ if(j>i){ localSum = localSum + arr.at(j); vec.push_back(localSum); } } } bool first = true; int ans; for(int i=0;i<vec.size();i++){ if(first == true){ ans = vec.at(i); first = false; } else { if(vec.at(i)>ans){ ans = vec.at(i); } } } cout << ans << endl; return ans; }
#include "boo/inputdev/IHIDListener.hpp" namespace boo { class HIDListenerNX : public IHIDListener { DeviceFinder& m_finder; public: HIDListenerNX(DeviceFinder& finder) : m_finder(finder) {} bool startScanning() override { return false; } bool stopScanning() override { return false; } bool scanNow() override { return false; } }; std::unique_ptr<IHIDListener> IHIDListenerNew(DeviceFinder& finder) { return std::make_unique<HIDListenerNX>(finder); } } // namespace boo
#include <iostream> #include <algorithm> #include <fstream> #include <vector> #include <limits> #include <sstream> #include <string> #include "windows.h" #include "quicksort.h" #include "bstr.h" int main() { //I begin by declaring some variables that will be used throughout the scope of this program. std::ifstream inputfile; std::ifstream data; std::ofstream results; std::ofstream outputflag; std::string datapath; std::string linestr; std::string directory; std::vector<std::string> allvarnames; std::vector<std::string> varnames; std::vector<std::vector<double> > uniquenums; char buffer[MAX_PATH]; int cases = 0; int current_case; //Now I will obtain the directory of the program in order to locate our input files and place our output files. GetModuleFileName(NULL, buffer, MAX_PATH); directory = std::string(buffer).substr(0,std::string(buffer).find_last_of("\\/")); inputfile.open(directory + "\\uniquevaluesinput.txt"); results.open(directory + "\\uniquevaluesoutput.txt"); if (!inputfile.is_open()) { std::cout << "inputfile does not exist" << std::endl; return 0; } //The first line of inputfile will be the path of the dataset that the user is currently using getline(inputfile,linestr); datapath = linestr; //The second line of inputfile will be the number of cases that the user wishes to analyze getline(inputfile,linestr); if(linestr != "Cases = ALL") { std::stringstream SS(linestr.substr(linestr.find("=") + 2)); SS >> cases; } else{ cases = -1; // we will set cases = -1 if the user wishes to view the entire dataset } //The third line of the inputfile will include the variablenames that the user has sent over. These will be in a comma-delimited format. getline(inputfile,linestr); varnames = split(linestr,','); inputfile.close(); // close the file. //Now we will open the dataset. data.open(datapath); if (!data.is_open()) { std::cout << "data does not exist" << std::endl; return 0; } //Allocate space for our 2-d vector to hold the sets of unique numbers. uniquenums.resize(varnames.size()); //The first line of the dataset will include the variable names of all variables in the dataset. getline(data,linestr); allvarnames = split(linestr,','); // This will be a container that holds all variable names. current_case = 0; // This variable will break the while loop if it reaches the max cases the user has specified. while(getline(data,linestr)) // Begin reading the dataset. { //These first lines will increment the current case by 1, declare an iterator for varnames vector, and establish the current case with a vector of strings. current_case++; std::vector<std::string> case_i = split(linestr,','); size_t i = 0; for(size_t varit=0 ; varit<varnames.size() ; ++varit) { //For each string in our case, a boolean variable will trigger if we find a value we have already seen for that variable. bool match = false; //This while loop will sync our case iterator with the current variables' location in the dataset. //Since allvarnames includes all variables and equals case_i in size, we will push i until allvarnames[i] equals varnames[varit]. //We do not need to reset i to 0 because the list in varnames is forced to follow the same sequence as allvarnames. while(allvarnames[i] != varnames[varit]) { ++i; } //Extract the number with a stringstream. if(case_i[i] != "") { std::stringstream numberstream(case_i[i]); double number = 0; numberstream >> number; //Here we will perform a series of searches and sorts, which I believe is optimal due to the amount of searches and sorts we will perform through the scope of this loop. if(std::binary_search(uniquenums[varit].begin(), uniquenums[varit].end(), number)) match = true; if(match == false) { uniquenums[varit].push_back(number); quicksort(&uniquenums[varit], 0, (uniquenums[varit].size() - 1)); } } } // Break the loop if we reach the potentially specified limit. if(current_case >= cases && cases != -1) break; } //Close the dataset and print the results into our 'results' output txt file. data.close(); if (uniquenums.size() > 0) { for(size_t i=0 ; i<uniquenums.size() ; ++i) { for(size_t j=0 ; j<uniquenums[i].size() ; ++ j) { if(j<uniquenums[i].size() - 1) results << uniquenums[i].at(j) << ','; else results << uniquenums[i].at(j) << std::endl; } } } results.close(); outputflag.open(directory + "\\FLAG.txt"); // Create a flag for VBA to detect that the program here is complete. outputflag.close(); }
/* //@HEADER // ***************************************************************************** // // spec.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // 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 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 OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "vt/config.h" #include "vt/trace/file_spec/spec.h" #include "vt/objgroup/manager.h" #include <fstream> namespace vt { namespace trace { namespace file_spec { void TraceSpec::init(ProxyType in_proxy) { proxy_ = in_proxy; } bool TraceSpec::checkTraceEnabled(SpecIndex in_phase) { vtAssertExpr(has_spec_); for (auto&& elm : spec_mod_) { if (elm.second.testTraceEnabledFor(in_phase)) { return true; } } for (auto&& elm : spec_exact_) { if (elm.second.testTraceEnabledFor(in_phase)) { return true; } } return false; } bool TraceSpec::hasSpec() { if (theConfig()->vt_trace_spec) { if (theConfig()->vt_trace_spec_file == "") { vtAbort( "--vt_trace_spec enabled but no file name is specified:" " --vt_trace_spec_file" ); return false; } else { auto& filename = theConfig()->vt_trace_spec_file; std::ifstream file(filename); if (not file.good()) { auto str = fmt::format( "--vt_trace_spec_file={} is not a valid file", filename ); vtAbort(str); return false; } else { return true; } } } else { return false; } } void TraceSpec::parse() { if (not hasSpec()) { return; } auto& filename = theConfig()->vt_trace_spec_file; std::ifstream file(filename); vtAssertExpr(file.good()); while (!file.eof()) { bool is_mod = false; SpecIndex phase = -1; SpecIndex phase_negative_offset = 0; SpecIndex phase_positive_offset = 0; int c = eatWhitespace(file); /* * Optionally parse an entry that starts with an mod phase: "% ..." * ^ */ if (static_cast<char>(c) == '%') { is_mod = true; // Eat up the '%', move to next file.get(); c = eatWhitespace(file); } /* * Parse phase/mod phase: "[%]10..." * ^^ */ if (std::isdigit(c)) { file >> phase; } c = eatWhitespace(file); /* * Parse negative offset for phase/mod: "[%]10 -5..." * ^^ * This offset must be negative or zero! */ if (std::isdigit(c) or static_cast<char>(c) == '-') { file >> phase_negative_offset; vtAbortIf( phase_negative_offset > 0, fmt::format( "Parsing file \"{}\" error: found offset in negative offset position" " that is > 0: value \"{}\"", filename, phase_negative_offset ) ); } c = eatWhitespace(file); /* * Parse positive offset for phase/mod: "[%]10 -5 5..." * ^ * This offset must be positive or zero! */ if (std::isdigit(c)) { file >> phase_positive_offset; vtAbortIf( phase_positive_offset < 0, fmt::format( "Parsing file \"{}\" error: found offset in positive offset position" " that is < 0: value \"{}\"", filename, phase_positive_offset ) ); } eatWhitespace(file); /* * Entry is complete; eat all the following newlines */ while (file.peek() == '\n') { file.get(); } vt_debug_print( verbose, trace, "TraceSpec::parser: is_mod={}, phase={}, neg={}, pos={}\n", is_mod, phase, phase_negative_offset, phase_positive_offset ); // We have a whole entry, put in the spec; it should not already exist insertSpec( phase, phase_negative_offset, phase_positive_offset, is_mod, is_mod ? spec_mod_ : spec_exact_ ); } has_spec_ = true; } void TraceSpec::broadcastSpec() { auto root = theContext()->getNode(); proxy_.template broadcast<SpecMsg, &TraceSpec::transferSpec>( spec_mod_, spec_exact_, root ); } void TraceSpec::transferSpec(SpecMsg* msg) { // The broadcast will hit all nodes, so the node that it exists on will // ignore it if (not has_spec_) { spec_mod_ = msg->spec_mod_; spec_exact_ = msg->spec_exact_; has_spec_ = true; } } void TraceSpec::insertSpec( SpecIndex phase, SpecIndex neg, SpecIndex pos, bool is_mod, SpecMapType& map ) { vtAbortIf( map.find(phase) != map.end(), fmt::format( "Parsing file \"{}\" error: multiple lines start with the same {}:" " value \"{}{}\"", is_mod ? "mod phase" : "phase", theConfig()->vt_trace_spec_file, is_mod ? "%" : "", phase ) ); map.emplace( std::piecewise_construct, std::forward_as_tuple(phase), std::forward_as_tuple(SpecEntry{phase, neg, pos, is_mod}) ); } int TraceSpec::eatWhitespace(std::ifstream& file) { while (not file.eof() and std::isspace(file.peek()) and file.peek() != '\n') { file.get(); } return file.eof() ? 0 : file.peek(); } /*static*/ typename TraceSpec::ProxyType TraceSpec::construct() { auto proxy = theObjGroup()->makeCollective<TraceSpec>(); proxy.get()->init(proxy); return proxy; } }}} /* end namespace vt::trace::file_spec */
/****************************************************************************** * * Project: GDAL * Purpose: Implements a EXIF directory reader * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * Copyright (c) 2012, Even Rouault <even dot rouault at mines-paris dot org> * * Portions Copyright (c) Her majesty the Queen in right of Canada as * represented by the Minister of National Defence, 2006. * * 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 <vector> #include "cpl_conv.h" #include "cpl_port.h" #include "cpl_error.h" #include "cpl_string.h" #include "cpl_vsi.h" #include "gdal_priv.h" #include "gdalexif.h" using std::vector; CPL_CVSID("$Id$"); static const int MAXSTRINGLENGTH = 65535; static const int EXIFOFFSETTAG = 0x8769; static const int INTEROPERABILITYOFFSET = 0xA005; static const int GPSOFFSETTAG = 0x8825; /************************************************************************/ /* EXIFPrintData() */ /************************************************************************/ static void EXIFPrintData(char* pszData, GUInt16 type, GUInt32 count, const unsigned char* data) { const char* sep = ""; char szTemp[128]; char* pszDataEnd = pszData; pszData[0]='\0'; switch (type) { case TIFF_UNDEFINED: case TIFF_BYTE: for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%#02x", sep, *data++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; case TIFF_SBYTE: for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%d", sep, *(const char *)data++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; case TIFF_ASCII: memcpy( pszData, data, count ); pszData[count] = '\0'; break; case TIFF_SHORT: { const GUInt16 *wp = (const GUInt16*)data; for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%u", sep, *wp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_SSHORT: { const GInt16 *wp = (const GInt16*)data; for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%d", sep, *wp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_LONG: { const GUInt32 *lp = (const GUInt32*)data; for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%lu", sep, (unsigned long) *lp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_SLONG: { const GInt32 *lp = (const GInt32*)data; for(;count>0;count--) { snprintf(szTemp, sizeof(szTemp), "%s%ld", sep, (long) *lp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_RATIONAL: { const GUInt32 *lp = (const GUInt32*)data; // if(bSwabflag) // TIFFSwabArrayOfLong((GUInt32*) data, 2*count); for(;count>0;count--) { if( (lp[0]==0) && (lp[1] == 0) ) { snprintf(szTemp, sizeof(szTemp), "%s(0)",sep); } else{ CPLsnprintf(szTemp, sizeof(szTemp), "%s(%g)", sep, (double) lp[0]/ (double)lp[1]); } sep = " "; lp += 2; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_SRATIONAL: { const GInt32 *lp = (const GInt32*)data; for(;count>0;count--) { CPLsnprintf(szTemp, sizeof(szTemp), "%s(%g)", sep, (float) lp[0]/ (float) lp[1]); sep = " "; lp += 2; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_FLOAT: { const float *fp = (const float *)data; for(;count>0;count--) { CPLsnprintf(szTemp, sizeof(szTemp), "%s%g", sep, *fp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } case TIFF_DOUBLE: { const double *dp = (const double *)data; for(;count>0;count--) { CPLsnprintf(szTemp, sizeof(szTemp), "%s%g", sep, *dp++); sep = " "; if (strlen(szTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH) break; strcat(pszDataEnd,szTemp); pszDataEnd += strlen(pszDataEnd); } break; } default: return; } if (type != TIFF_ASCII && count != 0) { CPLError(CE_Warning, CPLE_AppDefined, "EXIF metadata truncated"); } } /************************************************************************/ /* EXIFExtractMetadata() */ /* */ /* Extract all entry from a IFD */ /************************************************************************/ CPLErr EXIFExtractMetadata(char**& papszMetadata, void *fpInL, int nOffset, int bSwabflag, int nTIFFHEADER, int& nExifOffset, int& nInterOffset, int& nGPSOffset) { /* -------------------------------------------------------------------- */ /* Read number of entry in directory */ /* -------------------------------------------------------------------- */ GUInt16 nEntryCount; VSILFILE * const fp = static_cast<VSILFILE *>(fpInL); if( nOffset > INT_MAX - nTIFFHEADER || VSIFSeekL(fp, nOffset+nTIFFHEADER, SEEK_SET) != 0 || VSIFReadL(&nEntryCount,1,sizeof(GUInt16),fp) != sizeof(GUInt16) ) { CPLError( CE_Failure, CPLE_AppDefined, "Error reading EXIF Directory count at " CPL_FRMT_GUIB, static_cast<vsi_l_offset>(nOffset) + nTIFFHEADER ); return CE_Failure; } if (bSwabflag) TIFFSwabShort(&nEntryCount); // Some apps write empty directories - see bug 1523. if( nEntryCount == 0 ) return CE_None; // Some files are corrupt, a large entry count is a sign of this. if( nEntryCount > 125 ) { CPLError( CE_Warning, CPLE_AppDefined, "Ignoring EXIF directory with unlikely entry count (%d).", nEntryCount ); return CE_Warning; } GDALEXIFTIFFDirEntry *poTIFFDir = static_cast<GDALEXIFTIFFDirEntry *>( CPLMalloc(nEntryCount * sizeof(GDALEXIFTIFFDirEntry)) ); /* -------------------------------------------------------------------- */ /* Read all directory entries */ /* -------------------------------------------------------------------- */ { const unsigned int n = static_cast<int>(VSIFReadL( poTIFFDir, 1,nEntryCount*sizeof(GDALEXIFTIFFDirEntry),fp)); if (n != nEntryCount*sizeof(GDALEXIFTIFFDirEntry)) { CPLError( CE_Failure, CPLE_AppDefined, "Could not read all directories"); CPLFree(poTIFFDir); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Parse all entry information in this directory */ /* -------------------------------------------------------------------- */ vector<char> oTempStorage(MAXSTRINGLENGTH+1, 0); char * const szTemp = &oTempStorage[0]; char szName[128]; GDALEXIFTIFFDirEntry *poTIFFDirEntry = poTIFFDir; for( unsigned int i = nEntryCount; i > 0; i--,poTIFFDirEntry++ ) { if (bSwabflag) { TIFFSwabShort(&poTIFFDirEntry->tdir_tag); TIFFSwabShort(&poTIFFDirEntry->tdir_type); TIFFSwabLong (&poTIFFDirEntry->tdir_count); TIFFSwabLong (&poTIFFDirEntry->tdir_offset); } /* -------------------------------------------------------------------- */ /* Find Tag name in table */ /* -------------------------------------------------------------------- */ szName[0] = '\0'; szTemp[0] = '\0'; for ( const struct tagname *poExifTags = tagnames; poExifTags->tag; poExifTags++) { if(poExifTags->tag == poTIFFDirEntry->tdir_tag) { CPLAssert( NULL != poExifTags && NULL != poExifTags->name ); CPLStrlcpy(szName, poExifTags->name, sizeof(szName)); break; } } if( nOffset == nGPSOffset) { for( const struct gpsname *poGPSTags = gpstags; poGPSTags->tag != 0xffff; poGPSTags++ ) { if( poGPSTags->tag == poTIFFDirEntry->tdir_tag ) { CPLAssert( NULL != poGPSTags && NULL != poGPSTags->name ); CPLStrlcpy(szName, poGPSTags->name, sizeof(szName)); break; } } } /* -------------------------------------------------------------------- */ /* If the tag was not found, look into the interoperability table */ /* -------------------------------------------------------------------- */ if( nOffset == nInterOffset ) { const struct intr_tag *poInterTags = intr_tags; for( ; poInterTags->tag; poInterTags++) if(poInterTags->tag == poTIFFDirEntry->tdir_tag) { CPLAssert( NULL != poInterTags && NULL != poInterTags->name ); CPLStrlcpy(szName, poInterTags->name, sizeof(szName)); break; } } /* -------------------------------------------------------------------- */ /* Save important directory tag offset */ /* -------------------------------------------------------------------- */ // Our current API uses int32 and not uint32 if( poTIFFDirEntry->tdir_offset < INT_MAX ) { if( poTIFFDirEntry->tdir_tag == EXIFOFFSETTAG ) nExifOffset=poTIFFDirEntry->tdir_offset; else if( poTIFFDirEntry->tdir_tag == INTEROPERABILITYOFFSET ) nInterOffset=poTIFFDirEntry->tdir_offset; else if( poTIFFDirEntry->tdir_tag == GPSOFFSETTAG ) nGPSOffset=poTIFFDirEntry->tdir_offset; } /* -------------------------------------------------------------------- */ /* If we didn't recognise the tag just ignore it. To see all */ /* tags comment out the continue. */ /* -------------------------------------------------------------------- */ if( szName[0] == '\0' ) { snprintf( szName, sizeof(szName), "EXIF_%d", poTIFFDirEntry->tdir_tag ); continue; } /* -------------------------------------------------------------------- */ /* For UserComment we need to ignore the language binding and */ /* just return the actual contents. */ /* -------------------------------------------------------------------- */ if( EQUAL(szName,"EXIF_UserComment") ) { poTIFFDirEntry->tdir_type = TIFF_ASCII; if( poTIFFDirEntry->tdir_count >= 8 ) { poTIFFDirEntry->tdir_count -= 8; poTIFFDirEntry->tdir_offset += 8; } } /* -------------------------------------------------------------------- */ /* Make some UNDEFINED or BYTE fields ASCII for readability. */ /* -------------------------------------------------------------------- */ if( EQUAL(szName,"EXIF_ExifVersion") || EQUAL(szName,"EXIF_FlashPixVersion") || EQUAL(szName,"EXIF_MakerNote") || EQUAL(szName,"GPSProcessingMethod") ) poTIFFDirEntry->tdir_type = TIFF_ASCII; /* -------------------------------------------------------------------- */ /* Print tags */ /* -------------------------------------------------------------------- */ const int nDataWidth = TIFFDataWidth((GDALEXIFTIFFDataType) poTIFFDirEntry->tdir_type); const int space = poTIFFDirEntry->tdir_count * nDataWidth; /* Previous multiplication could overflow, hence this additional check */ if( poTIFFDirEntry->tdir_count > static_cast<GUInt32>(MAXSTRINGLENGTH) ) { CPLError( CE_Warning, CPLE_AppDefined, "Too many bytes in tag: %u, ignoring tag.", poTIFFDirEntry->tdir_count ); } else if (nDataWidth == 0 || poTIFFDirEntry->tdir_type >= TIFF_IFD ) { CPLError( CE_Warning, CPLE_AppDefined, "Invalid or unhandled EXIF data type: %d, ignoring tag.", poTIFFDirEntry->tdir_type ); } /* -------------------------------------------------------------------- */ /* This is at most 4 byte data so we can read it from tdir_offset */ /* -------------------------------------------------------------------- */ else if (space >= 0 && space <= 4) { unsigned char data[4]; memcpy(data, &poTIFFDirEntry->tdir_offset, 4); if (bSwabflag) { // Unswab 32bit value, and reswab per data type. TIFFSwabLong((GUInt32*) data); switch (poTIFFDirEntry->tdir_type) { case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabLong((GUInt32*) data); break; case TIFF_SSHORT: case TIFF_SHORT: TIFFSwabArrayOfShort((GUInt16*) data, poTIFFDirEntry->tdir_count); break; default: break; } } /* coverity[overrun-buffer-arg] */ EXIFPrintData(szTemp, poTIFFDirEntry->tdir_type, poTIFFDirEntry->tdir_count, data); } /* -------------------------------------------------------------------- */ /* The data is being read where tdir_offset point to in the file */ /* -------------------------------------------------------------------- */ else if (space > 0 && space < MAXSTRINGLENGTH) { unsigned char *data = (unsigned char *)VSIMalloc(space); if (data) { CPL_IGNORE_RET_VAL(VSIFSeekL(fp,poTIFFDirEntry->tdir_offset+nTIFFHEADER,SEEK_SET)); CPL_IGNORE_RET_VAL(VSIFReadL(data, 1, space, fp)); if (bSwabflag) { switch (poTIFFDirEntry->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((GUInt16*) data, poTIFFDirEntry->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((GUInt32*) data, poTIFFDirEntry->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((GUInt32*) data, 2*poTIFFDirEntry->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) data, poTIFFDirEntry->tdir_count); break; default: break; } } EXIFPrintData(szTemp, poTIFFDirEntry->tdir_type, poTIFFDirEntry->tdir_count, data); CPLFree(data); } } else { CPLError( CE_Warning, CPLE_AppDefined, "Invalid EXIF header size: %ld, ignoring tag.", (long) space ); } papszMetadata = CSLSetNameValue(papszMetadata, szName, szTemp); } CPLFree(poTIFFDir); return CE_None; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: OggVorbisEncoder.Setup.IStaticCodeBook #include "OggVorbisEncoder/Setup/IStaticCodeBook.hpp" // Including type: OggVorbisEncoder.Setup.CodeBookMapType #include "OggVorbisEncoder/Setup/CodeBookMapType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: OggVorbisEncoder.Setup.Templates.FloorBooks namespace OggVorbisEncoder::Setup::Templates::FloorBooks { // Forward declaring type: Line2048X27Class3 class Line2048X27Class3; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3); DEFINE_IL2CPP_ARG_TYPE(::OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*, "OggVorbisEncoder.Setup.Templates.FloorBooks", "Line2048X27Class3"); // Type namespace: OggVorbisEncoder.Setup.Templates.FloorBooks namespace OggVorbisEncoder::Setup::Templates::FloorBooks { // Size: 0x40 #pragma pack(push, 1) // Autogenerated type: OggVorbisEncoder.Setup.Templates.FloorBooks.Line2048X27Class3 // [TokenAttribute] Offset: FFFFFFFF class Line2048X27Class3 : public ::Il2CppObject/*, public ::OggVorbisEncoder::Setup::IStaticCodeBook*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private readonly System.Int32 <Dimensions>k__BackingField // Size: 0x4 // Offset: 0x10 int Dimensions; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: Dimensions and: LengthList char __padding0[0x4] = {}; // private readonly System.Byte[] <LengthList>k__BackingField // Size: 0x8 // Offset: 0x18 ::ArrayW<uint8_t> LengthList; // Field size check static_assert(sizeof(::ArrayW<uint8_t>) == 0x8); // private readonly OggVorbisEncoder.Setup.CodeBookMapType <MapType>k__BackingField // Size: 0x4 // Offset: 0x20 ::OggVorbisEncoder::Setup::CodeBookMapType MapType; // Field size check static_assert(sizeof(::OggVorbisEncoder::Setup::CodeBookMapType) == 0x4); // private readonly System.Int32 <QuantMin>k__BackingField // Size: 0x4 // Offset: 0x24 int QuantMin; // Field size check static_assert(sizeof(int) == 0x4); // private readonly System.Int32 <QuantDelta>k__BackingField // Size: 0x4 // Offset: 0x28 int QuantDelta; // Field size check static_assert(sizeof(int) == 0x4); // private readonly System.Int32 <Quant>k__BackingField // Size: 0x4 // Offset: 0x2C int Quant; // Field size check static_assert(sizeof(int) == 0x4); // private readonly System.Int32 <QuantSequenceP>k__BackingField // Size: 0x4 // Offset: 0x30 int QuantSequenceP; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: QuantSequenceP and: QuantList char __padding6[0x4] = {}; // private readonly System.Int32[] <QuantList>k__BackingField // Size: 0x8 // Offset: 0x38 ::ArrayW<int> QuantList; // Field size check static_assert(sizeof(::ArrayW<int>) == 0x8); public: // Creating interface conversion operator: operator ::OggVorbisEncoder::Setup::IStaticCodeBook operator ::OggVorbisEncoder::Setup::IStaticCodeBook() noexcept { return *reinterpret_cast<::OggVorbisEncoder::Setup::IStaticCodeBook*>(this); } // Get instance field reference: private readonly System.Int32 <Dimensions>k__BackingField int& dyn_$Dimensions$k__BackingField(); // Get instance field reference: private readonly System.Byte[] <LengthList>k__BackingField ::ArrayW<uint8_t>& dyn_$LengthList$k__BackingField(); // Get instance field reference: private readonly OggVorbisEncoder.Setup.CodeBookMapType <MapType>k__BackingField ::OggVorbisEncoder::Setup::CodeBookMapType& dyn_$MapType$k__BackingField(); // Get instance field reference: private readonly System.Int32 <QuantMin>k__BackingField int& dyn_$QuantMin$k__BackingField(); // Get instance field reference: private readonly System.Int32 <QuantDelta>k__BackingField int& dyn_$QuantDelta$k__BackingField(); // Get instance field reference: private readonly System.Int32 <Quant>k__BackingField int& dyn_$Quant$k__BackingField(); // Get instance field reference: private readonly System.Int32 <QuantSequenceP>k__BackingField int& dyn_$QuantSequenceP$k__BackingField(); // Get instance field reference: private readonly System.Int32[] <QuantList>k__BackingField ::ArrayW<int>& dyn_$QuantList$k__BackingField(); // public System.Int32 get_Dimensions() // Offset: 0x766AD8 int get_Dimensions(); // public System.Byte[] get_LengthList() // Offset: 0x766AE0 ::ArrayW<uint8_t> get_LengthList(); // public OggVorbisEncoder.Setup.CodeBookMapType get_MapType() // Offset: 0x766AE8 ::OggVorbisEncoder::Setup::CodeBookMapType get_MapType(); // public System.Int32 get_QuantMin() // Offset: 0x766AF0 int get_QuantMin(); // public System.Int32 get_QuantDelta() // Offset: 0x766AF8 int get_QuantDelta(); // public System.Int32 get_Quant() // Offset: 0x766B00 int get_Quant(); // public System.Int32 get_QuantSequenceP() // Offset: 0x766B08 int get_QuantSequenceP(); // public System.Int32[] get_QuantList() // Offset: 0x766B10 ::ArrayW<int> get_QuantList(); // public System.Void .ctor() // Offset: 0x766B18 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Line2048X27Class3* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Line2048X27Class3*, creationType>())); } }; // OggVorbisEncoder.Setup.Templates.FloorBooks.Line2048X27Class3 #pragma pack(pop) static check_size<sizeof(Line2048X27Class3), 56 + sizeof(::ArrayW<int>)> __OggVorbisEncoder_Setup_Templates_FloorBooks_Line2048X27Class3SizeCheck; static_assert(sizeof(Line2048X27Class3) == 0x40); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_Dimensions // Il2CppName: get_Dimensions template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_Dimensions)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_Dimensions", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_LengthList // Il2CppName: get_LengthList template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_LengthList)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_LengthList", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_MapType // Il2CppName: get_MapType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OggVorbisEncoder::Setup::CodeBookMapType (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_MapType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_MapType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantMin // Il2CppName: get_QuantMin template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantMin)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_QuantMin", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantDelta // Il2CppName: get_QuantDelta template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantDelta)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_QuantDelta", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_Quant // Il2CppName: get_Quant template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_Quant)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_Quant", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantSequenceP // Il2CppName: get_QuantSequenceP template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantSequenceP)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_QuantSequenceP", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantList // Il2CppName: get_QuantList template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<int> (OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::*)()>(&OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::get_QuantList)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3*), "get_QuantList", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Templates::FloorBooks::Line2048X27Class3::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
//===--- DiagnosticConsumer.cpp - Diagnostic Consumer Impl ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the DiagnosticConsumer class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "swift-ast" #include "swift/AST/DiagnosticConsumer.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/Basic/Defer.h" #include "swift/Basic/SourceManager.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace swift; DiagnosticConsumer::~DiagnosticConsumer() = default; llvm::SMLoc DiagnosticConsumer::getRawLoc(SourceLoc loc) { return loc.Value; } LLVM_ATTRIBUTE_UNUSED static bool hasDuplicateFileNames( ArrayRef<FileSpecificDiagnosticConsumer::Subconsumer> subconsumers) { llvm::StringSet<> seenFiles; for (const auto &subconsumer : subconsumers) { if (subconsumer.getInputFileName().empty()) { // We can handle multiple subconsumers that aren't associated with any // file, because they only collect diagnostics that aren't in any of the // special files. This isn't an important use case to support, but also // SmallSet doesn't handle empty strings anyway! continue; } bool isUnique = seenFiles.insert(subconsumer.getInputFileName()).second; if (!isUnique) return true; } return false; } std::unique_ptr<DiagnosticConsumer> FileSpecificDiagnosticConsumer::consolidateSubconsumers( SmallVectorImpl<Subconsumer> &subconsumers) { if (subconsumers.empty()) return nullptr; if (subconsumers.size() == 1) return std::move(subconsumers.front()).consumer; // Cannot use return // llvm::make_unique<FileSpecificDiagnosticConsumer>(subconsumers); because // the constructor is private. return std::unique_ptr<DiagnosticConsumer>( new FileSpecificDiagnosticConsumer(subconsumers)); } FileSpecificDiagnosticConsumer::FileSpecificDiagnosticConsumer( SmallVectorImpl<Subconsumer> &subconsumers) : Subconsumers(std::move(subconsumers)) { assert(!Subconsumers.empty() && "don't waste time handling diagnostics that will never get emitted"); assert(!hasDuplicateFileNames(Subconsumers) && "having multiple subconsumers for the same file is not implemented"); } void FileSpecificDiagnosticConsumer::computeConsumersOrderedByRange( SourceManager &SM) { // Look up each file's source range and add it to the "map" (to be sorted). for (const unsigned subconsumerIndex: indices(Subconsumers)) { const Subconsumer &subconsumer = Subconsumers[subconsumerIndex]; if (subconsumer.getInputFileName().empty()) continue; Optional<unsigned> bufferID = SM.getIDForBufferIdentifier(subconsumer.getInputFileName()); assert(bufferID.hasValue() && "consumer registered for unknown file"); CharSourceRange range = SM.getRangeForBuffer(bufferID.getValue()); ConsumersOrderedByRange.emplace_back( ConsumerAndRange(range, subconsumerIndex)); } // Sort the "map" by buffer /end/ location, for use with std::lower_bound // later. (Sorting by start location would produce the same sort, since the // ranges must not be overlapping, but since we need to check end locations // later it's consistent to sort by that here.) std::sort(ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end()); // Check that the ranges are non-overlapping. If the files really are all // distinct, this should be trivially true, but if it's ever not we might end // up mis-filing diagnostics. assert(ConsumersOrderedByRange.end() == std::adjacent_find(ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(), [](const ConsumerAndRange &left, const ConsumerAndRange &right) { return left.overlaps(right); }) && "overlapping ranges despite having distinct files"); } Optional<FileSpecificDiagnosticConsumer::Subconsumer *> FileSpecificDiagnosticConsumer::subconsumerForLocation(SourceManager &SM, SourceLoc loc) { // Diagnostics with invalid locations always go to every consumer. if (loc.isInvalid()) return None; // What if a there's a FileSpecificDiagnosticConsumer but there are no // subconsumers in it? (This situation occurs for the fix-its // FileSpecificDiagnosticConsumer.) In such a case, bail out now. if (Subconsumers.empty()) return None; // This map is generated on first use and cached, to allow the // FileSpecificDiagnosticConsumer to be set up before the source files are // actually loaded. if (ConsumersOrderedByRange.empty()) { // It's possible to get here while a bridging header PCH is being // attached-to, if there's some sort of AST-reader warning or error, which // happens before CompilerInstance::setUpInputs(), at which point _no_ // source buffers are loaded in yet. In that case we return None, rather // than trying to build a nonsensical map (and actually crashing since we // can't find buffers for the inputs). assert(!Subconsumers.empty()); if (!SM.getIDForBufferIdentifier(Subconsumers.begin()->getInputFileName()) .hasValue()) { assert(llvm::none_of(Subconsumers, [&](const Subconsumer &subconsumer) { return SM.getIDForBufferIdentifier(subconsumer.getInputFileName()) .hasValue(); })); return None; } auto *mutableThis = const_cast<FileSpecificDiagnosticConsumer*>(this); mutableThis->computeConsumersOrderedByRange(SM); } // This std::lower_bound call is doing a binary search for the first range // that /might/ contain 'loc'. Specifically, since the ranges are sorted // by end location, it's looking for the first range where the end location // is greater than or equal to 'loc'. const ConsumerAndRange *possiblyContainingRangeIter = std::lower_bound( ConsumersOrderedByRange.begin(), ConsumersOrderedByRange.end(), loc, [](const ConsumerAndRange &entry, SourceLoc loc) -> bool { return entry.endsAfter(loc); }); if (possiblyContainingRangeIter != ConsumersOrderedByRange.end() && possiblyContainingRangeIter->contains(loc)) { auto *consumerAndRangeForLocation = const_cast<ConsumerAndRange *>(possiblyContainingRangeIter); return &(*this)[*consumerAndRangeForLocation]; } return None; } void FileSpecificDiagnosticConsumer::handleDiagnostic( SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind, StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs, const DiagnosticInfo &Info, const SourceLoc bufferIndirectlyCausingDiagnostic) { HasAnErrorBeenConsumed |= Kind == DiagnosticKind::Error; auto subconsumer = findSubconsumer(SM, Loc, Kind, bufferIndirectlyCausingDiagnostic); if (subconsumer) { subconsumer.getValue()->handleDiagnostic(SM, Loc, Kind, FormatString, FormatArgs, Info, bufferIndirectlyCausingDiagnostic); return; } // Last resort: spray it everywhere for (auto &subconsumer : Subconsumers) subconsumer.handleDiagnostic(SM, Loc, Kind, FormatString, FormatArgs, Info, bufferIndirectlyCausingDiagnostic); } Optional<FileSpecificDiagnosticConsumer::Subconsumer *> FileSpecificDiagnosticConsumer::findSubconsumer( SourceManager &SM, SourceLoc loc, DiagnosticKind Kind, SourceLoc bufferIndirectlyCausingDiagnostic) { // Ensure that a note goes to the same place as the preceeding non-note. switch (Kind) { case DiagnosticKind::Error: case DiagnosticKind::Warning: case DiagnosticKind::Remark: { auto subconsumer = findSubconsumerForNonNote(SM, loc, bufferIndirectlyCausingDiagnostic); SubconsumerForSubsequentNotes = subconsumer; return subconsumer; } case DiagnosticKind::Note: return SubconsumerForSubsequentNotes; } } Optional<FileSpecificDiagnosticConsumer::Subconsumer *> FileSpecificDiagnosticConsumer::findSubconsumerForNonNote( SourceManager &SM, const SourceLoc loc, const SourceLoc bufferIndirectlyCausingDiagnostic) { const auto subconsumer = subconsumerForLocation(SM, loc); if (!subconsumer) return None; // No place to put it; might be in an imported module if ((*subconsumer)->getConsumer()) return subconsumer; // A primary file with a .dia file // Try to put it in the responsible primary input if (bufferIndirectlyCausingDiagnostic.isInvalid()) return None; const auto currentPrimarySubconsumer = subconsumerForLocation(SM, bufferIndirectlyCausingDiagnostic); assert(!currentPrimarySubconsumer || (*currentPrimarySubconsumer)->getConsumer() && "current primary must have a .dia file"); return currentPrimarySubconsumer; } bool FileSpecificDiagnosticConsumer::finishProcessing() { tellSubconsumersToInformDriverOfIncompleteBatchModeCompilation(); // Deliberately don't use std::any_of here because we don't want early-exit // behavior. bool hadError = false; for (auto &subconsumer : Subconsumers) hadError |= subconsumer.getConsumer() && subconsumer.getConsumer()->finishProcessing(); return hadError; } void FileSpecificDiagnosticConsumer:: tellSubconsumersToInformDriverOfIncompleteBatchModeCompilation() { if (!HasAnErrorBeenConsumed) return; for (auto &info : ConsumersOrderedByRange) (*this)[info].informDriverOfIncompleteBatchModeCompilation(); } void NullDiagnosticConsumer::handleDiagnostic( SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind, StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs, const DiagnosticInfo &Info, const SourceLoc) { LLVM_DEBUG({ llvm::dbgs() << "NullDiagnosticConsumer received diagnostic: "; DiagnosticEngine::formatDiagnosticText(llvm::dbgs(), FormatString, FormatArgs); llvm::dbgs() << "\n"; }); } ForwardingDiagnosticConsumer::ForwardingDiagnosticConsumer(DiagnosticEngine &Target) : TargetEngine(Target) {} void ForwardingDiagnosticConsumer::handleDiagnostic( SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind, StringRef FormatString, ArrayRef<DiagnosticArgument> FormatArgs, const DiagnosticInfo &Info, const SourceLoc bufferIndirectlyCausingDiagnostic) { LLVM_DEBUG({ llvm::dbgs() << "ForwardingDiagnosticConsumer received diagnostic: "; DiagnosticEngine::formatDiagnosticText(llvm::dbgs(), FormatString, FormatArgs); llvm::dbgs() << "\n"; }); for (auto *C : TargetEngine.getConsumers()) { C->handleDiagnostic(SM, Loc, Kind, FormatString, FormatArgs, Info, bufferIndirectlyCausingDiagnostic); } }
// // TileData.cpp // AntificialAntelligence // // Created by Jonathan Wood on 14/11/2015. // // #include "TileData.h" //__________________TileData_____________________ TileData::TileData(sf::Sprite newSprite){ sprite = newSprite; } const std::vector<TileTransformation> & TileData::getPossibleTransformations() const{ return posibleTransformations; } //______________TileTransformation_____________ TileTransformation::TileTransformation(AssetLoader::TileType newFinalTileType){ finalTileType = newFinalTileType; } AssetLoader::TileType TileTransformation::getFinalTileType() const{ return finalTileType; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 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 <net.h> #include <chainparams.h> #include <clientversion.h> #include <consensus/consensus.h> #include <crypto/common.h> #include <crypto/sha256.h> #include <primitives/transaction.h> #include <netbase.h> #include <scheduler.h> #include <ui_interface.h> #include <utilstrencodings.h> #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <math.h> // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization. #define FEELER_SLEEP_WINDOW 1 #if !defined(HAVE_MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0 #if !defined(HAVE_MSG_DONTWAIT) #define MSG_DONTWAIT 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1), BF_WHITELIST = (1U << 2), }; const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*"; static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8] static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8] // // Global state variables // bool fDiscover = true; bool fListen = true; bool fRelayTxes = true; CCriticalSection cs_mapLocalHost; std::map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfLimited[NET_MAX] = {}; std::string strSubVersion; limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); void CConnman::AddOneShot(const std::string& strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (const auto& entry : mapLocalHost) { int nScore = entry.second.nScore; int nReachability = entry.first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService(entry.first, entry.second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } //! Convert the pnSeeds6 array into usable address objects. static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; std::vector<CAddress> vSeedsOut; vSeedsOut.reserve(vSeedsIn.size()); for (const auto& seed_in : vSeedsIn) { struct in6_addr ip; memcpy(&ip, seed_in.addr, sizeof(ip)); CAddress addr(CService(ip, seed_in.port), GetDesirableServiceFlags(NODE_NONE)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } return vSeedsOut; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices) { CAddress ret(CService(CNetAddr(),GetListenPort()), nLocalServices); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr, nLocalServices); } ret.nTime = GetAdjustedTime(); return ret; } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode *pnode) { CService addrLocal = pnode->GetAddrLocal(); return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() && !IsLimited(addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertiseLocal(CNode *pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices()); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) { addrLocal.SetIP(pnode->GetAddrLocal()); } if (addrLocal.IsRoutable()) { LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString()); FastRandomContext insecure_rand; pnode->PushAddress(addrLocal, insecure_rand); } } } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } bool RemoveLocal(const CService& addr) { LOCK(cs_mapLocalHost); LogPrintf("RemoveLocal(%s)\n", addr.ToString()); mapLocalHost.erase(addr); return true; } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE || net == NET_INTERNAL) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } CNode* CConnman::FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if ((CNetAddr)pnode->addr == ip) { return pnode; } } return nullptr; } CNode* CConnman::FindNode(const CSubNet& subNet) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (subNet.Match((CNetAddr)pnode->addr)) { return pnode; } } return nullptr; } CNode* CConnman::FindNode(const std::string& addrName) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (pnode->GetAddrName() == addrName) { return pnode; } } return nullptr; } CNode* CConnman::FindNode(const CService& addr) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if ((CService)pnode->addr == addr) { return pnode; } } return nullptr; } bool CConnman::CheckIncomingNonce(uint64_t nonce) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce) return false; } return true; } /** Get the bind address for a socket as CAddress */ static CAddress GetBindAddress(SOCKET sock) { CAddress addr_bind; struct sockaddr_storage sockaddr_bind; socklen_t sockaddr_bind_len = sizeof(sockaddr_bind); if (sock != INVALID_SOCKET) { if (!getsockname(sock, (struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) { addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind); } else { LogPrint(BCLog::NET, "Warning: getsockname failed\n"); } } return addr_bind; } CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure) { if (pszDest == nullptr) { if (IsLocal(addrConnect)) return nullptr; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { LogPrintf("Failed to open new connection, already connected\n"); return nullptr; } } /// debug print LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Resolve const int default_port = Params().GetDefaultPort(); if (pszDest) { std::vector<CService> resolved; if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) { addrConnect = CAddress(resolved[GetRand(resolved.size())], NODE_NONE); if (!addrConnect.IsValid()) { LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s", addrConnect.ToString(), pszDest); return nullptr; } // It is possible that we already have a connection to the IP/port pszDest resolved to. // In that case, drop the connection that was just created, and return the existing CNode instead. // Also store the name we used to connect in that CNode, so that future FindNode() calls to that // name catch this early. LOCK(cs_vNodes); CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->MaybeSetAddrName(std::string(pszDest)); LogPrintf("Failed to open new connection, already connected\n"); return nullptr; } } } // Connect bool connected = false; SOCKET hSocket = INVALID_SOCKET; proxyType proxy; if (addrConnect.IsValid()) { bool proxyConnectionFailed = false; if (GetProxy(addrConnect.GetNetwork(), proxy)) { hSocket = CreateSocket(proxy.proxy); if (hSocket == INVALID_SOCKET) { return nullptr; } connected = ConnectThroughProxy(proxy, addrConnect.ToStringIP(), addrConnect.GetPort(), hSocket, nConnectTimeout, &proxyConnectionFailed); } else { // no proxy needed (none set for target network) hSocket = CreateSocket(addrConnect); if (hSocket == INVALID_SOCKET) { return nullptr; } connected = ConnectSocketDirectly(addrConnect, hSocket, nConnectTimeout); } if (!proxyConnectionFailed) { // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect, fCountFailure); } } else if (pszDest && GetNameProxy(proxy)) { hSocket = CreateSocket(proxy.proxy); if (hSocket == INVALID_SOCKET) { return nullptr; } std::string host; int port = default_port; SplitHostPort(std::string(pszDest), port, host); connected = ConnectThroughProxy(proxy, host, port, hSocket, nConnectTimeout, nullptr); } if (!connected) { CloseSocket(hSocket); return nullptr; } // Add node NodeId id = GetNewNodeId(); uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize(); CAddress addr_bind = GetBindAddress(hSocket); CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", false); pnode->AddRef(); return pnode; } void CConnman::DumpBanlist() { SweepBanned(); // clean unused entries (if bantime has expired) if (!BannedSetIsDirty()) return; int64_t nStart = GetTimeMillis(); CBanDB bandb; banmap_t banmap; GetBanned(banmap); if (bandb.Write(banmap)) { SetBannedSetDirty(false); } LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n", banmap.size(), GetTimeMillis() - nStart); } void CNode::CloseSocketDisconnect() { fDisconnect = true; LOCK(cs_hSocket); if (hSocket != INVALID_SOCKET) { LogPrint(BCLog::NET, "disconnecting peer=%d\n", id); CloseSocket(hSocket); } } void CConnman::ClearBanned() { { LOCK(cs_setBanned); setBanned.clear(); setBannedIsDirty = true; } DumpBanlist(); //store banlist to disk if(clientInterface) clientInterface->BannedListChanged(); } bool CConnman::IsBanned(CNetAddr ip) { LOCK(cs_setBanned); for (const auto& it : setBanned) { CSubNet subNet = it.first; CBanEntry banEntry = it.second; if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) { return true; } } return false; } bool CConnman::IsBanned(CSubNet subnet) { LOCK(cs_setBanned); banmap_t::iterator i = setBanned.find(subnet); if (i != setBanned.end()) { CBanEntry banEntry = (*i).second; if (GetTime() < banEntry.nBanUntil) { return true; } } return false; } void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) { CSubNet subNet(addr); Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch); } void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) { CBanEntry banEntry(GetTime()); banEntry.banReason = banReason; if (bantimeoffset <= 0) { bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME); sinceUnixEpoch = false; } banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset; { LOCK(cs_setBanned); if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) { setBanned[subNet] = banEntry; setBannedIsDirty = true; } else return; } if(clientInterface) clientInterface->BannedListChanged(); { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (subNet.Match((CNetAddr)pnode->addr)) pnode->fDisconnect = true; } } if(banReason == BanReasonManuallyAdded) DumpBanlist(); //store banlist to disk immediately if user requested ban } bool CConnman::Unban(const CNetAddr &addr) { CSubNet subNet(addr); return Unban(subNet); } bool CConnman::Unban(const CSubNet &subNet) { { LOCK(cs_setBanned); if (!setBanned.erase(subNet)) return false; setBannedIsDirty = true; } if(clientInterface) clientInterface->BannedListChanged(); DumpBanlist(); //store banlist to disk immediately return true; } void CConnman::GetBanned(banmap_t &banMap) { LOCK(cs_setBanned); // Sweep the banlist so expired bans are not returned SweepBanned(); banMap = setBanned; //create a thread safe copy } void CConnman::SetBanned(const banmap_t &banMap) { LOCK(cs_setBanned); setBanned = banMap; setBannedIsDirty = true; } void CConnman::SweepBanned() { int64_t now = GetTime(); bool notifyUI = false; { LOCK(cs_setBanned); banmap_t::iterator it = setBanned.begin(); while(it != setBanned.end()) { CSubNet subNet = (*it).first; CBanEntry banEntry = (*it).second; if(now > banEntry.nBanUntil) { setBanned.erase(it++); setBannedIsDirty = true; notifyUI = true; LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString()); } else ++it; } } // update UI if(notifyUI && clientInterface) { clientInterface->BannedListChanged(); } } bool CConnman::BannedSetIsDirty() { LOCK(cs_setBanned); return setBannedIsDirty; } void CConnman::SetBannedSetDirty(bool dirty) { LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag setBannedIsDirty = dirty; } bool CConnman::IsWhitelistedRange(const CNetAddr &addr) { for (const CSubNet& subnet : vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } std::string CNode::GetAddrName() const { LOCK(cs_addrName); return addrName; } void CNode::MaybeSetAddrName(const std::string& addrNameIn) { LOCK(cs_addrName); if (addrName.empty()) { addrName = addrNameIn; } } CService CNode::GetAddrLocal() const { LOCK(cs_addrLocal); return addrLocal; } void CNode::SetAddrLocal(const CService& addrLocalIn) { LOCK(cs_addrLocal); if (addrLocal.IsValid()) { error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString()); } else { addrLocal = addrLocalIn; } } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { stats.nodeid = this->GetId(); X(nServices); X(addr); X(addrBind); { LOCK(cs_filter); X(fRelayTxes); } X(nLastSend); X(nLastRecv); X(nTimeConnected); X(nTimeOffset); stats.addrName = GetAddrName(); X(nVersion); { LOCK(cs_SubVer); X(cleanSubVer); } X(fInbound); X(m_manual_connection); X(nStartingHeight); { LOCK(cs_vSend); X(mapSendBytesPerMsgCmd); X(nSendBytes); } { LOCK(cs_vRecv); X(mapRecvBytesPerMsgCmd); X(nRecvBytes); } X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dMinPing = (((double)nMinPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) CService addrLocalUnlocked = GetAddrLocal(); stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : ""; } #undef X bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete) { complete = false; int64_t nTimeMicros = GetTimeMicros(); LOCK(cs_vRecv); nLastRecv = nTimeMicros / 1000000; nRecvBytes += nBytes; while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { //store received bytes per message command //to prevent a memory DOS, only allow valid commands mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand); if (i == mapRecvBytesPerMsgCmd.end()) i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER); assert(i != mapRecvBytesPerMsgCmd.end()); i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE; msg.nTime = nTimeMicros; complete = true; } } return true; } void CNode::SetSendVersion(int nVersionIn) { // Send version may only be changed in the version message, and // only one version message is allowed per session. We can therefore // treat this value as const and even atomic as long as it's only used // once a version message has been successfully processed. Any attempt to // set this twice is an error. if (nSendVersion != 0) { error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn); } else { nSendVersion = nVersionIn; } } int CNode::GetSendVersion() const { // The send version should always be explicitly set to // INIT_PROTO_VERSION rather than using this value until SetSendVersion // has been called. if (nSendVersion == 0) { error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION); return INIT_PROTO_VERSION; } return nSendVersion; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } hasher.Write((const unsigned char*)pch, nCopy); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } const uint256& CNetMessage::GetMessageHash() const { assert(complete()); if (data_hash.IsNull()) hasher.Finalize(data_hash.begin()); return data_hash; } // requires LOCK(cs_vSend) size_t CConnman::SocketSendData(CNode *pnode) const { auto it = pnode->vSendMsg.begin(); size_t nSentSize = 0; while (it != pnode->vSendMsg.end()) { const auto &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = 0; { LOCK(pnode->cs_hSocket); if (pnode->hSocket == INVALID_SOCKET) break; nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); } if (nBytes > 0) { pnode->nLastSend = GetSystemTimeInSeconds(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; nSentSize += nBytes; if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize; it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); return nSentSize; } struct NodeEvictionCandidate { NodeId id; int64_t nTimeConnected; int64_t nMinPingUsecTime; int64_t nLastBlockTime; int64_t nLastTXTime; bool fRelevantServices; bool fRelayTxes; bool fBloomFilter; CAddress addr; uint64_t nKeyedNetGroup; }; static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nMinPingUsecTime > b.nMinPingUsecTime; } static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nTimeConnected > b.nTimeConnected; } static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nKeyedNetGroup < b.nKeyedNetGroup; } static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block. if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime; if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices; return a.nTimeConnected > b.nTimeConnected; } static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { // There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn. if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime; if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes; if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter; return a.nTimeConnected > b.nTimeConnected; } //! Sort an array by the specified comparator, then erase the last K elements. template<typename T, typename Comparator> static void EraseLastKElements(std::vector<T> &elements, Comparator comparator, size_t k) { std::sort(elements.begin(), elements.end(), comparator); size_t eraseSize = std::min(k, elements.size()); elements.erase(elements.end() - eraseSize, elements.end()); } /** Try to find a connection to evict when the node is full. * Extreme care must be taken to avoid opening the node to attacker * triggered network partitioning. * The strategy used here is to protect a small number of peers * for each of several distinct characteristics which are difficult * to forge. In order to partition a node the attacker must be * simultaneously better at all of them than honest peers. */ bool CConnman::AttemptToEvictConnection() { std::vector<NodeEvictionCandidate> vEvictionCandidates; { LOCK(cs_vNodes); for (const CNode* node : vNodes) { if (node->fWhitelisted) continue; if (!node->fInbound) continue; if (node->fDisconnect) continue; NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime, node->nLastBlockTime, node->nLastTXTime, HasAllDesirableServiceFlags(node->nServices), node->fRelayTxes, node->pfilter != nullptr, node->addr, node->nKeyedNetGroup}; vEvictionCandidates.push_back(candidate); } } // Protect connections with certain characteristics // Deterministically select 4 peers to protect by netgroup. // An attacker cannot predict which netgroups will be protected EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4); // Protect the 8 nodes with the lowest minimum ping time. // An attacker cannot manipulate this metric without physically moving nodes closer to the target. EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8); // Protect 4 nodes that most recently sent us transactions. // An attacker cannot manipulate this metric without performing useful work. EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4); // Protect 4 nodes that most recently sent us blocks. // An attacker cannot manipulate this metric without performing useful work. EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4); // Protect the half of the remaining nodes which have been connected the longest. // This replicates the non-eviction implicit behavior, and precludes attacks that start later. EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, vEvictionCandidates.size() / 2); if (vEvictionCandidates.empty()) return false; // Identify the network group with the most connections and youngest member. // (vEvictionCandidates is already sorted by reverse connect time) uint64_t naMostConnections; unsigned int nMostConnections = 0; int64_t nMostConnectionsTime = 0; std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes; for (const NodeEvictionCandidate &node : vEvictionCandidates) { std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup]; group.push_back(node); int64_t grouptime = group[0].nTimeConnected; if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) { nMostConnections = group.size(); nMostConnectionsTime = grouptime; naMostConnections = node.nKeyedNetGroup; } } // Reduce to the network group with the most connections vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]); // Disconnect from the network group with the most connections NodeId evicted = vEvictionCandidates.front().id; LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (pnode->GetId() == evicted) { pnode->fDisconnect = true; return true; } } return false; } void CConnman::AcceptConnection(const ListenSocket& hListenSocket) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler); if (hSocket != INVALID_SOCKET) { if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) { LogPrintf("Warning: Unknown socket family\n"); } } bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr); { LOCK(cs_vNodes); for (const CNode* pnode : vNodes) { if (pnode->fInbound) nInbound++; } } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); return; } if (!fNetworkActive) { LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString()); CloseSocket(hSocket); return; } if (!IsSelectableSocket(hSocket)) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); CloseSocket(hSocket); return; } // According to the internet TCP_NODELAY is not carried into accepted sockets // on all platforms. Set it again here just to be sure. SetSocketNoDelay(hSocket); if (IsBanned(addr) && !whitelisted) { LogPrint(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); return; } if (nInbound >= nMaxInbound) { if (!AttemptToEvictConnection()) { // No connection to evict, disconnect the new connection LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n"); CloseSocket(hSocket); return; } } NodeId id = GetNewNodeId(); uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize(); CAddress addr_bind = GetBindAddress(hSocket); CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; m_msgproc->InitializeNode(pnode); LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString()); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } void CConnman::ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (!interruptNet) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes std::vector<CNode*> vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; for (CNode* pnode : vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); DeleteNode(pnode); } } } } size_t vNodesSize; { LOCK(cs_vNodes); vNodesSize = vNodes.size(); } if(vNodesSize != nPrevNodeCount) { nPrevNodeCount = vNodesSize; if(clientInterface) clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; for (const ListenSocket& hListenSocket : vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = std::max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is space left in the receive buffer, select() for // receiving data. // * Hand off all complete messages to the processor, to be handled without // blocking here. bool select_recv = !pnode->fPauseRecv; bool select_send; { LOCK(pnode->cs_vSend); select_send = !pnode->vSendMsg.empty(); } LOCK(pnode->cs_hSocket); if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = std::max(hSocketMax, pnode->hSocket); have_fds = true; if (select_send) { FD_SET(pnode->hSocket, &fdsetSend); continue; } if (select_recv) { FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); if (interruptNet) return; if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000))) return; } // // Accept new connections // for (const ListenSocket& hListenSocket : vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { AcceptConnection(hListenSocket); } } // // Service each socket // std::vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) pnode->AddRef(); } for (CNode* pnode : vNodesCopy) { if (interruptNet) return; // // Receive // bool recvSet = false; bool sendSet = false; bool errorSet = false; { LOCK(pnode->cs_hSocket); if (pnode->hSocket == INVALID_SOCKET) continue; recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv); sendSet = FD_ISSET(pnode->hSocket, &fdsetSend); errorSet = FD_ISSET(pnode->hSocket, &fdsetError); } if (recvSet || errorSet) { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = 0; { LOCK(pnode->cs_hSocket); if (pnode->hSocket == INVALID_SOCKET) continue; nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); } if (nBytes > 0) { bool notify = false; if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify)) pnode->CloseSocketDisconnect(); RecordBytesRecv(nBytes); if (notify) { size_t nSizeAdded = 0; auto it(pnode->vRecvMsg.begin()); for (; it != pnode->vRecvMsg.end(); ++it) { if (!it->complete()) break; nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE; } { LOCK(pnode->cs_vProcessMsg); pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it); pnode->nProcessQueueSize += nSizeAdded; pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize; } WakeMessageHandler(); } } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) { LogPrint(BCLog::NET, "socket closed\n"); } pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } // // Send // if (sendSet) { LOCK(pnode->cs_vSend); size_t nBytes = SocketSendData(pnode); if (nBytes) { RecordBytesSent(nBytes); } } // // Inactivity checking // int64_t nTime = GetSystemTimeInSeconds(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId()); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } else if (!pnode->fSuccessfullyConnected) { LogPrintf("version handshake timeout from %d\n", pnode->GetId()); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); for (CNode* pnode : vNodesCopy) pnode->Release(); } } } void CConnman::WakeMessageHandler() { { std::lock_guard<std::mutex> lock(mutexMsgProc); fMsgProcWake = true; } condMsgProc.notify_one(); } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = nullptr; const char * minissdpdpath = nullptr; struct UPNPDev * devlist = nullptr; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { CNetAddr resolved; if(LookupHost(externalIPAddress, resolved, false)) { LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str()); AddLocal(resolved, LOCAL_UPNP); } } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } std::string strDesc = "Bitcoin " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n"); MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (const boost::thread_interrupted&) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r); freeUPNPDevlist(devlist); devlist = nullptr; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = nullptr; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static std::unique_ptr<boost::thread> upnp_thread; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); } upnp_thread.reset(new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort))); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); upnp_thread.reset(); } } #else void MapPort(bool) { // Intentionally left blank. } #endif void CConnman::ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute // Avoiding DNS seeds when we don't need them improves user privacy by // creating fewer identifying DNS requests, reduces trust by giving seeds // less influence on the network topology, and reduces traffic to the seeds. if ((addrman.size() > 0) && (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) { if (!interruptNet.sleep_for(std::chrono::seconds(11))) return; LOCK(cs_vNodes); int nRelevant = 0; for (auto pnode : vNodes) { nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound; } if (nRelevant >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const std::vector<std::string> &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); for (const std::string &seed : vSeeds) { if (interruptNet) { return; } if (HaveNameProxy()) { AddOneShot(seed); } else { std::vector<CNetAddr> vIPs; std::vector<CAddress> vAdd; ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE); std::string host = strprintf("x%x.%s", requiredServiceBits, seed); CNetAddr resolveSource; if (!resolveSource.SetInternal(host)) { continue; } unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed if (LookupHost(host.c_str(), vIPs, nMaxIPs, true)) { for (const CNetAddr& ip : vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } addrman.Add(vAdd, resolveSource); } else { // We now avoid directly using results from DNS Seeds which do not support service bit filtering, // instead using them as a oneshot to get nodes with our desired service bits. AddOneShot(seed); } } } LogPrintf("%d addresses found from DNS seeds\n", found); } void CConnman::DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void CConnman::DumpData() { DumpAddresses(); DumpBanlist(); } void CConnman::ProcessOneShot() { std::string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true); } } bool CConnman::GetTryNewOutboundPeer() { return m_try_another_outbound_peer; } void CConnman::SetTryNewOutboundPeer(bool flag) { m_try_another_outbound_peer = flag; LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false"); } // Return the number of peers we have over our outbound connection limit // Exclude peers that are marked for disconnect, or are going to be // disconnected soon (eg one-shots and feelers) // Also exclude peers that haven't finished initial connection handshake yet // (so that we don't decide we're over our desired connection limit, and then // evict some peer that has finished the handshake) int CConnman::GetExtraOutboundCount() { int nOutbound = 0; { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (!pnode->fInbound && !pnode->m_manual_connection && !pnode->fFeeler && !pnode->fDisconnect && !pnode->fOneShot && pnode->fSuccessfullyConnected) { ++nOutbound; } } } return std::max(nOutbound - nMaxOutbound, 0); } void CConnman::ThreadOpenConnections(const std::vector<std::string> connect) { // Connect to specific addresses if (!connect.empty()) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); for (const std::string& strAddr : connect) { CAddress addr(CService(), NODE_NONE); OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), false, false, true); for (int i = 0; i < 10 && i < nLoop; i++) { if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; } } if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; } } // Initiate network connections int64_t nStart = GetTime(); // Minimum time before next feeler connection (in microseconds). int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL); while (!interruptNet) { ProcessOneShot(); if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; CSemaphoreGrant grant(*semOutbound); if (interruptNet) return; // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); CNetAddr local; local.SetInternal("fixedseeds"); addrman.Add(convertSeed6(Params().FixedSeeds()), local); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; std::set<std::vector<unsigned char> > setConnected; { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { if (!pnode->fInbound && !pnode->m_manual_connection) { // Netgroups for inbound and addnode peers are not excluded because our goal here // is to not use multiple of our limited outbound slots on a single netgroup // but inbound and addnode peers do not use our outbound slots. Inbound peers // also have the added issue that they're attacker controlled and could be used // to prevent us from connecting to particular hosts if we used them here. setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } // Feeler Connections // // Design goals: // * Increase the number of connectable addresses in the tried table. // // Method: // * Choose a random address from new and attempt to connect to it if we can connect // successfully it is added to tried. // * Start attempting feeler connections only after node finishes making outbound // connections. // * Only make a feeler connection once every few minutes. // bool fFeeler = false; if (nOutbound >= nMaxOutbound && !GetTryNewOutboundPeer()) { int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds). if (nTime > nNextFeeler) { nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL); fFeeler = true; } else { continue; } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (!interruptNet) { CAddrInfo addr = addrman.Select(fFeeler); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // for non-feelers, require all the services we'll want, // for feelers, only require they be a full node (only because most // SPV clients don't have a good address DB available) if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) { continue; } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) { continue; } // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) { if (fFeeler) { // Add small amount of random noise before connection to avoid synchronization. int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000); if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep))) return; LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString()); } OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler); } } } std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() { std::vector<AddedNodeInfo> ret; std::list<std::string> lAddresses(0); { LOCK(cs_vAddedNodes); ret.reserve(vAddedNodes.size()); std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses)); } // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService std::map<CService, bool> mapConnected; std::map<std::string, std::pair<bool, CService>> mapConnectedByName; { LOCK(cs_vNodes); for (const CNode* pnode : vNodes) { if (pnode->addr.IsValid()) { mapConnected[pnode->addr] = pnode->fInbound; } std::string addrName = pnode->GetAddrName(); if (!addrName.empty()) { mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr)); } } } for (const std::string& strAddNode : lAddresses) { CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort())); if (service.IsValid()) { // strAddNode is an IP:port auto it = mapConnected.find(service); if (it != mapConnected.end()) { ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second}); } else { ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false}); } } else { // strAddNode is a name auto it = mapConnectedByName.find(strAddNode); if (it != mapConnectedByName.end()) { ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first}); } else { ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false}); } } } return ret; } void CConnman::ThreadOpenAddedConnections() { while (true) { CSemaphoreGrant grant(*semAddnode); std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(); bool tried = false; for (const AddedNodeInfo& info : vInfo) { if (!info.fConnected) { if (!grant.TryAcquire()) { // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting // the addednodeinfo state might change. break; } tried = true; CAddress addr(CService(), NODE_NONE); OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true); if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; } } // Retry every 60 seconds if a connection was attempted, otherwise two seconds if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) return; } } // if successful, this moves the passed grant to the constructed node void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool manual_connection) { // // Initiate outbound network connection // if (interruptNet) { return; } if (!fNetworkActive) { return; } if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return; } else if (FindNode(std::string(pszDest))) return; CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure); if (!pnode) return; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); if (fOneShot) pnode->fOneShot = true; if (fFeeler) pnode->fFeeler = true; if (manual_connection) pnode->m_manual_connection = true; m_msgproc->InitializeNode(pnode); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } void CConnman::ThreadMessageHandler() { while (!flagInterruptMsgProc) { std::vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) { pnode->AddRef(); } } bool fMoreWork = false; for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc); fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend); if (flagInterruptMsgProc) return; // Send messages { LOCK(pnode->cs_sendProcessing); m_msgproc->SendMessages(pnode, flagInterruptMsgProc); } if (flagInterruptMsgProc) return; } { LOCK(cs_vNodes); for (CNode* pnode : vNodesCopy) pnode->Release(); } std::unique_lock<std::mutex> lock(mutexMsgProc); if (!fMoreWork) { condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; }); } fMsgProcWake = false; } } bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = CreateSocket(addrBind); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int)); #endif // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME)); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { std::vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr, 0, true)) { for (const CNetAddr &addr : vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr == nullptr) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void CConnman::SetNetworkActive(bool active) { LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active); if (fNetworkActive == active) { return; } fNetworkActive = active; if (!fNetworkActive) { LOCK(cs_vNodes); // Close sockets to all nodes for (CNode* pnode : vNodes) { pnode->CloseSocketDisconnect(); } } uiInterface.NotifyNetworkActiveChanged(fNetworkActive); } CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In) { fNetworkActive = true; setBannedIsDirty = false; fAddressesInitialized = false; nLastNodeId = 0; nSendBufferMaxSize = 0; nReceiveFloodSize = 0; flagInterruptMsgProc = false; SetTryNewOutboundPeer(false); Options connOptions; Init(connOptions); } NodeId CConnman::GetNewNodeId() { return nLastNodeId.fetch_add(1, std::memory_order_relaxed); } bool CConnman::Bind(const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { if ((flags & BF_REPORT_ERROR) && clientInterface) { clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR); } return false; } return true; } bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) { bool fBound = false; for (const auto& addrBind : binds) { fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } for (const auto& addrBind : whiteBinds) { fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); } if (binds.empty() && whiteBinds.empty()) { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } return fBound; } bool CConnman::Start(CScheduler& scheduler, const Options& connOptions) { Init(connOptions); { LOCK(cs_totalBytesRecv); nTotalBytesRecv = 0; } { LOCK(cs_totalBytesSent); nTotalBytesSent = 0; nMaxOutboundTotalBytesSentInCycle = 0; nMaxOutboundCycleStartTime = 0; } if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) { if (clientInterface) { clientInterface->ThreadSafeMessageBox( _("Failed to listen on any port. Use -listen=0 if you want this."), "", CClientUIInterface::MSG_ERROR); } return false; } for (const auto& strDest : connOptions.vSeedNodes) { AddOneShot(strDest); } if (clientInterface) { clientInterface->InitMessage(_("Loading P2P addresses...")); } // Load addresses from peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (adb.Read(addrman)) LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); else { addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it LogPrintf("Invalid or missing peers.dat; recreating\n"); DumpAddresses(); } } if (clientInterface) clientInterface->InitMessage(_("Loading banlist...")); // Load addresses from banlist.dat nStart = GetTimeMillis(); CBanDB bandb; banmap_t banmap; if (bandb.Read(banmap)) { SetBanned(banmap); // thread save setter SetBannedSetDirty(false); // no need to write down, just read data SweepBanned(); // sweep out unused entries LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n", banmap.size(), GetTimeMillis() - nStart); } else { LogPrintf("Invalid or missing banlist.dat; recreating\n"); SetBannedSetDirty(true); // force write DumpBanlist(); } uiInterface.InitMessage(_("Starting network threads...")); fAddressesInitialized = true; if (semOutbound == nullptr) { // initialize semaphore semOutbound = MakeUnique<CSemaphore>(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections)); } if (semAddnode == nullptr) { // initialize semaphore semAddnode = MakeUnique<CSemaphore>(nMaxAddnode); } // // Start threads // assert(m_msgproc); InterruptSocks5(false); interruptNet.reset(); flagInterruptMsgProc = false; { std::unique_lock<std::mutex> lock(mutexMsgProc); fMsgProcWake = false; } // Send and receive from sockets, accept connections threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this))); if (!gArgs.GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this))); // Initiate outbound connections from -addnode threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this))); if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) { if (clientInterface) { clientInterface->ThreadSafeMessageBox( _("Cannot provide specific connections and have addrman find outgoing connections at the same."), "", CClientUIInterface::MSG_ERROR); } return false; } if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing))); // Process messages threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this))); // Dump network addresses scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000); return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CConnman::Interrupt() { { std::lock_guard<std::mutex> lock(mutexMsgProc); flagInterruptMsgProc = true; } condMsgProc.notify_all(); interruptNet(); InterruptSocks5(true); if (semOutbound) { for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) { semOutbound->post(); } } if (semAddnode) { for (int i=0; i<nMaxAddnode; i++) { semAddnode->post(); } } } void CConnman::Stop() { if (threadMessageHandler.joinable()) threadMessageHandler.join(); if (threadOpenConnections.joinable()) threadOpenConnections.join(); if (threadOpenAddedConnections.joinable()) threadOpenAddedConnections.join(); if (threadDNSAddressSeed.joinable()) threadDNSAddressSeed.join(); if (threadSocketHandler.joinable()) threadSocketHandler.join(); if (fAddressesInitialized) { DumpData(); fAddressesInitialized = false; } // Close sockets for (CNode* pnode : vNodes) pnode->CloseSocketDisconnect(); for (ListenSocket& hListenSocket : vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) for (CNode *pnode : vNodes) { DeleteNode(pnode); } for (CNode *pnode : vNodesDisconnected) { DeleteNode(pnode); } vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); semOutbound.reset(); semAddnode.reset(); } void CConnman::DeleteNode(CNode* pnode) { assert(pnode); bool fUpdateConnectionTime = false; m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime); if(fUpdateConnectionTime) { addrman.Connected(pnode->addr); } delete pnode; } CConnman::~CConnman() { Interrupt(); Stop(); } size_t CConnman::GetAddressCount() const { return addrman.size(); } void CConnman::SetServices(const CService &addr, ServiceFlags nServices) { addrman.SetServices(addr, nServices); } void CConnman::MarkAddressGood(const CAddress& addr) { addrman.Good(addr); } void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty) { addrman.Add(vAddr, addrFrom, nTimePenalty); } std::vector<CAddress> CConnman::GetAddresses() { return addrman.GetAddr(); } bool CConnman::AddNode(const std::string& strNode) { LOCK(cs_vAddedNodes); for (const std::string& it : vAddedNodes) { if (strNode == it) return false; } vAddedNodes.push_back(strNode); return true; } bool CConnman::RemoveAddedNode(const std::string& strNode) { LOCK(cs_vAddedNodes); for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) { if (strNode == *it) { vAddedNodes.erase(it); return true; } } return false; } size_t CConnman::GetNodeCount(NumConnections flags) { LOCK(cs_vNodes); if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total return vNodes.size(); int nNum = 0; for (const auto& pnode : vNodes) { if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) { nNum++; } } return nNum; } void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); for (CNode* pnode : vNodes) { vstats.emplace_back(); pnode->copyStats(vstats.back()); } } bool CConnman::DisconnectNode(const std::string& strNode) { LOCK(cs_vNodes); if (CNode* pnode = FindNode(strNode)) { pnode->fDisconnect = true; return true; } return false; } bool CConnman::DisconnectNode(NodeId id) { LOCK(cs_vNodes); for(CNode* pnode : vNodes) { if (id == pnode->GetId()) { pnode->fDisconnect = true; return true; } } return false; } void CConnman::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CConnman::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; uint64_t now = GetTime(); if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now) { // timeframe expired, reset cycle nMaxOutboundCycleStartTime = now; nMaxOutboundTotalBytesSentInCycle = 0; } // TODO, exclude whitebind peers nMaxOutboundTotalBytesSentInCycle += bytes; } void CConnman::SetMaxOutboundTarget(uint64_t limit) { LOCK(cs_totalBytesSent); nMaxOutboundLimit = limit; } uint64_t CConnman::GetMaxOutboundTarget() { LOCK(cs_totalBytesSent); return nMaxOutboundLimit; } uint64_t CConnman::GetMaxOutboundTimeframe() { LOCK(cs_totalBytesSent); return nMaxOutboundTimeframe; } uint64_t CConnman::GetMaxOutboundTimeLeftInCycle() { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return 0; if (nMaxOutboundCycleStartTime == 0) return nMaxOutboundTimeframe; uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe; uint64_t now = GetTime(); return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime(); } void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe) { LOCK(cs_totalBytesSent); if (nMaxOutboundTimeframe != timeframe) { // reset measure-cycle in case of changing // the timeframe nMaxOutboundCycleStartTime = GetTime(); } nMaxOutboundTimeframe = timeframe; } bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return false; if (historicalBlockServingLimit) { // keep a large enough buffer to at least relay each block once uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle(); uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE; if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) return true; } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) return true; return false; } uint64_t CConnman::GetOutboundTargetBytesLeft() { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return 0; return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle; } uint64_t CConnman::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CConnman::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } ServiceFlags CConnman::GetLocalServices() const { return nLocalServices; } void CConnman::SetBestHeight(int height) { nBestHeight.store(height, std::memory_order_release); } int CConnman::GetBestHeight() const { return nBestHeight.load(std::memory_order_acquire); } unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; } CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string& addrNameIn, bool fInboundIn) : nTimeConnected(GetSystemTimeInSeconds()), addr(addrIn), addrBind(addrBindIn), fInbound(fInboundIn), nKeyedNetGroup(nKeyedNetGroupIn), addrKnown(5000, 0.001), filterInventoryKnown(50000, 0.000001), id(idIn), nLocalHostNonce(nLocalHostNonceIn), nLocalServices(nLocalServicesIn), nMyStartingHeight(nMyStartingHeightIn), nSendVersion(0) { nServices = NODE_NONE; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeOffset = 0; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; m_manual_connection = false; fClient = false; // set by version message fFeeler = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = uint256(); nStartingHeight = -1; filterInventoryKnown.reset(); fSendMempool = false; fGetAddr = false; nNextLocalAddrSend = 0; nNextAddrSend = 0; nNextInvSend = 0; fRelayTxes = false; fSentAddr = false; pfilter = MakeUnique<CBloomFilter>(); timeLastMempoolReq = 0; nLastBlockTime = 0; nLastTXTime = 0; nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; nMinPingUsecTime = std::numeric_limits<int64_t>::max(); minFeeFilter = 0; lastSentFeeFilter = 0; nextSendTimeFeeFilter = 0; fPauseRecv = false; fPauseSend = false; nProcessQueueSize = 0; for (const std::string &msg : getAllNetMessageTypes()) mapRecvBytesPerMsgCmd[msg] = 0; mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0; if (fLogIPs) { LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id); } else { LogPrint(BCLog::NET, "Added connection peer=%d\n", id); } } CNode::~CNode() { CloseSocket(hSocket); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ) return; // a peer may not have multiple non-responded queue positions for a single inv item if (!setAskFor.insert(inv.hash).second) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<uint256, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv.hash); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } bool CConnman::NodeFullyConnected(const CNode* pnode) { return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect; } void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg) { size_t nMessageSize = msg.data.size(); size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE; LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId()); std::vector<unsigned char> serializedHeader; serializedHeader.reserve(CMessageHeader::HEADER_SIZE); uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize); CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize); memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE); CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr}; size_t nBytesSent = 0; { LOCK(pnode->cs_vSend); bool optimisticSend(pnode->vSendMsg.empty()); //log total amount of bytes per command pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize; pnode->nSendSize += nTotalSize; if (pnode->nSendSize > nSendBufferMaxSize) pnode->fPauseSend = true; pnode->vSendMsg.push_back(std::move(serializedHeader)); if (nMessageSize) pnode->vSendMsg.push_back(std::move(msg.data)); // If write queue empty, attempt "optimistic write" if (optimisticSend == true) nBytesSent = SocketSendData(pnode); } if (nBytesSent) RecordBytesSent(nBytesSent); } bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func) { CNode* found = nullptr; LOCK(cs_vNodes); for (auto&& pnode : vNodes) { if(pnode->GetId() == id) { found = pnode; break; } } return found != nullptr && NodeFullyConnected(found) && func(found); } int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) { return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5); } CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const { return CSipHasher(nSeed0, nSeed1).Write(id); } uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const { std::vector<unsigned char> vchNetGroup(ad.GetGroup()); return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize(); }
//---------------------------------*-C++-*-----------------------------------// /*! * \file shift_driver.cpp * \author Steven Hamilton * \date Wed Aug 15 09:25:43 2018 * \brief ShiftDriver class definitions. * \note Copyright (c) 2018 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include <map> #include "smrt/shift_driver.h" #include "Teuchos_DefaultComm.hpp" #include "Teuchos_XMLParameterListHelpers.hpp" #include "Nemesis/comm/global.hh" #include "Omnibus/driver/Sequence_Shift.hh" #include "Omnibus/shift_managers/Shift_Tallies.hh" #include "Shift/mc_tallies/Cell_Union_Tally.hh" namespace enrico { //---------------------------------------------------------------------------// // Constructor //---------------------------------------------------------------------------// ShiftDriver::ShiftDriver(SP_Assembly_Model assembly, std::string shift_input, const std::vector<double>& z_edges) : d_assembly(assembly) , d_power_tally_name("power") { // Build a Teuchos communicator const Teuchos::RCP<const Teuchos::Comm<int>> comm = Teuchos::DefaultComm<int>::getComm(); // Make a temporary Parameter list RCP_PL plist = RCP_PL(new Teuchos::ParameterList("Omnibus_plist_root")); // Save the input XML path for later output plist->set("input_path", shift_input); // Load parameters from disk on processor zero and broadcast them Teuchos::updateParametersFromXmlFileAndBroadcast(shift_input, plist.ptr(), *comm); // Build Problem auto problem = std::make_shared<omnibus::Problem>(plist); // Build driver d_driver = std::make_shared<omnibus::Multiphysics_Driver>(problem); // Store geometry auto problem_geom = problem->geometry(); Expects(problem_geom != nullptr); d_geometry = std::dynamic_pointer_cast<Geometry>(problem_geom); Expects(d_geometry != nullptr); // Create or validate power tally add_power_tally(plist, z_edges); } std::vector<double> ShiftDriver::heat_source(double power) const { // Extract fission rate from Shift tally auto sequence = d_driver->sequence(); auto shift_seq = std::dynamic_pointer_cast<omnibus::Sequence_Shift>(sequence); const auto& tallies = shift_seq->tallies(); std::vector<double> power_by_cell_ID; const auto& cell_tallies = tallies.cell_tallies(); for (const auto& tally : cell_tallies) { if (tally->name() == d_power_tally_name) { // Tally results are volume-integrated, // divide by volume to get volumetric power const auto& result = tally->result(); auto mean = result.mean(0); Expects(result.num_multipliers() == 1); // Compute global sum for normalization double total_power = std::accumulate(mean.begin(), mean.end(), 0.0); for (int cellid = 0; cellid < mean.size(); ++cellid) { double tally_volume = d_geometry->cell_volume(cellid); power_by_cell_ID.push_back(mean[cellid] / tally_volume / total_power); } } } double total_power = 0.0; for (int cellid = 0; cellid < power_by_cell_ID.size(); ++cellid) { total_power += power_by_cell_ID[cellid] * d_geometry->cell_volume(cellid); } nemesis::global_sum(total_power); double norm_factor = power / total_power; for (auto& val : power_by_cell_ID) val *= norm_factor; return power_by_cell_ID; } //---------------------------------------------------------------------------// // Solve //---------------------------------------------------------------------------// void ShiftDriver::solve(const std::vector<double>& th_temperature, const std::vector<double>& coolant_density, std::vector<double>& power) { update_temperature(th_temperature); // currently does nothing update_density(coolant_density); // Rebuild problem (loading any new data needed and run transport d_driver->rebuild(); d_driver->run(); } void ShiftDriver::update_temperature(const std::vector<double>& temperatures) { Expects(temperatures.size() == d_matids.size()); auto& comps = d_driver->compositions(); // Average T/H mesh temperatures onto Shift materials std::vector<double> material_temperatures(d_num_materials, 0.0); for (int elem = 0; elem < temperatures.size(); ++elem) { material_temperatures[d_matids[elem]] += d_vfracs[elem] * temperatures[elem]; } nemesis::global_sum(material_temperatures.data(), d_num_materials); for (int matid = 0; matid < d_num_materials; ++matid) { if (material_temperatures[matid] > 0.0) comps[matid]->set_temperature(material_temperatures[matid]); } } //---------------------------------------------------------------------------// // Register list of centroids and cell volumes from T/H solver //---------------------------------------------------------------------------// void ShiftDriver::set_centroids_and_volumes( const std::vector<enrico::Position>& centroids, const std::vector<double>& volumes) { assert(centroids.size() == volumes.size()); d_matids.resize(centroids.size()); std::vector<int> cells(centroids.size()); for (int elem = 0; elem < centroids.size(); ++elem) { const auto& c = centroids[elem]; // Find geometric cell and corresponding material cells[elem] = d_geometry->find_cell({c.x, c.y, c.z}); d_matids[elem] = d_geometry->matid(cells[elem]); } // Compute per-material volume d_num_materials = d_driver->compositions().size(); d_num_shift_cells = d_geometry->num_cells(); d_power_map.resize(d_num_shift_cells); std::vector<double> mat_volumes(d_num_materials, 0.0); for (int elem = 0; elem < volumes.size(); ++elem) { int matid = d_matids[elem]; assert(matid < d_num_materials); mat_volumes[matid] += volumes[elem]; d_power_map[cells[elem]].push_back(elem); } // Perform global reduction of material volumes nemesis::global_sum(mat_volumes.data(), d_num_materials); // Convert volumes to volume fractions d_vfracs.resize(volumes.size()); for (int elem = 0; elem < volumes.size(); ++elem) { int matid = d_matids[elem]; d_vfracs[elem] = volumes[elem] / mat_volumes[matid]; } int num_cells = d_geometry->num_cells(); std::vector<double> cell_volumes(num_cells, 0.0); for (int elem = 0; elem < centroids.size(); ++elem) { const auto& c = centroids[elem]; int cell = d_geometry->find_cell({c.x, c.y, c.z}); cell_volumes[cell] += volumes[elem]; } } //---------------------------------------------------------------------------// // Add power (fission rate) tally to shift problem //---------------------------------------------------------------------------// void ShiftDriver::add_power_tally(RCP_PL& pl, const std::vector<double>& z_edges) { Expects(d_assembly != nullptr); auto tally_pl = Teuchos::sublist(pl, "TALLY"); auto cell_pl = Teuchos::sublist(tally_pl, "CELL"); using Array_Int = Teuchos::Array<int>; using Array_Dbl = Teuchos::Array<double>; using Array_Str = Teuchos::Array<std::string>; if (!cell_pl->isSublist("power")) { // If "power" tally doesn't exist, create it auto power_pl = Teuchos::sublist(cell_pl, "power"); power_pl->set("name", d_power_tally_name); power_pl->set("normalization", 1.0); power_pl->set("description", std::string("power tally")); Teuchos::Array<std::string> rxns(1, "fission"); power_pl->set("reactions", rxns); power_pl->set("cycles", std::string("active")); Array_Str cells(d_geometry->num_cells()); for (int cellid = 0; cellid < d_geometry->num_cells(); ++cellid) cells[cellid] = std::to_string(cellid); Array_Int counts(d_geometry->num_cells(), 1); power_pl->set("union_cells", cells); power_pl->set("union_lengths", counts); } else { // If it exists, make sure it aligns with assembly auto power_pl = Teuchos::sublist(cell_pl, "power"); Validate(d_power_tally_name == power_pl->get<std::string>("name"), "Incorrect power tally name"); auto rxns = power_pl->get<Array_Str>("reactions"); Validate(rxns.size() == 1, "Incorrect number of reactions in power tally"); Validate(rxns[0] == "fission", "Incorrect reaction in power tally"); Validate(power_pl->get<std::string>("cycles") == "active", "Incorrect cycle designation in power tally."); Validate(power_pl->get<std::string>("type") == "grid", "Incorrect mesh type in power tally."); // Check x edges const auto& x_edges = d_assembly->x_edges(); const auto& x_tally = power_pl->get<Array_Dbl>("x"); Validate(x_tally.size() == x_edges.size(), "Tally specifies incorrect size of x edges"); for (int i = 0; i < x_edges.size(); ++i) Validate(nemesis::soft_equiv(x_edges[i], x_tally[i]), "Tally specifies incorrect x edge"); // Check y edges const auto& y_edges = d_assembly->y_edges(); const auto& y_tally = power_pl->get<Array_Dbl>("y"); Validate(y_tally.size() == y_edges.size(), "Tally specifies incorrect size of y edges"); for (int i = 0; i < y_edges.size(); ++i) Validate(nemesis::soft_equiv(y_edges[i], y_tally[i]), "Tally specifies incorrect y edge"); // Check z edges const auto& z_tally = power_pl->get<Array_Dbl>("z"); Validate(z_tally.size() == z_edges.size(), "Tally specifies incorrect size of z edges"); for (int i = 0; i < z_edges.size(); ++i) Validate(nemesis::soft_equiv(z_edges[i], z_tally[i]), "Tally specifies incorrect z edge"); } } //---------------------------------------------------------------------------// } // end namespace enrico //---------------------------------------------------------------------------// // end of shift_driver.cpp //---------------------------------------------------------------------------//
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2015 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | 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 "hphp/runtime/ext/soap/soap.h" #include "hphp/runtime/ext/soap/encoding.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// SoapData::SoapData() : m_cache(WSDL_CACHE_MEMORY), m_cache_ttl(86400) { for (int i = 0; s_defaultEncoding[i].type != END_KNOWN_TYPES; ++i) { encodeStatic &e = s_defaultEncoding[i]; auto enc = std::make_shared<encode>(); enc->details.type = e.type; enc->details.type_str = e.type_str; enc->details.ns = e.ns; enc->to_zval = e.to_zval; enc->to_xml = e.to_xml; const encodeType &details = enc->details; if (!details.type_str.empty()) { std::string name = details.type_str; if (!details.ns.empty()) { name = std::string(details.ns) + ':' + name; } m_defEnc[name] = enc; } if (m_defEncIndex.find(details.type) == m_defEncIndex.end()) { m_defEncIndex[details.type] = enc; } } m_defEncNs[XSD_1999_NAMESPACE] = XSD_NS_PREFIX; m_defEncNs[XSD_NAMESPACE] = XSD_NS_PREFIX; m_defEncNs[XSI_NAMESPACE] = XSI_NS_PREFIX; m_defEncNs[XML_NAMESPACE] = XML_NS_PREFIX; m_defEncNs[SOAP_1_1_ENC_NAMESPACE] = SOAP_1_1_ENC_NS_PREFIX; m_defEncNs[SOAP_1_2_ENC_NAMESPACE] = SOAP_1_2_ENC_NS_PREFIX; } sdl *SoapData::get_sdl(const char *uri, long cache_wsdl, HttpClient *http /* = nullptr */) { sdlPtr sdl = get_sdl_impl(uri, cache_wsdl, http); if (sdl) { // holding it for the entire request life time, so soapserver and // soapclient can use sdl* without being deleted m_sdls.insert(sdl); return sdl.get(); } return nullptr; } encodeMap *SoapData::register_typemap(encodeMapPtr typemap) { if (typemap) { // holding it for the entire request life time, so soapserver and // soapclient can use encodeMap* without being deleted m_typemaps.insert(typemap); return typemap.get(); } return nullptr; } void SoapData::register_encoding(xmlCharEncodingHandlerPtr encoding) { if (encoding) { m_encodings.insert(encoding); } } sdlPtr SoapData::get_sdl_impl(const char *uri, long cache_wsdl, HttpClient *http) { if (cache_wsdl & WSDL_CACHE_MEMORY) { sdlCache::iterator iter = m_mem_cache.find(uri); if (iter != m_mem_cache.end()) { auto p = iter->second; if (p->time >= time(0) - m_cache_ttl) { return p->sdl; } /* in-memory cache entry is expired */ m_mem_cache.erase(iter); } } const char *old = m_error_code; m_error_code = "WSDL"; sdlPtr sdl = load_wsdl((char*)uri, http); m_error_code = old; if (sdl && (cache_wsdl & WSDL_CACHE_MEMORY)) { auto p = std::make_shared<sdlCacheBucket>(); p->sdl = sdl; p->time = time(0); m_mem_cache[uri] = p; } return sdl; } void SoapData::reset() { m_soap_version = SOAP_1_1; m_sdl = nullptr; m_encoding = nullptr; m_classmap.reset(); m_typemap = nullptr; m_features = 0; m_use_soap_error_handler = false; m_error_code = nullptr; m_error_object.reset(); m_cur_uniq_ns = 0; m_cur_uniq_ref = 0; m_ref_map.reset(); m_sdls.clear(); m_typemaps.clear(); for (auto& handler : m_encodings) { xmlCharEncCloseFunc(handler); } m_encodings.clear(); } IMPLEMENT_REQUEST_LOCAL(SoapData, s_soap_data); /////////////////////////////////////////////////////////////////////////////// SoapException::SoapException(const char *fmt, ...) { va_list ap; va_start(ap, fmt); format((std::string("SOAP_ERROR: ") + fmt).c_str(), ap); va_end(ap); } /////////////////////////////////////////////////////////////////////////////// }
/*============================================================================= 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_RANGE_ALGORITHM_UNIQUE_HPP #define SPROUT_RANGE_ALGORITHM_UNIQUE_HPP #include <sprout/config.hpp> #include <sprout/range/algorithm/cxx14/unique.hpp> #endif // #ifndef SPROUT_RANGE_ALGORITHM_UNIQUE_HPP