text
stringlengths 5
1.04M
|
|---|
/*
Copyright 2016 Tommi M. Tykkälä
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 "PointCloud3D.h"
// CUDA
#include <cuda_runtime.h>
#include <cutil_inline.h>
PointCloud3D::PointCloud3D( int numMaxPoints )
{
nSamplePoints = 0;
nSupportPoints = 0;
nMaxPoints = numMaxPoints;
refPoints3d = new float[numMaxPoints*3]; refSupport3d = new float[numMaxPoints*3];
refPoints2d = new float[numMaxPoints*2]; refSupport2d = new float[numMaxPoints*2];
tmpPoints3d = new float[numMaxPoints*3];
curPoints3d = new float[numMaxPoints*3];
curPoints2d = new float[numMaxPoints*2];
offsets = new unsigned int[numMaxPoints];
colors = new unsigned char[numMaxPoints];
supportOffsets = new unsigned int[numMaxPoints];
supportColors = new unsigned char[numMaxPoints];
curPointsdZ1 = new float[numMaxPoints];
curPointsdZ2 = new float[numMaxPoints];
curPointsdZ3 = new float[numMaxPoints];
curPointsdZ4 = new float[numMaxPoints];
curPointsdZ5 = new float[numMaxPoints];
curPointsdZ6 = new float[numMaxPoints];
points2d_dx1 = new float[numMaxPoints*2];
points2d_dx2 = new float[numMaxPoints*2];
points2d_dx3 = new float[numMaxPoints*2];
points2d_dx4 = new float[numMaxPoints*2];
points2d_dx5 = new float[numMaxPoints*2];
points2d_dx6 = new float[numMaxPoints*2];
points2d_dxz = new float[numMaxPoints*2];
differentialsComputed = false;
}
PointCloud3D::~PointCloud3D()
{
delete[] refPoints2d;
delete[] refSupport2d;
delete[] refPoints3d;
delete[] tmpPoints3d;
delete[] refSupport3d;
delete[] curPoints2d;
delete[] curPoints3d;
delete[] curPointsdZ1;
delete[] curPointsdZ2;
delete[] curPointsdZ3;
delete[] curPointsdZ4;
delete[] curPointsdZ5;
delete[] curPointsdZ6;
delete[] offsets;
delete[] colors;
delete[] supportOffsets;
delete[] supportColors;
delete[] points2d_dx1;
delete[] points2d_dx2;
delete[] points2d_dx3;
delete[] points2d_dx4;
delete[] points2d_dx5;
delete[] points2d_dx6;
delete[] points2d_dxz;
}
void PointCloud3D::addRefPoint( float x, float y, float z, unsigned int offset, unsigned char color, float i, float j)
{
refPoints3d[nSamplePoints*3+0] = x;
refPoints3d[nSamplePoints*3+1] = y;
refPoints3d[nSamplePoints*3+2] = z;
refPoints2d[nSamplePoints*2+0] = i;
refPoints2d[nSamplePoints*2+1] = j;
offsets[nSamplePoints] = offset;
colors[nSamplePoints] = color;
nSamplePoints++;
}
void PointCloud3D::addRefPointSupport( float x, float y, float z, unsigned int offset, unsigned char color, float i, float j)
{
refSupport3d[nSupportPoints*3+0] = x;
refSupport3d[nSupportPoints*3+1] = y;
refSupport3d[nSupportPoints*3+2] = z;
refSupport2d[nSupportPoints*2+0] = i;
refSupport2d[nSupportPoints*2+1] = j;
supportOffsets[nSupportPoints] = offset;
supportColors[nSupportPoints] = color;
nSupportPoints++;
}
void PointCloud3D::reset() {
nSamplePoints = 0;
nSupportPoints = 0;
differentialsComputed = false;
}
void PointCloud3D::updateRefDevice() {
if (nSupportPoints > 0) {
// copy support points on device to same memory buffer with sample points
// this allows single warp call for all points
memcpy(refPoints3d+nSamplePoints*3,refSupport3d,nSupportPoints*sizeof(float)*3);
memcpy(colors+nSamplePoints,supportColors,nSupportPoints*sizeof(char));
memcpy(offsets+nSamplePoints,supportOffsets,nSupportPoints*sizeof(int));
}
}
|
#include "formatter.h"
#include <iterator>
const std::string Format::nullString(" null");
void Formatter::format(Format & source,
std::vector<AttributeWrapper*> & attributes, Format & dest) {
source.readFileHeader();
dest.writeFileHeader();
/*
Reading the rows one by one.
*/
while (!source.isTheEnd()) {
// process each column in a line/row/tuple
source.readRowHeader();
dest.writeRowHeader();
// printf("Attributes size: %lu\n", attributes.size());
// if (attributes.size() > 0) {
// attributes.at(0)->toString();
// }
for (std::vector<AttributeWrapper*>::iterator it = attributes.begin();
it != attributes.end(); ++it) {
// printf("Attributes wrapper: ");
// (*it)->toString();
(*it)->readWrite();
}
source.readRowFooter();
dest.writeRowFooter();
}
source.readFileFooter();
dest.writeFileFooter();
}
|
#include "dynet/rnn.h"
#include "dynet/io-macros.h"
#include <string>
#include <cassert>
#include <vector>
#include <fstream>
#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/vector.hpp>
#include "dynet/nodes.h"
#include "dynet/expr.h"
using namespace std;
using namespace dynet::expr;
using namespace dynet;
namespace dynet {
enum { X2H=0, H2H, HB, L2H };
RNNBuilder::~RNNBuilder() {}
void RNNBuilder::save_parameters_pretraining(const string& fname) const {
cerr << "RNNBuilder::save_parameters_pretraining not overridden.\n";
abort();
}
void RNNBuilder::load_parameters_pretraining(const string& fname) {
cerr << "RNNBuilder::load_parameters_pretraining not overridden.\n";
abort();
}
template<class Archive>
void RNNBuilder::serialize(Archive& ar, const unsigned int) {
ar & cur;
ar & head;
ar & sm;
}
DYNET_SERIALIZE_IMPL(RNNBuilder)
SimpleRNNBuilder::SimpleRNNBuilder(unsigned layers,
unsigned input_dim,
unsigned hidden_dim,
Model* model,
bool support_lags) : layers(layers), lagging(support_lags) {
unsigned layer_input_dim = input_dim;
for (unsigned i = 0; i < layers; ++i) {
Parameter p_x2h = model->add_parameters({hidden_dim, layer_input_dim});
Parameter p_h2h = model->add_parameters({hidden_dim, hidden_dim});
Parameter p_hb = model->add_parameters({hidden_dim});
vector<Parameter> ps = {p_x2h, p_h2h, p_hb};
if (lagging)
ps.push_back(model->add_parameters({hidden_dim, hidden_dim}));
params.push_back(ps);
layer_input_dim = hidden_dim;
}
dropout_rate = 0.f;
}
void SimpleRNNBuilder::new_graph_impl(ComputationGraph& cg) {
param_vars.clear();
for (unsigned i = 0; i < layers; ++i) {
Parameter p_x2h = params[i][X2H];
Parameter p_h2h = params[i][H2H];
Parameter p_hb = params[i][HB];
Expression i_x2h = parameter(cg,p_x2h);
Expression i_h2h = parameter(cg,p_h2h);
Expression i_hb = parameter(cg,p_hb);
vector<Expression> vars = {i_x2h, i_h2h, i_hb};
if (lagging) {
Parameter p_l2h = params[i][L2H];
Expression i_l2h = parameter(cg,p_l2h);
vars.push_back(i_l2h);
}
param_vars.push_back(vars);
}
}
void SimpleRNNBuilder::start_new_sequence_impl(const vector<Expression>& h_0) {
h.clear();
h0 = h_0;
if (h0.size()) { assert(h0.size() == layers); }
}
Expression SimpleRNNBuilder::set_h_impl(int prev, const vector<Expression>& h_new) {
if (h_new.size()) { assert(h_new.size() == layers); }
const unsigned t = h.size();
h.push_back(vector<Expression>(layers));
for (unsigned i = 0; i < layers; ++i) {
Expression y = h_new[i];
h[t][i] = y;
}
return h[t].back();
}
Expression SimpleRNNBuilder::add_input_impl(int prev, const Expression &in) {
if(dropout_rate != 0.f)
throw std::runtime_error("SimpleRNNBuilder doesn't support dropout yet");
const unsigned t = h.size();
h.push_back(vector<Expression>(layers));
Expression x = in;
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
// y <--- f(x)
Expression y = affine_transform({vars[2], vars[0], x});
// y <--- g(y_prev)
if (prev == -1 && h0.size() > 0)
y = affine_transform({y, vars[1], h0[i]});
else if (prev >= 0)
y = affine_transform({y, vars[1], h[prev][i]});
// x <--- tanh(y)
x = h[t][i] = tanh(y);
}
return h[t].back();
}
Expression SimpleRNNBuilder::add_auxiliary_input(const Expression &in, const Expression &aux) {
const unsigned t = h.size();
h.push_back(vector<Expression>(layers));
Expression x = in;
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
assert(vars.size() >= L2H + 1);
Expression y = affine_transform({vars[HB], vars[X2H], x, vars[L2H], aux});
if (t == 0 && h0.size() > 0)
y = affine_transform({y, vars[H2H], h0[i]});
else if (t >= 1)
y = affine_transform({y, vars[H2H], h[t-1][i]});
x = h[t][i] = tanh(y);
}
return h[t].back();
}
void SimpleRNNBuilder::copy(const RNNBuilder & rnn) {
const SimpleRNNBuilder & rnn_simple = (const SimpleRNNBuilder&)rnn;
assert(params.size() == rnn_simple.params.size());
for(size_t i = 0; i < rnn_simple.params.size(); ++i) {
params[i][0] = rnn_simple.params[i][0];
params[i][1] = rnn_simple.params[i][1];
params[i][2] = rnn_simple.params[i][2];
}
}
void SimpleRNNBuilder::save_parameters_pretraining(const string& fname) const {
cerr << "Writing parameters to " << fname << endl;
ofstream of(fname);
assert(of);
boost::archive::binary_oarchive oa(of);
std::string id = "SimpleRNNBuilder:params";
oa << id;
oa << layers;
for (unsigned i = 0; i < layers; ++i) {
for (auto p : params[i]) {
oa << p.get()->values;
}
}
}
void SimpleRNNBuilder::load_parameters_pretraining(const string& fname) {
cerr << "Loading parameters from " << fname << endl;
ifstream of(fname);
assert(of);
boost::archive::binary_iarchive ia(of);
std::string id;
ia >> id;
if (id != "SimpleRNNBuilder:params") {
cerr << "Bad id read\n";
abort();
}
unsigned l = 0;
ia >> l;
if (l != layers) {
cerr << "Bad number of layers\n";
abort();
}
// TODO check other dimensions
for (unsigned i = 0; i < layers; ++i) {
for (auto p : params[i]) {
ia >> p.get()->values;
}
}
}
template<class Archive>
void SimpleRNNBuilder::serialize(Archive& ar, const unsigned int) {
ar & boost::serialization::base_object<RNNBuilder>(*this);
ar & params;
ar & layers;
ar & lagging;
}
DYNET_SERIALIZE_IMPL(SimpleRNNBuilder)
} // namespace dynet
BOOST_CLASS_EXPORT_IMPLEMENT(dynet::RNNBuilder)
BOOST_CLASS_EXPORT_IMPLEMENT(dynet::SimpleRNNBuilder)
|
#include "DwarfCompileUnit.h"
#include "DwarfExpression.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instruction.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
namespace llvm {
DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
AsmPrinter *A, DwarfDebug *DW,
DwarfFile *DWU)
: DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
Skeleton(nullptr), BaseAddress(nullptr) {
insertDIE(Node, &getUnitDie());
MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
}
/// addLabelAddress - Add a dwarf label attribute data and value using
/// DW_FORM_addr or DW_FORM_GNU_addr_index.
///
void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Label) {
// Don't use the address pool in non-fission or in the skeleton unit itself.
// FIXME: Once GDB supports this, it's probably worthwhile using the address
// pool from the skeleton - maybe even in non-fission (possibly fewer
// relocations by sharing them in the pool, but we have other ideas about how
// to reduce the number of relocations as well/instead).
if (!DD->useSplitDwarf() || !Skeleton)
return addLocalLabelAddress(Die, Attribute, Label);
if (Label)
DD->addArangeLabel(SymbolCU(this, Label));
unsigned idx = DD->getAddressPool().getIndex(Label);
Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
DIEInteger(idx));
}
void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
dwarf::Attribute Attribute,
const MCSymbol *Label) {
if (Label)
DD->addArangeLabel(SymbolCU(this, Label));
if (Label)
Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
DIELabel(Label));
else
Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
DIEInteger(0));
}
unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
StringRef DirName) {
// If we print assembly, we can't separate .file entries according to
// compile units. Thus all files will belong to the default compile unit.
// FIXME: add a better feature test than hasRawTextSupport. Even better,
// extend .file to support this.
return Asm->OutStreamer->EmitDwarfFileDirective(
0, DirName, FileName,
Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
}
// Return const expression if value is a GEP to access merged global
// constant. e.g.
// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
if (!CE || CE->getNumOperands() != 3 ||
CE->getOpcode() != Instruction::GetElementPtr)
return nullptr;
// First operand points to a global struct.
Value *Ptr = CE->getOperand(0);
GlobalValue *GV = dyn_cast<GlobalValue>(Ptr);
if (!GV || !isa<StructType>(GV->getValueType()))
return nullptr;
// Second operand is zero.
const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
if (!CI || !CI->isZero())
return nullptr;
// Third operand is offset.
if (!isa<ConstantInt>(CE->getOperand(2)))
return nullptr;
return CE;
}
/// getOrCreateGlobalVariableDIE - get or create global variable DIE.
DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
const DIGlobalVariable *GV) {
// Check for pre-existence.
if (DIE *Die = getDIE(GV))
return Die;
assert(GV);
auto *GVContext = GV->getScope();
auto *GTy = DD->resolve(GV->getType());
// Construct the context before querying for the existence of the DIE in
// case such construction creates the DIE.
DIE *ContextDIE = getOrCreateContextDIE(GVContext);
// Add to map.
DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
DIScope *DeclContext;
if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
DeclContext = resolve(SDMDecl->getScope());
assert(SDMDecl->isStaticMember() && "Expected static member decl");
assert(GV->isDefinition());
// We need the declaration DIE that is in the static member's class.
DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
} else {
DeclContext = GV->getScope();
// Add name and type.
addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
addType(*VariableDIE, GTy);
// Add scoping info.
if (!GV->isLocalToUnit())
addFlag(*VariableDIE, dwarf::DW_AT_external);
// Add line number info.
addSourceLine(*VariableDIE, GV);
}
if (!GV->isDefinition())
addFlag(*VariableDIE, dwarf::DW_AT_declaration);
else
addGlobalName(GV->getName(), *VariableDIE, DeclContext);
// Add location.
bool addToAccelTable = false;
if (auto *Global = dyn_cast_or_null<GlobalVariable>(GV->getVariable())) {
addToAccelTable = true;
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
const MCSymbol *Sym = Asm->getSymbol(Global);
if (Global->isThreadLocal()) {
if (Asm->TM.Options.EmulatedTLS) {
// TODO: add debug info for emulated thread local mode.
} else {
// FIXME: Make this work with -gsplit-dwarf.
unsigned PointerSize = Asm->getDataLayout().getPointerSize();
assert((PointerSize == 4 || PointerSize == 8) &&
"Add support for other sizes if necessary");
// Based on GCC's support for TLS:
if (!DD->useSplitDwarf()) {
// 1) Start with a constNu of the appropriate pointer size
addUInt(*Loc, dwarf::DW_FORM_data1, PointerSize == 4
? dwarf::DW_OP_const4u
: dwarf::DW_OP_const8u);
// 2) containing the (relocated) offset of the TLS variable
// within the module's TLS block.
addExpr(*Loc, dwarf::DW_FORM_udata,
Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
} else {
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
addUInt(*Loc, dwarf::DW_FORM_udata,
DD->getAddressPool().getIndex(Sym, /* TLS */ true));
}
// 3) followed by an OP to make the debugger do a TLS lookup.
addUInt(*Loc, dwarf::DW_FORM_data1,
DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
: dwarf::DW_OP_form_tls_address);
}
} else {
DD->addArangeLabel(SymbolCU(this, Sym));
addOpAddress(*Loc, Sym);
}
addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
if (DD->useAllLinkageNames())
addLinkageName(*VariableDIE, GV->getLinkageName());
} else if (const ConstantInt *CI =
dyn_cast_or_null<ConstantInt>(GV->getVariable())) {
addConstantValue(*VariableDIE, CI, GTy);
} else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) {
addToAccelTable = true;
// GV is a merged global.
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
auto *Ptr = cast<GlobalValue>(CE->getOperand(0));
MCSymbol *Sym = Asm->getSymbol(Ptr);
DD->addArangeLabel(SymbolCU(this, Sym));
addOpAddress(*Loc, Sym);
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
addUInt(*Loc, dwarf::DW_FORM_udata,
Asm->getDataLayout().getIndexedOffsetInType(Ptr->getValueType(), Idx));
addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
}
if (addToAccelTable) {
DD->addAccelName(GV->getName(), *VariableDIE);
// If the linkage name is different than the name, go ahead and output
// that as well into the name table.
if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
DD->addAccelName(GV->getLinkageName(), *VariableDIE);
}
return VariableDIE;
}
void DwarfCompileUnit::addRange(RangeSpan Range) {
bool SameAsPrevCU = this == DD->getPrevCU();
DD->setPrevCU(this);
// If we have no current ranges just add the range and return, otherwise,
// check the current section and CU against the previous section and CU we
// emitted into and the subprogram was contained within. If these are the
// same then extend our current range, otherwise add this as a new range.
if (CURanges.empty() || !SameAsPrevCU ||
(&CURanges.back().getEnd()->getSection() !=
&Range.getEnd()->getSection())) {
CURanges.push_back(Range);
return;
}
CURanges.back().setEnd(Range.getEnd());
}
DIE::value_iterator
DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Label, const MCSymbol *Sec) {
if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
return addLabel(Die, Attribute,
DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
: dwarf::DW_FORM_data4,
Label);
return addSectionDelta(Die, Attribute, Label, Sec);
}
void DwarfCompileUnit::initStmtList() {
// Define start line table label for each Compile Unit.
MCSymbol *LineTableStartSym =
Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
// DW_AT_stmt_list is a offset of line number information for this
// compile unit in debug_line section. For split dwarf this is
// left in the skeleton CU and so not included.
// The line table entries are not always emitted in assembly, so it
// is not okay to use line_table_start here.
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
StmtListValue =
addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
TLOF.getDwarfLineSection()->getBeginSymbol());
}
void DwarfCompileUnit::applyStmtList(DIE &D) {
D.addValue(DIEValueAllocator, *StmtListValue);
}
void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
const MCSymbol *End) {
assert(Begin && "Begin label should not be null!");
assert(End && "End label should not be null!");
assert(Begin->isDefined() && "Invalid starting label");
assert(End->isDefined() && "Invalid end label");
addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
if (DD->getDwarfVersion() < 4)
addLabelAddress(D, dwarf::DW_AT_high_pc, End);
else
addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
}
// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
// and DW_AT_high_pc attributes. If there are global variables in this
// scope then create and insert DIEs for these variables.
DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
*DD->getCurrentFunction()))
addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
// Only include DW_AT_frame_base in full debug info
if (!includeMinimalInlineScopes()) {
const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
MachineLocation Location(RI->getFrameRegister(*Asm->MF));
if (RI->isPhysicalRegister(Location.getReg()))
addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
}
// Add name to the name table, we do this here because we're guaranteed
// to have concrete versions of our DW_TAG_subprogram nodes.
DD->addSubprogramNames(SP, *SPDie);
return *SPDie;
}
// Construct a DIE for this scope.
void DwarfCompileUnit::constructScopeDIE(
LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
if (!Scope || !Scope->getScopeNode())
return;
auto *DS = Scope->getScopeNode();
assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
"Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined "
"subprograms");
SmallVector<DIE *, 8> Children;
// We try to create the scope DIE first, then the children DIEs. This will
// avoid creating un-used children then removing them later when we find out
// the scope DIE is null.
DIE *ScopeDIE;
if (Scope->getParent() && isa<DISubprogram>(DS)) {
ScopeDIE = constructInlinedScopeDIE(Scope);
if (!ScopeDIE)
return;
// We create children when the scope DIE is not null.
createScopeChildrenDIE(Scope, Children);
} else {
// Early exit when we know the scope DIE is going to be null.
if (DD->isLexicalScopeDIENull(Scope))
return;
unsigned ChildScopeCount;
// We create children here when we know the scope DIE is not going to be
// null and the children will be added to the scope DIE.
createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
// Skip imported directives in gmlt-like data.
if (!includeMinimalInlineScopes()) {
// There is no need to emit empty lexical block DIE.
for (const auto *IE : ImportedEntities[DS])
Children.push_back(
constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
}
// If there are only other scopes as children, put them directly in the
// parent instead, as this scope would serve no purpose.
if (Children.size() == ChildScopeCount) {
FinalChildren.insert(FinalChildren.end(),
std::make_move_iterator(Children.begin()),
std::make_move_iterator(Children.end()));
return;
}
ScopeDIE = constructLexicalScopeDIE(Scope);
assert(ScopeDIE && "Scope DIE should not be null.");
}
// Add children
for (auto &I : Children)
ScopeDIE->addChild(std::move(I));
FinalChildren.push_back(std::move(ScopeDIE));
}
DIE::value_iterator
DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Hi, const MCSymbol *Lo) {
return Die.addValue(DIEValueAllocator, Attribute,
DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
: dwarf::DW_FORM_data4,
new (DIEValueAllocator) DIEDelta(Hi, Lo));
}
void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
SmallVector<RangeSpan, 2> Range) {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
// Emit offset in .debug_range as a relocatable label. emitDIE will handle
// emitting it appropriately.
const MCSymbol *RangeSectionSym =
TLOF.getDwarfRangesSection()->getBeginSymbol();
RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
// Under fission, ranges are specified by constant offsets relative to the
// CU's DW_AT_GNU_ranges_base.
if (isDwoUnit())
addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
RangeSectionSym);
else
addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
RangeSectionSym);
// Add the range list to the set of ranges to be emitted.
(Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
}
void DwarfCompileUnit::attachRangesOrLowHighPC(
DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
if (Ranges.size() == 1) {
const auto &single = Ranges.front();
attachLowHighPC(Die, single.getStart(), single.getEnd());
} else
addScopeRangeList(Die, std::move(Ranges));
}
void DwarfCompileUnit::attachRangesOrLowHighPC(
DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
SmallVector<RangeSpan, 2> List;
List.reserve(Ranges.size());
for (const InsnRange &R : Ranges)
List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
DD->getLabelAfterInsn(R.second)));
attachRangesOrLowHighPC(Die, std::move(List));
}
// This scope represents inlined body of a function. Construct DIE to
// represent this concrete inlined copy of the function.
DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
assert(Scope->getScopeNode());
auto *DS = Scope->getScopeNode();
auto *InlinedSP = getDISubprogram(DS);
// Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
// was inlined from another compile unit.
DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
// Add the call site information to the DIE.
const DILocation *IA = Scope->getInlinedAt();
addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
if (IA->getDiscriminator())
addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
IA->getDiscriminator());
// Add name to the name table, we do this here because we're guaranteed
// to have concrete versions of our DW_TAG_inlined_subprogram nodes.
DD->addSubprogramNames(InlinedSP, *ScopeDIE);
return ScopeDIE;
}
// Construct new DW_TAG_lexical_block for this scope and attach
// DW_AT_low_pc/DW_AT_high_pc labels.
DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
if (DD->isLexicalScopeDIENull(Scope))
return nullptr;
auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
if (Scope->isAbstractScope())
return ScopeDIE;
attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
return ScopeDIE;
}
/// constructVariableDIE - Construct a DIE for the given DbgVariable.
DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
auto D = constructVariableDIEImpl(DV, Abstract);
DV.setDIE(*D);
return D;
}
DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
bool Abstract) {
// Define variable debug information entry.
auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
if (Abstract) {
applyVariableAttributes(DV, *VariableDie);
return VariableDie;
}
// Add variable address.
unsigned Offset = DV.getDebugLocListIndex();
if (Offset != ~0U) {
addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
return VariableDie;
}
// Check if variable is described by a DBG_VALUE instruction.
if (const MachineInstr *DVInsn = DV.getMInsn()) {
assert(DVInsn->getNumOperands() == 4);
if (DVInsn->getOperand(0).isReg()) {
const MachineOperand RegOp = DVInsn->getOperand(0);
// If the second operand is an immediate, this is an indirect value.
if (DVInsn->getOperand(1).isImm()) {
MachineLocation Location(RegOp.getReg(),
DVInsn->getOperand(1).getImm());
addVariableAddress(DV, *VariableDie, Location);
} else if (RegOp.getReg())
addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
} else if (DVInsn->getOperand(0).isImm()) {
// This variable is described by a single constant.
// Check whether it has a DIExpression.
auto *Expr = DV.getSingleExpression();
if (Expr && Expr->getNumElements()) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
// If there is an expression, emit raw unsigned bytes.
DwarfExpr.AddUnsignedConstant(DVInsn->getOperand(0).getImm());
DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
} else
addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
} else if (DVInsn->getOperand(0).isFPImm())
addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
else if (DVInsn->getOperand(0).isCImm())
addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
DV.getType());
return VariableDie;
}
// .. else use frame index.
if (DV.getFrameIndex().empty())
return VariableDie;
auto Expr = DV.getExpression().begin();
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
for (auto FI : DV.getFrameIndex()) {
unsigned FrameReg = 0;
const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
assert(Expr != DV.getExpression().end() && "Wrong number of expressions");
DwarfExpr.AddMachineRegIndirect(FrameReg, Offset);
DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end());
++Expr;
}
addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
return VariableDie;
}
DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
const LexicalScope &Scope,
DIE *&ObjectPointer) {
auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
if (DV.isObjectPointer())
ObjectPointer = Var;
return Var;
}
DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
SmallVectorImpl<DIE *> &Children,
unsigned *ChildScopeCount) {
DIE *ObjectPointer = nullptr;
for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
unsigned ChildCountWithoutScopes = Children.size();
for (LexicalScope *LS : Scope->getChildren())
constructScopeDIE(LS, Children);
if (ChildScopeCount)
*ChildScopeCount = Children.size() - ChildCountWithoutScopes;
return ObjectPointer;
}
void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
assert(Scope && Scope->getScopeNode());
assert(!Scope->getInlinedAt());
assert(!Scope->isAbstractScope());
auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
DD->getProcessedSPNodes().insert(Sub);
DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
// If this is a variadic function, add an unspecified parameter.
DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
// Collect lexical scope children first.
// ObjectPointer might be a local (non-argument) local variable if it's a
// block's synthetic this pointer.
if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
// If we have a single element of null, it is a function that returns void.
// If we have more than one elements and the last one is null, it is a
// variadic function.
if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
!includeMinimalInlineScopes())
ScopeDIE.addChild(
DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
}
DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
DIE &ScopeDIE) {
// We create children when the scope DIE is not null.
SmallVector<DIE *, 8> Children;
DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
// Add children
for (auto &I : Children)
ScopeDIE.addChild(std::move(I));
return ObjectPointer;
}
void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
LexicalScope *Scope) {
DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
if (AbsDef)
return;
auto *SP = cast<DISubprogram>(Scope->getScopeNode());
DIE *ContextDIE;
if (includeMinimalInlineScopes())
ContextDIE = &getUnitDie();
// Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
// the important distinction that the debug node is not associated with the
// DIE (since the debug node will be associated with the concrete DIE, if
// any). It could be refactored to some common utility function.
else if (auto *SPDecl = SP->getDeclaration()) {
ContextDIE = &getUnitDie();
getOrCreateSubprogramDIE(SPDecl);
} else
ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
// Passing null as the associated node because the abstract definition
// shouldn't be found by lookup.
AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
applySubprogramAttributesToDefinition(SP, *AbsDef);
if (!includeMinimalInlineScopes())
addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
}
DIE *DwarfCompileUnit::constructImportedEntityDIE(
const DIImportedEntity *Module) {
DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
insertDIE(Module, IMDie);
DIE *EntityDie;
auto *Entity = resolve(Module->getEntity());
if (auto *NS = dyn_cast<DINamespace>(Entity))
EntityDie = getOrCreateNameSpace(NS);
else if (auto *M = dyn_cast<DIModule>(Entity))
EntityDie = getOrCreateModule(M);
else if (auto *SP = dyn_cast<DISubprogram>(Entity))
EntityDie = getOrCreateSubprogramDIE(SP);
else if (auto *T = dyn_cast<DIType>(Entity))
EntityDie = getOrCreateTypeDIE(T);
else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
EntityDie = getOrCreateGlobalVariableDIE(GV);
else
EntityDie = getDIE(Entity);
assert(EntityDie);
addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
Module->getScope()->getDirectory());
addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
StringRef Name = Module->getName();
if (!Name.empty())
addString(*IMDie, dwarf::DW_AT_name, Name);
return IMDie;
}
void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
DIE *D = getDIE(SP);
if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
if (D)
// If this subprogram has an abstract definition, reference that
addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
} else {
if (!D && !includeMinimalInlineScopes())
// Lazily construct the subprogram if we didn't see either concrete or
// inlined versions during codegen. (except in -gmlt ^ where we want
// to omit these entirely)
D = getOrCreateSubprogramDIE(SP);
if (D)
// And attach the attributes
applySubprogramAttributesToDefinition(SP, *D);
}
}
void DwarfCompileUnit::emitHeader(bool UseOffsets) {
// Don't bother labeling the .dwo unit, as its offset isn't used.
if (!Skeleton) {
LabelBegin = Asm->createTempSymbol("cu_begin");
Asm->OutStreamer->EmitLabel(LabelBegin);
}
DwarfUnit::emitHeader(UseOffsets);
}
/// addGlobalName - Add a new global name to the compile unit.
void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
const DIScope *Context) {
if (includeMinimalInlineScopes())
return;
std::string FullName = getParentContextString(Context) + Name.str();
GlobalNames[FullName] = &Die;
}
/// Add a new global type to the unit.
void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
const DIScope *Context) {
if (includeMinimalInlineScopes())
return;
std::string FullName = getParentContextString(Context) + Ty->getName().str();
GlobalTypes[FullName] = &Die;
}
/// addVariableAddress - Add DW_AT_location attribute for a
/// DbgVariable based on provided MachineLocation.
void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
MachineLocation Location) {
if (DV.hasComplexAddress())
addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
else if (DV.isBlockByrefVariable())
addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
else
addAddress(Die, dwarf::DW_AT_location, Location);
}
/// Add an address attribute to a die based on the location provided.
void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
const MachineLocation &Location) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
bool validReg;
if (Location.isReg())
validReg = addRegisterOpPiece(*Loc, Location.getReg());
else
validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
if (!validReg)
return;
// Now attach the location information to the DIE.
addBlock(Die, Attribute, Loc);
}
/// Start with the address based on the location provided, and generate the
/// DWARF information necessary to find the actual variable given the extra
/// address information encoded in the DbgVariable, starting from the starting
/// location. Add the DWARF information to the die.
void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
dwarf::Attribute Attribute,
const MachineLocation &Location) {
DIELoc *Loc = new (DIEValueAllocator) DIELoc;
DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
const DIExpression *Expr = DV.getSingleExpression();
bool ValidReg;
if (Location.getOffset()) {
ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
Location.getOffset());
if (ValidReg)
DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
} else
ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
// Now attach the location information to the DIE.
if (ValidReg)
addBlock(Die, Attribute, Loc);
}
/// Add a Dwarf loclistptr attribute data and value.
void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
unsigned Index) {
dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
: dwarf::DW_FORM_data4;
Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
}
void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
DIE &VariableDie) {
StringRef Name = Var.getName();
if (!Name.empty())
addString(VariableDie, dwarf::DW_AT_name, Name);
addSourceLine(VariableDie, Var.getVariable());
addType(VariableDie, Var.getType());
if (Var.isArtificial())
addFlag(VariableDie, dwarf::DW_AT_artificial);
}
/// Add a Dwarf expression attribute data and value.
void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
const MCExpr *Expr) {
Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
}
void DwarfCompileUnit::applySubprogramAttributesToDefinition(
const DISubprogram *SP, DIE &SPDie) {
auto *SPDecl = SP->getDeclaration();
auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
addGlobalName(SP->getName(), SPDie, Context);
}
bool DwarfCompileUnit::isDwoUnit() const {
return DD->useSplitDwarf() && Skeleton;
}
bool DwarfCompileUnit::includeMinimalInlineScopes() const {
return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
(DD->useSplitDwarf() && !Skeleton);
}
} // end llvm namespace
|
/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include <drivers/device/integrator.h>
#include <drivers/drv_accel.h>
#include <drivers/drv_hrt.h>
#include <lib/cdev/CDev.hpp>
#include <lib/conversion/rotation.h>
#include <mathlib/math/filter/LowPassFilter2pVector3f.hpp>
#include <px4_module_params.h>
#include <uORB/uORB.h>
#include <uORB/Publication.hpp>
#include <uORB/topics/sensor_accel.h>
class PX4Accelerometer : public cdev::CDev, public ModuleParams
{
public:
PX4Accelerometer(uint32_t device_id, uint8_t priority, enum Rotation rotation);
~PX4Accelerometer() override;
int ioctl(cdev::file_t *filp, int cmd, unsigned long arg) override;
void set_device_type(uint8_t devtype);
void set_error_count(uint64_t error_count) { _sensor_accel_pub.get().error_count = error_count; }
void set_scale(float scale) { _sensor_accel_pub.get().scaling = scale; }
void set_temperature(float temperature) { _sensor_accel_pub.get().temperature = temperature; }
void set_sample_rate(unsigned rate) { _sample_rate = rate; _filter.set_cutoff_frequency(_sample_rate, _filter.get_cutoff_freq()); }
void configure_filter(float cutoff_freq) { _filter.set_cutoff_frequency(_sample_rate, cutoff_freq); }
void update(hrt_abstime timestamp, int16_t x, int16_t y, int16_t z);
void print_status();
private:
uORB::Publication<sensor_accel_s> _sensor_accel_pub;
math::LowPassFilter2pVector3f _filter{1000, 100};
Integrator _integrator{4000, false};
const enum Rotation _rotation;
matrix::Vector3f _calibration_scale{1.0f, 1.0f, 1.0f};
matrix::Vector3f _calibration_offset{0.0f, 0.0f, 0.0f};
int _class_device_instance{-1};
unsigned _sample_rate{1000};
DEFINE_PARAMETERS(
(ParamFloat<px4::params::IMU_ACCEL_CUTOFF>) _param_imu_accel_cutoff
)
};
|
/* Copyright 2018 The MathWorks, Inc. */
#include "solve_from_qr.h"
#include <float.h>
int qr_rank_ci(cs_cin* N, double* tol) {
int col, rowOffset, nnzThisCol, row, minSize, maxSize, rank;
double eps, scale;
cs_ci* mat = N->U; /* R, from QR */
int* p = mat->p;
if (mat->m < mat->n) {
minSize = mat->m;
maxSize = mat->n;
} else {
minSize = mat->n;
maxSize = mat->m;
}
if (minSize == 0 || mat->nzmax == 0) {
*tol = 0;
return 0;
}
eps = DBL_EPSILON;
scale = fmin(10 * maxSize * eps, sqrt(eps));
*tol = scale * CS_ABS(mat->x[0]);
rank = 0;
for (col = 0; col < minSize; col++) {
nnzThisCol = p[col + 1] - p[col];
if (col == 0 && nnzThisCol == 0) {
*tol = 0;
return 0;
}
for (rowOffset = 0; rowOffset < nnzThisCol; rowOffset++) {
row = mat->i[p[col] + rowOffset];
if (row == col) {
if (CS_ABS(mat->x[p[col] + rowOffset]) > *tol) {
rank = rank + 1;
break;
} else {
break;
}
} else if (row > col) {
break;
}
}
}
return rank;
}
int qr_rank_di(cs_din* N, double* tol) {
int col, rowOffset, nnzThisCol, row, minSize, maxSize, rank;
double eps, scale;
cs_di* mat = N->U; /* R, from QR */
int* p = mat->p;
if (mat->m < mat->n) {
minSize = mat->m;
maxSize = mat->n;
} else {
minSize = mat->n;
maxSize = mat->m;
}
if (minSize == 0 || mat->nzmax == 0) {
*tol = 0;
return 0;
}
eps = DBL_EPSILON;
scale = fmin(10 * maxSize * eps, sqrt(eps));
*tol = scale * fabs(mat->x[0]);
rank = 0;
for (col = 0; col < minSize; col++) {
nnzThisCol = p[col + 1] - p[col];
if (col == 0 && nnzThisCol == 0) {
*tol = 0;
return 0;
}
for (rowOffset = 0; rowOffset < nnzThisCol; rowOffset++) {
row = mat->i[p[col] + rowOffset];
if (row == col) {
if (fabs(mat->x[p[col] + rowOffset]) > *tol) {
rank = rank + 1;
break;
} else {
return rank;
}
} else if (row > col) {
return rank;
}
}
}
return rank;
}
void solve_from_qr_di(cs_din* N, cs_dis* S, double* b, int m, int n) {
double* x = (double*)cs_di_calloc(S ? S->m2 : 1, sizeof(double)); /* get workspace */
if (m >= n) {
cs_di_ipvec(S->pinv, b, x, m); /* x(0:m-1) = b(p(0:m-1) */
CS_INT k;
for (k = 0; k < n; k++) /* apply Householder refl. to x */
{
cs_di_happly(N->L, k, N->B[k], x);
}
cs_di_usolve(N->U, x); /* x = R\x */
cs_di_ipvec(S->q, x, b, n); /* b(q(0:n-1)) = x(0:n-1) */
} else {
cs_di_pvec(S->q, b, x, m); /* x(q(0:m-1)) = b(0:m-1) */
cs_di_utsolve(N->U, x); /* x = R'\x */
CS_INT k;
for (k = m - 1; k >= 0; k--) /* apply Householder refl. to x */
{
cs_di_happly(N->L, k, N->B[k], x);
}
cs_di_pvec(S->pinv, x, b, n); /* b(0:n-1) = x(p(0:n-1)) */
}
cs_di_free(x);
}
void solve_from_qr_ci(cs_cin* N, cs_cis* S, cs_complex_t* b, int m, int n) {
cs_complex_t* x =
(cs_complex_t*)cs_ci_calloc(S ? S->m2 : 1, sizeof(cs_complex_t)); /* get workspace */
if (m >= n) {
cs_ci_ipvec(S->pinv, b, x, m); /* x(0:m-1) = b(p(0:m-1) */
CS_INT k;
for (k = 0; k < n; k++) /* apply Householder refl. to x */
{
cs_ci_happly(N->L, k, N->B[k], x);
}
cs_ci_usolve(N->U, x); /* x = R\x */
cs_ci_ipvec(S->q, x, b, n); /* b(q(0:n-1)) = x(0:n-1) */
} else {
cs_ci_pvec(S->q, b, x, m); /* x(q(0:m-1)) = b(0:m-1) */
cs_ci_utsolve(N->U, x); /* x = R'\x */
CS_INT k;
for (k = m - 1; k >= 0; k--) /* apply Householder refl. to x */
{
cs_ci_happly(N->L, k, N->B[k], x);
}
cs_ci_pvec(S->pinv, x, b, n); /* b(0:n-1) = x(p(0:n-1)) */
}
cs_ci_free(x);
}
|
#include "stdafx.h"
#include "libs.h"
#include "editor.h"
#include "blitzide.h"
static map<string,string> keyhelps;
std::vector<Runtime> runtimes;
int linker_ver,runtime_ver;
static string execProc( const string &proc ){
HANDLE rd,wr;
SECURITY_ATTRIBUTES sa={sizeof(sa),0,true};
if( CreatePipe( &rd,&wr,&sa,0 ) ){
STARTUPINFO si={sizeof(si)};
si.dwFlags=STARTF_USESTDHANDLES;
si.hStdOutput=si.hStdError=wr;
PROCESS_INFORMATION pi={0};
if( CreateProcess( 0,(char*)proc.c_str(),0,0,true,DETACHED_PROCESS,0,0,&si,&pi ) ){
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
CloseHandle( wr );
string t;
char *buf=new char[1024];
for(;;){
unsigned long sz;
int n=ReadFile( rd,buf,1024,&sz,0 );
if( !n && GetLastError()==ERROR_BROKEN_PIPE ) break;
if( !n ){ t="";break; }
if( !sz ) break;
t+=string( buf,sz );
}
delete[] buf;
CloseHandle(rd);
return t;
}
CloseHandle( rd );
CloseHandle( wr );
}
AfxMessageBox( (proc+" failed").c_str() );
ExitProcess(0);
return "";
}
int version( string vers,string t ){
t+=" version:";
int n=vers.find( t );n+=t.size();
int maj=atoi( vers.substr(n) );n=vers.find( '.',n )+1;
int min=atoi( vers.substr(n) );
return maj*100+min;
}
void initLibs(){
string valid=execProc( prefs.homeDir+"/bin/blitzcc.exe -q" );
if( valid.size() ){
AfxMessageBox( ("Compiler environment error: "+valid).c_str() );
ExitProcess(0);
}
string vers=tolower( execProc( prefs.homeDir+"/bin/blitzcc.exe -v" ) );
linker_ver=version( vers,"linker" );
runtime_ver=version( vers,"runtime" );
//generate keywords!
string kws=execProc( prefs.homeDir+"/bin/blitzcc.exe +k" );
if( !kws.size() ){
AfxMessageBox( "Error generating keywords" );
ExitProcess(0);
}
int pos=0,n;
while( (n=kws.find( '\n',pos ))!=string::npos ){
string t=kws.substr( pos,n-pos-1 );
for( int q=0;(q=t.find('\r',q))!=string::npos; ) t=t.replace( q,1,"" );
string help=t;
int i=t.find(' ');
if( i!=string::npos ){
t=t.substr(0,i);if( !t.size() ){
AfxMessageBox( "Error in keywords" );
ExitProcess(0);
}
if( !isalnum(t[t.size()-1]) ) t=t.substr(0,t.size()-1);
}
Editor::addKeyword(t);
keyhelps[t]=help;
pos=n+1;
}
string rts=execProc( prefs.homeDir+"/bin/blitzcc.exe -q -l" );
pos=0;
while( (n=rts.find( '\n',pos ))!=string::npos ){
string t=rts.substr( pos,n-pos-1 );
for( int q=0;(q=t.find('\r',q))!=string::npos; ) t=t.replace( q,1,"" );
Runtime rt;
rt.id=rt.name=t;
runtimes.push_back(rt);
pos=n+1;
}
}
string quickHelp( const string &kw ){
map<string,string>::const_iterator it=keyhelps.find(kw);
return it==keyhelps.end() ? "" : it->second;
}
bool isMediaFile( const string &f ){
#ifndef PRO
return false;
#endif
static char *exts[]={
"bmp","jpg","png","tga","iff","pcx",
"wav","mid","mp3","mod","s3m","xm","it","rmi","sgt",
"x","3ds",0
};
int i=f.rfind( '.' );
if( i==string::npos || i+1==f.size() ) return false;
string ext=f.substr( i+1 );
char **p=exts;
while( const char *e=*p++ ){
string t(e);
if( i+t.size()+1!=f.size() ) continue;
if( ext==t ) return true;
}
return false;
}
|
// Copyright (c) 2012-2018 The Bitcoin Core developers
// Copyright (c) 2017 The Raven Core developers
// Copyright (c) 2018 The Rito Core developers
// Copyright (c) 2020 The KringleProjectCoin 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/kringleprojectcoin-config.h"
#endif
#include "rpcconsole.h"
#include "ui_debugwindow.h"
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "chainparams.h"
#include "netbase.h"
#include "rpc/server.h"
#include "rpc/client.h"
#include "util.h"
#include <openssl/crypto.h>
#include <univalue.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#include <wallet/wallet.h>
#endif
#include <QDesktopWidget>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QScrollBar>
#include <QSettings>
#include <QSignalMapper>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QStringList>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
const QSize FONT_RANGE(4, 40);
const char fontSizeSettingsKey[] = "consoleFontSize";
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{nullptr, nullptr}
};
namespace {
// don't add private key handling cmd's to the history
const QStringList historyFilter = QStringList()
<< "importprivkey"
<< "importmulti"
<< "signmessagewithprivkey"
<< "signrawtransaction"
<< "walletpassphrase"
<< "walletpassphrasechange"
<< "encryptwallet";
}
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public Q_SLOTS:
void request(const QString &command);
Q_SIGNALS:
void reply(int category, const QString &command);
};
/** Class for handling RPC timers
* (used for e.g. re-locking the wallet after a timeout)
*/
class QtRPCTimerBase: public QObject, public RPCTimerBase
{
Q_OBJECT
public:
QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
func(_func)
{
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
timer.start(millis);
}
~QtRPCTimerBase() {}
private Q_SLOTS:
void timeout() { func(); }
private:
QTimer timer;
std::function<void(void)> func;
};
class QtRPCTimerInterface: public RPCTimerInterface
{
public:
~QtRPCTimerInterface() {}
const char *Name() { return "Qt"; }
RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis)
{
return new QtRPCTimerBase(func, millis);
}
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments and optionally execute the command(s).
* Aims to emulate \c bash and friends.
*
* - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress())
* - Arguments are delimited with whitespace or comma
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] result stringified Result from the executed command(chain)
* @param[in] strCommand Command line to split
* @param[in] fExecute set true if you want the command to be executed
* @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
*/
bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
{
std::vector< std::vector<std::string> > stack;
stack.push_back(std::vector<std::string>());
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_EATING_SPACES_IN_ARG,
STATE_EATING_SPACES_IN_BRACKETS,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED,
STATE_COMMAND_EXECUTED,
STATE_COMMAND_EXECUTED_INNER
} state = STATE_EATING_SPACES;
std::string curarg;
UniValue lastResult;
unsigned nDepthInsideSensitive = 0;
size_t filter_begin_pos = 0, chpos;
std::vector<std::pair<size_t, size_t>> filter_ranges;
auto add_to_current_stack = [&](const std::string& strArg) {
if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
nDepthInsideSensitive = 1;
filter_begin_pos = chpos;
}
// Make sure stack is not empty before adding something
if (stack.empty()) {
stack.push_back(std::vector<std::string>());
}
stack.back().push_back(strArg);
};
auto close_out_params = [&]() {
if (nDepthInsideSensitive) {
if (!--nDepthInsideSensitive) {
assert(filter_begin_pos);
filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
filter_begin_pos = 0;
}
}
stack.pop_back();
};
std::string strCommandTerminated = strCommand;
if (strCommandTerminated.back() != '\n')
strCommandTerminated += "\n";
for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
{
char ch = strCommandTerminated[chpos];
switch(state)
{
case STATE_COMMAND_EXECUTED_INNER:
case STATE_COMMAND_EXECUTED:
{
bool breakParsing = true;
switch(ch)
{
case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
default:
if (state == STATE_COMMAND_EXECUTED_INNER)
{
if (ch != ']')
{
// append char to the current argument (which is also used for the query command)
curarg += ch;
break;
}
if (curarg.size() && fExecute)
{
// if we have a value query, query arrays with index and objects with a string key
UniValue subelement;
if (lastResult.isArray())
{
for(char argch: curarg)
if (!std::isdigit(argch))
throw std::runtime_error("Invalid result query");
subelement = lastResult[atoi(curarg.c_str())];
}
else if (lastResult.isObject())
subelement = find_value(lastResult, curarg);
else
throw std::runtime_error("Invalid result query"); //no array or object: abort
lastResult = subelement;
}
state = STATE_COMMAND_EXECUTED;
break;
}
// don't break parsing when the char is required for the next argument
breakParsing = false;
// pop the stack and return the result to the current command arguments
close_out_params();
// don't stringify the json in case of a string to avoid doublequotes
if (lastResult.isStr())
curarg = lastResult.get_str();
else
curarg = lastResult.write(2);
// if we have a non empty result, use it as stack argument otherwise as general result
if (curarg.size())
{
if (stack.size())
add_to_current_stack(curarg);
else
strResult = curarg;
}
curarg.clear();
// assume eating space state
state = STATE_EATING_SPACES;
}
if (breakParsing)
break;
}
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES_IN_ARG:
case STATE_EATING_SPACES_IN_BRACKETS:
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case '(': case ')': case '\n':
if (state == STATE_EATING_SPACES_IN_ARG)
throw std::runtime_error("Invalid Syntax");
if (state == STATE_ARGUMENT)
{
if (ch == '(' && stack.size() && stack.back().size() > 0)
{
if (nDepthInsideSensitive) {
++nDepthInsideSensitive;
}
stack.push_back(std::vector<std::string>());
}
// don't allow commands after executed commands on baselevel
if (!stack.size())
throw std::runtime_error("Invalid Syntax");
add_to_current_stack(curarg);
curarg.clear();
state = STATE_EATING_SPACES_IN_BRACKETS;
}
if ((ch == ')' || ch == '\n') && stack.size() > 0)
{
if (fExecute) {
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
JSONRPCRequest req;
req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
req.strMethod = stack.back()[0];
#ifdef ENABLE_WALLET
// TODO: Move this logic to WalletModel
if (!vpwallets.empty()) {
// in Qt, use always the wallet with index 0 when running with multiple wallets
QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName()));
req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
}
#endif
lastResult = tableRPC.execute(req);
}
state = STATE_COMMAND_EXECUTED;
curarg.clear();
}
break;
case ' ': case ',': case '\t':
if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
throw std::runtime_error("Invalid Syntax");
else if(state == STATE_ARGUMENT) // Space ends argument
{
add_to_current_stack(curarg);
curarg.clear();
}
if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
{
state = STATE_EATING_SPACES_IN_ARG;
break;
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
if (pstrFilteredOut) {
if (STATE_COMMAND_EXECUTED == state) {
assert(!stack.empty());
close_out_params();
}
*pstrFilteredOut = strCommand;
for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
}
}
switch(state) // final state
{
case STATE_COMMAND_EXECUTED:
if (lastResult.isStr())
strResult = lastResult.get_str();
else
strResult = lastResult.write(2);
case STATE_ARGUMENT:
case STATE_EATING_SPACES:
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
try
{
std::string result;
std::string executableCommand = command.toStdString() + "\n";
if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
}
catch (UniValue& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
}
}
catch (const std::exception& e)
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
platformStyle(_platformStyle),
peersTableContextMenu(0),
banTableContextMenu(0),
consoleFontSize(0)
{
ui->setupUi(this);
QSettings settings;
if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
// Restore failed (perhaps missing setting), center the window
move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
}
ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
if (platformStyle->getImagesOnButtons()) {
ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// set library version labels
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
// Register RPC timer interface
rpcTimerInterface = new QtRPCTimerInterface();
// avoid accidentally overwriting an existing, non QTThread
// based timer interface
RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
clear();
}
RPCConsole::~RPCConsole()
{
QSettings settings;
settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
RPCUnsetTimerInterface(rpcTimerInterface);
delete rpcTimerInterface;
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
case Qt::Key_Return:
case Qt::Key_Enter:
// forward these events to lineEdit
if(obj == autoCompleter->popup()) {
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QWidget::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
updateNetworkState();
connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
// create peer table context menu actions
QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
// create peer table context menu
peersTableContextMenu = new QMenu(this);
peersTableContextMenu->addAction(disconnectAction);
peersTableContextMenu->addAction(banAction1h);
peersTableContextMenu->addAction(banAction24h);
peersTableContextMenu->addAction(banAction7d);
peersTableContextMenu->addAction(banAction365d);
// Add a signal mapping to allow dynamic context menu arguments.
// We need to use int (instead of int64_t), because signal mapper only supports
// int or objects, which is okay because max bantime (1 year) is < int_max.
QSignalMapper* signalMapper = new QSignalMapper(this);
signalMapper->setMapping(banAction1h, 60*60);
signalMapper->setMapping(banAction24h, 60*60*24);
signalMapper->setMapping(banAction7d, 60*60*24*7);
signalMapper->setMapping(banAction365d, 60*60*24*365);
connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
// peer table context menu signals
connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
// peer table signal handling - update peer details when selecting new node
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
// peer table signal handling - update peer details when new nodes are added to the model
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// peer table signal handling - cache selected node ids
connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
// set up ban table
ui->banlistWidget->setModel(model->getBanTableModel());
ui->banlistWidget->verticalHeader()->hide();
ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
// create ban table context menu action
QAction* unbanAction = new QAction(tr("&Unban"), this);
// create ban table context menu
banTableContextMenu = new QMenu(this);
banTableContextMenu->addAction(unbanAction);
// ban table context menu signals
connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
// ban table signal handling - clear peer details when clicking a peer in the ban table
connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
// ban table signal handling - ensure ban table is shown or hidden (if empty)
connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
showOrHideBanTableIfRequired();
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientUserAgent->setText(model->formatSubVersion());
ui->dataDir->setText(model->dataDir());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
//Setup autocomplete and attach it
QStringList wordList;
std::vector<std::string> commandList = tableRPC.listCommands();
for (size_t i = 0; i < commandList.size(); ++i)
{
wordList << commandList[i].c_str();
wordList << ("help " + commandList[i]).c_str();
}
wordList.sort();
autoCompleter = new QCompleter(wordList, this);
autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
ui->lineEdit->setCompleter(autoCompleter);
autoCompleter->popup()->installEventFilter(this);
// Start thread to execute RPC commands.
startExecutor();
}
if (!model) {
// Client model is being set to 0, this means shutdown() is about to be called.
// Make sure we clean up the executor thread
Q_EMIT stopExecutor();
thread.wait();
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::fontBigger()
{
setFontSize(consoleFontSize+1);
}
void RPCConsole::fontSmaller()
{
setFontSize(consoleFontSize-1);
}
void RPCConsole::setFontSize(int newSize)
{
QSettings settings;
//don't allow an insane font size
if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
return;
// temp. store the console content
QString str = ui->messagesWidget->toHtml();
// replace font tags size in current content
str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
// store the new font size
consoleFontSize = newSize;
settings.setValue(fontSizeSettingsKey, consoleFontSize);
// clear console (reset icon sizes, default stylesheet) and re-add the content
float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
clear(false);
ui->messagesWidget->setHtml(str);
ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
}
void RPCConsole::clear(bool clearHistory)
{
ui->messagesWidget->clear();
if(clearHistory)
{
history.clear();
historyPtr = 0;
}
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
ui->messagesWidget->document()->setDefaultStyleSheet(
QString(
"table { }"
"td.time { color: #808080; font-size: %2; padding-top: 3px; } "
"td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
".secwarning { color: red; }"
"b { color: #006060; } "
).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
);
#ifdef Q_OS_MAC
QString clsKey = "(⌘)-L";
#else
QString clsKey = "Ctrl-L";
#endif
message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")) +
"<br><span class=\"secwarning\">" +
tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
"</span>",
true);
}
void RPCConsole::keyPressEvent(QKeyEvent *event)
{
if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
{
close();
}
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, false);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::updateNetworkState()
{
QString connections = QString::number(clientModel->getNumConnections()) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
if(!clientModel->getNetworkActive()) {
connections += " (" + tr("Network activity disabled") + ")";
}
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
updateNetworkState();
}
void RPCConsole::setNetworkActive(bool networkActive)
{
updateNetworkState();
}
void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
{
if (!headers) {
ui->numberOfBlocks->setText(QString::number(count));
ui->lastBlockTime->setText(blockDate.toString());
}
}
void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
{
ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
if (dynUsage < 1000000)
ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
else
ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
if(!cmd.isEmpty())
{
std::string strFilteredCmd;
try {
std::string dummy;
if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
// Failed to parse command, so we cannot even filter it for the history
throw std::runtime_error("Invalid command line");
}
} catch (const std::exception& e) {
QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
return;
}
ui->lineEdit->clear();
cmdBeforeBrowsing = QString();
message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
Q_EMIT cmdRequest(cmd);
cmd = QString::fromStdString(strFilteredCmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
// store current text when start browsing through the history
if (historyPtr == history.size()) {
cmdBeforeBrowsing = ui->lineEdit->text();
}
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
else if (!cmdBeforeBrowsing.isNull()) {
cmd = cmdBeforeBrowsing;
}
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(&thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
// - queue executor for deletion (in execution thread)
connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread.start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console)
ui->lineEdit->setFocus();
else if (ui->tabWidget->widget(index) != ui->tab_peers)
clearSelectedNode();
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn));
ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut));
}
void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
return;
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutAboutToChange()
{
QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
cachedNodeids.clear();
for(int i = 0; i < selected.size(); i++)
{
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
cachedNodeids.append(stats->nodeStats.nodeid);
}
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel || !clientModel->getPeerTableModel())
return;
const CNodeCombinedStats *stats = nullptr;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeids.empty()) // no node selected yet
return;
// find the currently selected row
int selectedRow = -1;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (!selectedModelIndex.isEmpty()) {
selectedRow = selectedModelIndex.first().row();
}
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
if (detailNodeRow < 0)
{
// detail node disappeared from table (node disconnected)
fUnselect = true;
}
else
{
if (detailNodeRow != selectedRow)
{
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
clearSelectedNode();
}
if (fReselect)
{
for(int i = 0; i < cachedNodeids.size(); i++)
{
ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
}
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
{
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
// Common height is init to -1
if (stats->nodeStateStats.nCommonHeight > -1)
ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
else
ui->peerCommonHeight->setText(tr("Unknown"));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent *event)
{
QWidget::hideEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
void RPCConsole::showPeersTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->peerWidget->indexAt(point);
if (index.isValid())
peersTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::showBanTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->banlistWidget->indexAt(point);
if (index.isValid())
banTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::disconnectSelectedNode()
{
if(!g_connman)
return;
// Get selected peer addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected peer address
NodeId id = nodes.at(i).data().toLongLong();
// Find the node, disconnect it and clear the selected node
if(g_connman->DisconnectNode(id))
clearSelectedNode();
}
}
void RPCConsole::banSelectedNode(int bantime)
{
if (!clientModel || !g_connman)
return;
// Get selected peer addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected peer address
NodeId id = nodes.at(i).data().toLongLong();
// Get currently selected peer address
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
if(detailNodeRow < 0)
return;
// Find possible nodes, ban it and clear the selected node
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
if(stats) {
g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
}
}
clearSelectedNode();
clientModel->getBanTableModel()->refresh();
}
void RPCConsole::unbanSelectedNode()
{
if (!clientModel)
return;
// Get selected ban addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
for(int i = 0; i < nodes.count(); i++)
{
// Get currently selected ban address
QString strNode = nodes.at(i).data().toString();
CSubNet possibleSubnet;
LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
if (possibleSubnet.IsValid() && g_connman)
{
g_connman->Unban(possibleSubnet);
clientModel->getBanTableModel()->refresh();
}
}
}
void RPCConsole::clearSelectedNode()
{
ui->peerWidget->selectionModel()->clearSelection();
cachedNodeids.clear();
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}
void RPCConsole::showOrHideBanTableIfRequired()
{
if (!clientModel)
return;
bool visible = clientModel->getBanTableModel()->shouldShow();
ui->banlistWidget->setVisible(visible);
ui->banHeading->setVisible(visible);
}
void RPCConsole::setTabFocus(enum TabTypes tabType)
{
ui->tabWidget->setCurrentIndex(tabType);
}
|
#include <bits/stdc++.h>
using namespace std;
int a,b;
int main(){
cin >> a;
for ( int i = 0 ; i < a ; i++){
int x; cin >> x;
long long ans = x*(x+1LL)/2LL;
ans -= 2*((pow(2,int(log2(x))+1LL))-1LL);
cout << ans << endl;
}
}
|
#include "javascript_interface.h"
#include <iostream>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::vector;
void JavascriptInterface::Init(const char *execution_path) {}
void JavascriptInterface::Execute(
const vector<unique_ptr<Instruction>> &instructions) {
for (const auto &instr : instructions) {
cout << instr->Emit() << endl;
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_ncat_64b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-64b.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sinks: ncat
* BadSink : Copy data to string using wcsncat
* Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_ncat_64
{
#ifndef OMITBAD
void badSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr;
/* dereference dataPtr into data */
wchar_t * data = (*dataPtr);
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/
wcsncat(dest, data, wcslen(data));
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr;
/* dereference dataPtr into data */
wchar_t * data = (*dataPtr);
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/
wcsncat(dest, data, wcslen(data));
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
|
#include "stacktype.h"
#include <iostream>
using namespace std;
template <class ItemType>
StackType<ItemType>::StackType()
{
top=-1;
}
template <class ItemType>
bool StackType<ItemType>::IsEmpty()
{
return(top==-1);
}
template <class ItemType>
bool StackType<ItemType>::IsFull()
{
return (top==MAX_ITEMS-1);
}
template <class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
{
try
{
if(IsFull())
throw FullStack();
top++;
items[top]=newItem;
}
catch(FullStack f)
{
cout<<"Stack is Full";
}
}
template <class ItemType>
void StackType<ItemType>::Pop()
{
try
{
if(IsEmpty())
throw EmptyStack();
top--;
}
catch(EmptyStack e)
{
cout<<"Stack is Empty";
}
}
template <class ItemType>
ItemType StackType<ItemType>::Top()
{
return items[top];
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "db.h"
#include "init.h"
#include "kernel.h"
#include "net.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
using namespace std;
using namespace boost;
#if defined(NDEBUG)
# error "Blipcoin cannot be compiled without assertions."
#endif
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
CBigNum bnProofOfStakeLimit(~uint256(0) >> 20);
CBigNum bnProofOfStakeLimitV2(~uint256(0) >> 48);
int nStakeMinConfirmations = 60;
unsigned int nStakeMinAge = 1 * 60 * 60; // 1 hours
unsigned int nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
int nCoinbaseMaturity = 22;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainTrust = 0;
uint256 nBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64_t nTimeBestReceived = 0;
bool fImporting = false;
bool fReindex = false;
bool fHaveGUI = false;
struct COrphanBlock {
uint256 hashBlock;
uint256 hashPrev;
std::pair<COutPoint, unsigned int> stake;
vector<unsigned char> vchBlock;
};
map<uint256, COrphanBlock*> mapOrphanBlocks;
multimap<uint256, COrphanBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
size_t nOrphanBlocksSize = 0;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Blipcoin Signed Message:\n";
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
namespace {
struct CMainSignals {
// Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found in.
boost::signals2::signal<void (const CTransaction &, const CBlock *, bool)> SyncTransaction;
// Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
boost::signals2::signal<void (const uint256 &)> EraseTransaction;
// Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
// Notifies listeners of a new active block chain.
boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
// Notifies listeners about an inventory item being seen on the network.
boost::signals2::signal<void (const uint256 &)> Inventory;
// Tells listeners to broadcast their data.
boost::signals2::signal<void (bool)> Broadcast;
} g_signals;
}
void RegisterWallet(CWalletInterface* pwalletIn) {
g_signals.SyncTransaction.connect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
g_signals.EraseTransaction.connect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
g_signals.UpdatedTransaction.connect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.SetBestChain.connect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
g_signals.Inventory.connect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
g_signals.Broadcast.connect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn, _1));
}
void UnregisterWallet(CWalletInterface* pwalletIn) {
g_signals.Broadcast.disconnect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn, _1));
g_signals.Inventory.disconnect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
g_signals.SetBestChain.disconnect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
g_signals.UpdatedTransaction.disconnect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.EraseTransaction.disconnect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
g_signals.SyncTransaction.disconnect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
}
void UnregisterAllWallets() {
g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots();
g_signals.SetBestChain.disconnect_all_slots();
g_signals.UpdatedTransaction.disconnect_all_slots();
g_signals.EraseTransaction.disconnect_all_slots();
g_signals.SyncTransaction.disconnect_all_slots();
}
void SyncWithWallets(const CTransaction &tx, const CBlock *pblock, bool fConnect) {
g_signals.SyncTransaction(tx, pblock, fConnect);
}
void ResendWalletTransactions(bool fForce) {
g_signals.Broadcast(fForce);
}
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.ProcessMessages.connect(&ProcessMessages);
nodeSignals.SendMessages.connect(&SendMessages);
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (nSize > 5000)
{
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", nSize, hash.ToString());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
LogPrint("mempool", "stored orphan tx %s (mapsz %u)\n", hash.ToString(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return;
BOOST_FOREACH(const CTxIn& txin, it->second.vin)
{
map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(hash);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool IsStandardTx(const CTransaction& tx, string& reason)
{
if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Treat non-final transactions as non-standard to prevent a specific type
// of double-spend attack, as well as DoS attacks. (if the transaction
// can't be mined, the attacker isn't expending resources broadcasting it)
// Basically we don't want to propagate transactions that can't be included in
// the next block.
//
// However, IsFinalTx() is confusing... Without arguments, it uses
// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
// is set to the value of nHeight in the block. However, when IsFinalTx()
// is called within CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a transaction can
// be part of the *next* block, we need to call IsFinalTx() with one more
// than chainActive.Height().
//
// Timestamps on the other hand don't get any special treatment, because we
// can't know what timestamp the next block will have, and there aren't
// timestamp applications where it matters.
if (!IsFinalTx(tx, nBestHeight + 1)) {
reason = "non-final";
return false;
}
// nTime has different purpose from nLockTime but can be used in similar attacks
if (tx.nTime > FutureDrift(GetAdjustedTime(), nBestHeight + 1)) {
reason = "time-too-new";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz >= MAX_STANDARD_TX_SIZE) {
reason = "tx-size";
return false;
}
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys. (remember the 520 byte limit on redeemScript size) That works
// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
// bytes of scriptSig, which we round off to 1650 bytes for some minor
// future-proofing. That's also enough to spend a 20-of-20
// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
// considered standard)
if (txin.scriptSig.size() > 1650) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
if (!txin.scriptSig.HasCanonicalPushes()) {
reason = "scriptsig-non-canonical-push";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxOut& txout, tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
else if (txout.nValue == 0) {
reason = "dust";
return false;
}
if (!txout.scriptPubKey.HasCanonicalPushes()) {
reason = "scriptpubkey-non-canonical-push";
return false;
}
}
// not more than one data txout per non-data txout is permitted
// only one data txout is permitted too
if (nDataOut > 1 && nDataOut > tx.vout.size()/2) {
reason = "multi-op-return";
return false;
}
return true;
}
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
AssertLockHeld(cs_main);
// Time based nLockTime implemented in 0.1.6
if (tx.nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
//
// Check transaction inputs to mitigate two
// potential denial-of-service attacks:
//
// 1. scriptSigs with extra data stuffed into them,
// not consumed by scriptPubKey (or P2SH script)
// 2. P2SH scripts with a crazy number of expensive
// CHECKSIG/CHECKMULTISIG operations
//
bool AreInputsStandard(const CTransaction& tx, const MapPrevTx& mapInputs)
{
if (tx.IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut& prev = tx.GetOutputFor(tx.vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig
// IsStandard() will have already returned false
// and this method isn't called.
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, SCRIPT_VERIFY_NONE, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (Solver(subscript, whichType2, vSolutions2))
{
int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
else
{
// Any other Script with less than 15 sigops OK:
unsigned int sigops = subscript.GetSigOpCount(true);
// ... extra data left on the stack after execution is OK, too:
return (sigops <= MAX_P2SH_SIGOPS);
}
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const MapPrevTx& inputs)
{
if (tx.IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut& prevout = tx.GetOutputFor(tx.vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64_t nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64_t GetMinFee(const CTransaction& tx, unsigned int nBlockSize, enum GetMinFee_mode mode, unsigned int nBytes)
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64_t nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("AcceptToMemoryPool : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("AcceptToMemoryPool : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("AcceptToMemoryPool : coinstake as individual tx"));
// Rather not work on nonstandard transactions (unless -testnet)
string reason;
if (!TestNet() && !IsStandardTx(tx, reason))
return error("AcceptToMemoryPool : nonstandard transaction: %s",
reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// Check for conflicts with in-memory transactions
{
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
}
}
}
{
CTxDB txdb("r");
// do we already have it?
if (txdb.ContainsTx(hash))
return false;
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("AcceptToMemoryPool : FetchInputs found invalid tx %s", hash.ToString());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!TestNet() && !AreInputsStandard(tx, mapInputs))
return error("AcceptToMemoryPool : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
unsigned int nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nSigOps > MAX_TX_SIGOPS)
return tx.DoS(0,
error("AcceptToMemoryPool : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, MAX_TX_SIGOPS));
int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64_t txMinFee = GetMinFee(tx, 1000, GMF_RELAY, nSize);
if ((fLimitFree && nFees < txMinFee) || (!fLimitFree && nFees < MIN_TX_FEE))
return error("AcceptToMemoryPool : not enough fees %s, %d < %d",
hash.ToString(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000)
return error("AcceptToMemoryPool : free transaction rejected by rate limiter");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, STANDARD_SCRIPT_VERIFY_FLAGS))
{
return error("AcceptToMemoryPool : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, MANDATORY_SCRIPT_VERIFY_FLAGS))
{
return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
}
}
// Store transaction in memory
pool.addUnchecked(hash, tx);
SyncWithWallets(tx, NULL);
LogPrint("mempool", "AcceptToMemoryPool : accepted %s (poolsz %u)\n",
hash.ToString(),
pool.mapTx.size());
return true;
}
int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree)
{
return ::AcceptToMemoryPool(mempool, *this, fLimitFree, NULL);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb)
{
{
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(false);
}
}
return AcceptToMemoryPool(false);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
if (mempool.lookup(hash, tx))
{
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const uint256& hash)
{
map<uint256, COrphanBlock*>::iterator it = mapOrphanBlocks.find(hash);
if (it == mapOrphanBlocks.end())
return hash;
// Work back to the first block in the orphan chain
do {
map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.find(it->second->hashPrev);
if (it2 == mapOrphanBlocks.end())
return it->first;
it = it2;
} while(true);
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const COrphanBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrev))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrev];
return pblockOrphan->hashPrev;
}
// Remove a random orphan block (which does not have any dependent orphans).
void static PruneOrphanBlocks()
{
size_t nMaxOrphanBlocksSize = GetArg("-maxorphanblocksmib", DEFAULT_MAX_ORPHAN_BLOCKS) * ((size_t) 1 << 20);
while (nOrphanBlocksSize > nMaxOrphanBlocksSize)
{
// Pick a random orphan block.
int pos = insecure_rand() % mapOrphanBlocksByPrev.size();
std::multimap<uint256, COrphanBlock*>::iterator it = mapOrphanBlocksByPrev.begin();
while (pos--) it++;
// As long as this block has other orphans depending on it, move to one of those successors.
do {
std::multimap<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocksByPrev.find(it->second->hashBlock);
if (it2 == mapOrphanBlocksByPrev.end())
break;
it = it2;
} while(1);
setStakeSeenOrphan.erase(it->second->stake);
uint256 hash = it->second->hashBlock;
nOrphanBlocksSize -= it->second->vchBlock.size();
delete it->second;
mapOrphanBlocksByPrev.erase(it);
mapOrphanBlocks.erase(hash);
}
}
static CBigNum GetProofOfStakeLimit(int nHeight)
{
if (IsProtocolV2(nHeight))
return bnProofOfStakeLimitV2;
else
return bnProofOfStakeLimit;
}
// miner's coin base reward
int64_t GetProofOfWorkReward(int64_t nFees)
{
int64_t nSubsidy = 3 * COIN;
LogPrint("creation", "GetProofOfWorkReward() : create=%s nSubsidy=%d\n", FormatMoney(nSubsidy), nSubsidy);
return nSubsidy + nFees;
}
// miner's coin stake reward
int64_t GetProofOfStakeReward(const CBlockIndex* pindexPrev, int64_t nCoinAge, int64_t nFees)
{
int64_t nSubsidy;
if (IsProtocolV3(pindexPrev->nTime))
nSubsidy = COIN * 1;
else
nSubsidy = nCoinAge * COIN_YEAR_REWARD * 33 / (365 * 33 + 8);
LogPrint("creation", "GetProofOfStakeReward(): create=%s nCoinAge=%d\n", FormatMoney(nSubsidy), nCoinAge);
return nSubsidy + nFees;
}
static const int64_t nTargetTimespan = 3 * 60;
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = fProofOfStake ? GetProofOfStakeLimit(pindexLast->nHeight) : Params().ProofOfWorkLimit();
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64_t nTargetSpacing = GetTargetSpacing(pindexLast->nHeight);
int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
if (IsProtocolV1RetargetingFixed(pindexLast->nHeight)) {
if (nActualSpacing < 0)
nActualSpacing = nTargetSpacing;
}
if (IsProtocolV3(pindexLast->nTime)) {
if (nActualSpacing > nTargetSpacing * 10)
nActualSpacing = nTargetSpacing * 10;
}
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64_t nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew <= 0 || bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
bool IsInitialBlockDownload()
{
LOCK(cs_main);
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64_t nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 15 &&
pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainTrust > nBestInvalidTrust)
{
nBestInvalidTrust = pindexNew->nChainTrust;
CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
}
uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
LogPrintf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%d date=%s\n",
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
CBigNum(pindexNew->nChainTrust).ToString(), nBestInvalidBlockTrust.GetLow64(),
DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()));
LogPrintf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%d date=%s\n",
hashBestChain.ToString(), nBestHeight,
CBigNum(pindexBest->nChainTrust).ToString(),
nBestBlockTrust.GetLow64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()));
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool IsConfirmedInNPrevBlocks(const CTxIndex& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth)
{
for (const CBlockIndex* pindex = pindexFrom; pindex && pindexFrom->nHeight - pindex->nHeight < nMaxDepth; pindex = pindex->pprev)
{
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
{
nActualDepth = pindexFrom->nHeight - pindex->nHeight;
return true;
}
}
return false;
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString(), prevout.hash.ToString());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
if (!mempool.lookup(prevout.hash, txPrev))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString(), prevout.hash.ToString());
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString(), prevout.hash.ToString());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64_t nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64_t nValueIn = 0;
int64_t nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
{
int nSpendDepth;
if (IsConfirmedInNPrevBlocks(txindex, pindexBlock, nCoinbaseMaturity, nSpendDepth))
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", nSpendDepth);
}
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
if (IsProtocolV3(nTime))
{
if (txPrev.vout[prevout.n].IsEmpty())
return DoS(1, error("ConnectInputs() : special marker is not spendable"));
}
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString(), txindex.vSpent[prevout.n].ToString());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, flags, 0))
{
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-null dummy arguments;
// if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
if (VerifySignature(txPrev, *this, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0))
return error("ConnectInputs() : %s non-mandatory VerifySignature failed", GetHash().ToString());
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after a soft-fork
// super-majority vote has passed.
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (!IsCoinStake())
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString()));
// Tally transaction fees
int64_t nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString()));
if (!IsProtocolV3(nTime)) {
// enforce transaction fees for every block
int64_t nRequiredFee = GetMinFee(*this);
if (nTxFee < nRequiredFee)
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString(), FormatMoney(nRequiredFee), FormatMoney(nTxFee))) : false;
}
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in, but skip BlockSig checking
if (!CheckBlock(!fJustCheck, !fJustCheck, false))
return false;
unsigned int flags = SCRIPT_VERIFY_NOCACHE;
if (IsProtocolV3(nTime))
{
flags |= SCRIPT_VERIFY_NULLDUMMY |
SCRIPT_VERIFY_STRICTENC |
SCRIPT_VERIFY_ALLOW_EMPTY_SIG |
SCRIPT_VERIFY_FIX_HASHTYPE |
SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
}
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64_t nFees = 0;
int64_t nValueIn = 0;
int64_t nValueOut = 0;
int64_t nStakeReward = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
}
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
int64_t nTxValueIn = tx.GetValueIn(mapInputs);
int64_t nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (tx.IsCoinStake())
nStakeReward = nTxValueOut - nTxValueIn;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, flags))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
if (IsProofOfWork())
{
int64_t nReward = GetProofOfWorkReward(nFees);
// Check coinbase reward
if (vtx[0].GetValueOut() > nReward)
return DoS(50, error("ConnectBlock() : coinbase reward exceeded (actual=%d vs calculated=%d)",
vtx[0].GetValueOut(),
nReward));
}
if (IsProofOfStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64_t nCoinAge;
if (!vtx[1].GetCoinAge(txdb, pindex->pprev, nCoinAge))
return error("ConnectBlock() : %s unable to get coin age for coinstake", vtx[1].GetHash().ToString());
int64_t nCalculatedStakeReward = GetProofOfStakeReward(pindex->pprev, nCoinAge, nFees);
if (nStakeReward > nCalculatedStakeReward)
return DoS(100, error("ConnectBlock() : coinstake pays too much(actual=%d vs calculated=%d)", nStakeReward, nCalculatedStakeReward));
}
// ppcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
LogPrintf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
LogPrintf("REORGANIZE: Disconnect %u blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString(), pindexBest->GetBlockHash().ToString());
LogPrintf("REORGANIZE: Connect %u blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString(), pindexNew->GetBlockHash().ToString());
// Disconnect shorter branch
list<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString());
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()) && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
vResurrect.push_front(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
AcceptToMemoryPool(mempool, tx, false, NULL);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete) {
mempool.remove(tx);
mempool.removeConflicts(tx);
}
LogPrintf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == Params().HashGenesisBlock())
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
LogPrintf("Postponing %u reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
LogPrintf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
LogPrintf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
{
const CBlockLocator locator(pindexNew);
g_signals.SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
LogPrintf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%d date=%s\n",
hashBestChain.ToString(), nBestHeight,
CBigNum(nBestChainTrust).ToString(),
nBestBlockTrust.GetLow64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()));
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, const CBlockIndex* pindexPrev, uint64_t& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
if (IsProtocolV3(nTime))
{
int nSpendDepth;
if (IsConfirmedInNPrevBlocks(txindex, pindexPrev, nStakeMinConfirmations - 1, nSpendDepth))
{
LogPrint("coinage", "coin age skip nSpendDepth=%d\n", nSpendDepth + 1);
continue; // only count coins meeting min confirmations requirement
}
}
else
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
}
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
LogPrint("coinage", "coin age nValueIn=%d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
LogPrint("coinage", "coin age bnCoinDay=%s\n", bnCoinDay.ToString());
nCoinAge = bnCoinDay.getuint64();
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// Record proof hash value
pindexNew->hashProof = hashProof;
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->bnStakeModifierV2 = ComputeStakeModifierV2(pindexNew->pprev, IsProofOfWork() ? hash : vtx[1].vin[0].prevout.hash);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->nChainTrust > nBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
g_signals.UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > FutureDriftV2(GetAdjustedTime()))
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
if (IsProofOfStake())
{
// Coinbase output should be empty if proof-of-stake block
if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake, the rest must not be
if (vtx.empty() || !vtx[1].IsCoinStake())
return DoS(100, error("CheckBlock() : second tx is not coinstake"));
for (unsigned int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : more than one coinstake"));
}
// Check proof-of-stake block signature
if (fCheckSig && !CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64_t)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += GetLegacySigOpCount(tx);
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
AssertLockHeld(cs_main);
if (!IsProtocolV3(nTime)) {
if (nVersion > CURRENT_VERSION)
return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion));
}
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
if (IsProtocolV2(nHeight) && nVersion < 7)
return DoS(100, error("AcceptBlock() : reject too old nVersion = %d", nVersion));
else if (!IsProtocolV2(nHeight) && nVersion > 6)
return DoS(100, error("AcceptBlock() : reject too new nVersion = %d", nVersion));
if (IsProofOfWork() && nHeight > Params().LastPOWBlock())
return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight));
// Check coinbase timestamp
if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime, nHeight))
return DoS(50, error("AcceptBlock() : coinbase timestamp is too early"));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(nHeight, GetBlockTime(), (int64_t)vtx[1].nTime))
return DoS(50, error("AcceptBlock() : coinstake timestamp violation nTimeBlock=%d nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime(), nHeight) < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!IsFinalTx(tx, nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
uint256 hashProof;
// Verify hash target and signature of coinstake tx
if (IsProofOfStake())
{
uint256 targetProofOfStake;
if (!CheckProofOfStake(pindexPrev, vtx[1], nBits, hashProof, targetProofOfStake))
{
return error("AcceptBlock() : check proof-of-stake failed for block %s", hash.ToString());
}
}
// PoW is checked in CheckBlock()
if (IsProofOfWork())
{
hashProof = GetPoWHash();
}
// Check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(nHeight))
return error("AcceptBlock() : rejected by synchronized checkpoint");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos, hashProof))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
return true;
}
uint256 CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return ((CBigNum(1)<<256) / (bnTarget+1)).getuint256();
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
return;
pnode->pindexLastGetBlocksBegin = pindexBegin;
pnode->hashLastGetBlocksEnd = hashEnd;
pnode->PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
bool static IsCanonicalBlockSignature(CBlock* pblock, bool checkLowS)
{
if (pblock->IsProofOfWork()) {
return pblock->vchBlockSig.empty();
}
return checkLowS ? IsLowDERSignature(pblock->vchBlockSig, false) : IsDERSignature(pblock->vchBlockSig, false);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (!fReindex && !fImporting && pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString(), pblock->GetProofOfStake().second, hash.ToString());
if (pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
const CBlockIndex* pcheckpoint = Checkpoints::AutoSelectSyncCheckpoint();
int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
if (pfrom)
pfrom->Misbehaving(1);
return error("ProcessBlock() : block with timestamp before last checkpoint");
}
}
if (!IsCanonicalBlockSignature(pblock, false)) {
if (pfrom && pfrom->nVersion >= CANONICAL_BLOCK_SIG_VERSION) {
pfrom->Misbehaving(100);
}
return error("ProcessBlock(): bad block signature encoding");
}
if (!IsCanonicalBlockSignature(pblock, true)) {
if (pfrom && pfrom->nVersion >= CANONICAL_BLOCK_SIG_LOW_S_VERSION) {
pfrom->Misbehaving(100);
return error("ProcessBlock(): bad block signature encoding (low-s)");
}
if (!EnsureLowS(pblock->vchBlockSig))
return error("ProcessBlock(): EnsureLowS failed");
}
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
// If we don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
LogPrintf("ProcessBlock: ORPHAN BLOCK %lu, prev=%s\n", (unsigned long)mapOrphanBlocks.size(), pblock->hashPrevBlock.ToString());
// Accept orphans as long as there is a node to request its parents from
if (pfrom) {
// ppcoin: check proof-of-stake
if (pblock->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString(), pblock->GetProofOfStake().second, hash.ToString());
}
PruneOrphanBlocks();
COrphanBlock* pblock2 = new COrphanBlock();
{
CDataStream ss(SER_DISK, CLIENT_VERSION);
ss << *pblock;
pblock2->vchBlock = std::vector<unsigned char>(ss.begin(), ss.end());
}
pblock2->hashBlock = hash;
pblock2->hashPrev = pblock->hashPrevBlock;
pblock2->stake = pblock->GetProofOfStake();
nOrphanBlocksSize += pblock2->vchBlock.size();
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrev, pblock2));
if (pblock->IsProofOfStake())
setStakeSeenOrphan.insert(pblock->GetProofOfStake());
// Ask this guy to fill in what we're missing
PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(hash));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, COrphanBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock block;
{
CDataStream ss(mi->second->vchBlock, SER_DISK, CLIENT_VERSION);
ss >> block;
}
block.BuildMerkleTree();
if (block.AcceptBlock())
vWorkQueue.push_back(mi->second->hashBlock);
mapOrphanBlocks.erase(mi->second->hashBlock);
setStakeSeenOrphan.erase(block.GetProofOfStake());
nOrphanBlocksSize -= mi->second->vchBlock.size();
delete mi->second;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
LogPrintf("ProcessBlock: ACCEPTED\n");
return true;
}
#ifdef ENABLE_WALLET
// novacoin: attempt to generate suitable proof-of-stake
bool CBlock::SignBlock(CWallet& wallet, int64_t nFees)
{
// if we are trying to sign
// something except proof-of-stake block template
if (!vtx[0].vout[0].IsEmpty())
return false;
// if we are trying to sign
// a complete proof-of-stake block
if (IsProofOfStake())
return true;
static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
CKey key;
CTransaction txCoinStake;
if (IsProtocolV2(nBestHeight+1))
txCoinStake.nTime &= ~STAKE_TIMESTAMP_MASK;
int64_t nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
int64_t nSearchInterval = IsProtocolV2(nBestHeight+1) ? 1 : nSearchTime - nLastCoinStakeSearchTime;
if (wallet.CreateCoinStake(wallet, nBits, nSearchInterval, nFees, txCoinStake, key))
{
if (txCoinStake.nTime >= pindexBest->GetPastTimeLimit()+1)
{
// make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
vtx[0].nTime = nTime = txCoinStake.nTime;
// we have to make sure that we have no future timestamps in
// our transactions set
for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
vtx.insert(vtx.begin() + 1, txCoinStake);
hashMerkleRoot = BuildMerkleTree();
// append a signature to our block
return key.Sign(GetHash(), vchBlockSig);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
return false;
}
#endif
bool CBlock::CheckBlockSignature() const
{
if (IsProofOfWork())
return vchBlockSig.empty();
if (vchBlockSig.empty())
return false;
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
return CPubKey(vchPubKey).Verify(GetHash(), vchBlockSig);
}
else if (IsProtocolV3(nTime))
{
// Block signing key also can be encoded in the nonspendable output
// This allows to not pollute UTXO set with useless outputs e.g. in case of multisig staking
const CScript& script = txout.scriptPubKey;
CScript::const_iterator pc = script.begin();
opcodetype opcode;
valtype vchPushValue;
if (!script.GetOp(pc, opcode, vchPushValue))
return false;
if (opcode != OP_RETURN)
return false;
if (!script.GetOp(pc, opcode, vchPushValue))
return false;
if (!IsCompressedOrUncompressedPubKey(vchPushValue))
return false;
return CPubKey(vchPushValue).Verify(GetHash(), vchBlockSig);
}
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
string strMessage = _("Error: Disk space is low!");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
while (true)
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
LOCK(cs_main);
if (TestNet())
{
nStakeMinConfirmations = 10;
nCoinbaseMaturity = 10; // test maturity is 10 blocks
}
//
// Load block index
//
CTxDB txdb("cr+");
if (!txdb.LoadBlockIndex())
return false;
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos, Params().HashGenesisBlock()))
return error("LoadBlockIndex() : genesis block not accepted");
}
return true;
}
void PrintBlockTree()
{
AssertLockHeld(cs_main);
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
LogPrintf("| ");
LogPrintf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
LogPrintf("| ");
LogPrintf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
LogPrintf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
LogPrintf("%d (%u,%u) %s %08x %s mint %7s tx %u",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()),
FormatMoney(pindex->nMint),
block.vtx.size());
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
{
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good())
{
boost::this_thread::interruption_point();
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, Params().MessageStart()[0], nRead+1-MESSAGE_START_SIZE);
if (nFind)
{
if (memcmp(nFind, Params().MessageStart(), MESSAGE_START_SIZE)==0)
{
nPos += ((unsigned char*)nFind - pchData) + MESSAGE_START_SIZE;
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - MESSAGE_START_SIZE + 1;
boost::this_thread::interruption_point();
} while(true);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
LOCK(cs_main);
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
LogPrintf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("blipcoin-loadblk");
CImportingNow imp;
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode", false))
strRPC = "test";
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
txInMap = mempool.exists(inv.hash);
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
void static ProcessGetData(CNode* pfrom)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv &inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
// previous versions could accept sigs with high s
if (!IsCanonicalBlockSignature(&block, true)) {
bool ret = EnsureLowS(block.vchBlockSig);
assert(ret);
}
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
CTransaction tx;
if (mempool.lookup(inv.hash, tx)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
pushed = true;
}
}
if (!pushed) {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
g_signals.Inventory(inv.hash);
if (inv.type == MSG_BLOCK /* || inv.type == MSG_FILTERED_BLOCK */)
break;
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage("notfound", vNotFound);
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
{
RandAddSeedPerfmon();
LogPrint("net", "received: %s (%u bytes)\n", strCommand, vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable())
{
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
{
pfrom->PushAddress(addr);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(pfrom->addrLocal);
pfrom->PushAddress(addr);
}
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
LogPrintf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), addrFrom.ToString(), pfrom->addr.ToString());
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset;
if (GetBoolArg("-synctime", true))
AddTimeData(pfrom->addr, nTimeOffset);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %u", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
LOCK(cs_main);
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
LogPrint("net", " got inventory: %s %s\n", inv.ToString(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave) {
if (!fImporting)
pfrom->AskFor(inv);
} else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(inv.hash));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
LogPrintf("force request: %s\n", inv.ToString());
}
// Track requests for our stuff
g_signals.Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1))
LogPrint("net", "received getdata (%u invsz)\n", vInv.size());
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s\n", vInv[0].ToString());
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
mapAlreadyAskedFor.erase(inv);
if (AcceptToMemoryPool(mempool, tx, true, &fMissingInputs))
{
RelayTransaction(tx, inv.hash);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
if (itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for (set<uint256>::iterator mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi)
{
const uint256& orphanTxHash = *mi;
CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
bool fMissingInputs2 = false;
if (AcceptToMemoryPool(mempool, orphanTx, true, &fMissingInputs2))
{
LogPrint("mempool", " accepted orphan tx %s\n", orphanTxHash.ToString());
RelayTransaction(orphanTx, orphanTxHash);
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
}
else if (!fMissingInputs2)
{
// invalid or too-little-fee orphan
vEraseQueue.push_back(orphanTxHash);
LogPrint("mempool", " removed orphan tx %s\n", orphanTxHash.ToString());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
LogPrint("net", "received block %s\n", hashBlock.ToString());
CInv inv(MSG_BLOCK, hashBlock);
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making users (which are behind NAT and can only make outgoing connections) ignore
// getaddr message mitigates the attack.
else if ((strCommand == "getaddr") && (pfrom->fInbound))
{
// Don't return addresses older than nCutOff timestamp
int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
if(addr.nTime > nCutOff)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
LOCK(cs_main);
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "pong")
{
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong %s %s: %s, %x expected, %x received, %zu bytes\n"
, pfrom->addr.ToString()
, pfrom->strSubVer
, sProblem
, pfrom->nPingNonceSent
, nonce
, nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// LogPrintf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom);
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return fOk;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// LogPrintf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid())
{
LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand, nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
boost::this_thread::interruption_point();
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand, nMessageSize);
break;
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
RAND_bytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce;
pto->PushMessage("ping", nonce);
} else {
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
pto->PushMessage("ping");
}
}
// Start block sync
if (pto->fStartSync && !fImporting && !fReindex) {
pto->fStartSync = false;
PushGetBlocks(pto, pindexBest, uint256(0));
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
ResendWalletTransactions();
}
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
AdvertizeLocal(pnode);
}
if (!vNodes.empty())
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64_t nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebug)
LogPrint("net", "sending getdata: %s\n", inv.ToString());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018 Intel Corporation
#include "../test_precomp.hpp"
#include "../common/gapi_imgproc_tests.hpp"
#include "opencv2/gapi/cpu/imgproc.hpp"
#define IMGPROC_CPU cv::gapi::imgproc::cpu::kernels()
namespace opencv_test
{
INSTANTIATE_TEST_CASE_P(Filter2DTestCPU, Filter2DTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 4, 5, 7),
Values(cv::Size(1280, 720),
cv::Size(640, 480),
cv::Size(128, 128)),
Values(cv::BORDER_DEFAULT),
Values(-1, CV_32F),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(BoxFilterTestCPU, BoxFilterTest,
Combine(Values(AbsTolerance(0).to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3,5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(cv::BORDER_DEFAULT),
Values(-1, CV_32F),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(SepFilterTestCPU_8U, SepFilterTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3),
Values(3),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(-1, CV_16S, CV_32F),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(SepFilterTestCPU_other, SepFilterTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_16UC1, CV_16SC1, CV_32FC1),
Values(3),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(-1, CV_32F),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(BlurTestCPU, BlurTest,
Combine(Values(AbsTolerance(0.0).to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3,5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(cv::BORDER_DEFAULT),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(gaussBlurTestCPU, GaussianBlurTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(MedianBlurTestCPU, MedianBlurTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(ErodeTestCPU, ErodeTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(cv::MorphShapes::MORPH_RECT,
cv::MorphShapes::MORPH_CROSS,
cv::MorphShapes::MORPH_ELLIPSE),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(Erode3x3TestCPU, Erode3x3Test,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(1,2,4),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(DilateTestCPU, DilateTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(cv::MorphShapes::MORPH_RECT,
cv::MorphShapes::MORPH_CROSS,
cv::MorphShapes::MORPH_ELLIPSE),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(Dilate3x3TestCPU, Dilate3x3Test,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(1,2,4),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(SobelTestCPU, SobelTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1),
Values(3, 5),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(-1, CV_32F),
Values(0, 1),
Values(1, 2),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(EqHistTestCPU, EqHistTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(CannyTestCPU, CannyTest,
Combine(Values(AbsExact().to_compare_f()),
Values(CV_8UC1, CV_8UC3),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(3.0, 120.0),
Values(125.0, 240.0),
Values(3, 5),
testing::Bool(),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(RGB2GrayTestCPU, RGB2GrayTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(BGR2GrayTestCPU, BGR2GrayTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(RGB2YUVTestCPU, RGB2YUVTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(YUV2RGBTestCPU, YUV2RGBTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(RGB2LabTestCPU, RGB2LabTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(BGR2LUVTestCPU, BGR2LUVTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(LUV2BGRTestCPU, LUV2BGRTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(BGR2YUVTestCPU, BGR2YUVTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
INSTANTIATE_TEST_CASE_P(YUV2BGRTestCPU, YUV2BGRTest,
Combine(Values(AbsExact().to_compare_f()),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
/*init output matrices or not*/ testing::Bool(),
Values(cv::compile_args(IMGPROC_CPU))));
} // opencv_test
|
//
// Package: RecoTracker/FinalTrackSelectors
// Class: ConversionTrackProducer
//
// Description: Trivial producer of ConversionTrack collection from an edm::View of a track collection
// (ConversionTrack is a simple wrappper class containing a TrackBaseRef and some additional flags)
//
// Original Author: J.Bendavid
//
//
#include <memory>
#include <string>
#include <iostream>
#include <cmath>
#include <vector>
#include "TrackingTools/PatternTools/interface/Trajectory.h"
#include "DataFormats/GsfTrackReco/interface/GsfTrack.h"
#include "DataFormats/GsfTrackReco/interface/GsfTrackFwd.h"
#include "RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackProducer.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/BeamSpot/interface/BeamSpot.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
ConversionTrackProducer::ConversionTrackProducer(edm::ParameterSet const& conf) :
conf_(conf),
trackProducer ( conf.getParameter<std::string>("TrackProducer") ),
useTrajectory ( conf.getParameter<bool>("useTrajectory") ),
setTrackerOnly ( conf.getParameter<bool>("setTrackerOnly") ),
setArbitratedEcalSeeded ( conf.getParameter<bool>("setArbitratedEcalSeeded") ),
setArbitratedMerged ( conf.getParameter<bool>("setArbitratedMerged") ),
setArbitratedMergedEcalGeneral ( conf.getParameter<bool>("setArbitratedMergedEcalGeneral") ),
beamSpotInputTag ( consumes<reco::BeamSpot>(conf.getParameter<edm::InputTag>("beamSpotInputTag")) ),
filterOnConvTrackHyp( conf.getParameter<bool>("filterOnConvTrackHyp") ),
minConvRadius( conf.getParameter<double>("minConvRadius") )
{
edm::InputTag thetp(trackProducer);
genericTracks =
consumes<edm::View<reco::Track> >(thetp);
kfTrajectories =
consumes<TrajTrackAssociationCollection>(thetp);
gsfTrajectories =
consumes<TrajGsfTrackAssociationCollection>(thetp);
produces<reco::ConversionTrackCollection>();
}
// Virtual destructor needed.
ConversionTrackProducer::~ConversionTrackProducer() { }
// Functions that gets called by framework every event
void ConversionTrackProducer::produce(edm::Event& e, const edm::EventSetup& es)
{
//get input collection (through edm::View)
edm::Handle<edm::View<reco::Track> > hTrks;
e.getByToken(genericTracks, hTrks);
//get association maps between trajectories and tracks and build temporary maps
edm::Handle< TrajTrackAssociationCollection > hTTAss;
edm::Handle< TrajGsfTrackAssociationCollection > hTTAssGsf;
std::map<reco::TrackRef,edm::Ref<std::vector<Trajectory> > > tracktrajmap;
std::map<reco::GsfTrackRef,edm::Ref<std::vector<Trajectory> > > gsftracktrajmap;
if (useTrajectory) {
if (hTrks->size()>0) {
if (dynamic_cast<const reco::GsfTrack*>(&hTrks->at(0))) {
//fill map for gsf tracks
e.getByToken(gsfTrajectories, hTTAssGsf);
for ( TrajGsfTrackAssociationCollection::const_iterator iPair =
hTTAssGsf->begin();
iPair != hTTAssGsf->end(); ++iPair) {
gsftracktrajmap[iPair->val] = iPair->key;
}
}
else {
//fill map for standard tracks
e.getByToken(kfTrajectories, hTTAss);
for ( TrajTrackAssociationCollection::const_iterator iPair = hTTAss->begin();
iPair != hTTAss->end();
++iPair) {
tracktrajmap[iPair->val] = iPair->key;
}
}
}
}
// Step B: create empty output collection
outputTrks = std::make_unique<reco::ConversionTrackCollection>();
//--------------------------------------------------
//Added by D. Giordano
// 2011/08/05
// Reduction of the track sample based on geometric hypothesis for conversion tracks
edm::Handle<reco::BeamSpot> beamSpotHandle;
e.getByToken(beamSpotInputTag,beamSpotHandle);
edm::ESHandle<MagneticField> magFieldHandle;
es.get<IdealMagneticFieldRecord>().get( magFieldHandle );
if(filterOnConvTrackHyp && !beamSpotHandle.isValid()) {
edm::LogError("Invalid Collection")
<< "invalid collection for the BeamSpot";
throw;
}
ConvTrackPreSelector.setMagnField(magFieldHandle.product());
//----------------------------------------------------------
// Simple conversion of tracks to conversion tracks, setting appropriate flags from configuration
for (size_t i = 0; i < hTrks->size(); ++i) {
//--------------------------------------------------
//Added by D. Giordano
// 2011/08/05
// Reduction of the track sample based on geometric hypothesis for conversion tracks
math::XYZVector beamSpot= math::XYZVector(beamSpotHandle->position());
edm::RefToBase<reco::Track> trackBaseRef = hTrks->refAt(i);
if( filterOnConvTrackHyp && ConvTrackPreSelector.isTangentPointDistanceLessThan( minConvRadius, trackBaseRef.get(), beamSpot ) )
continue;
//--------------------------------------------------
reco::ConversionTrack convTrack(trackBaseRef);
convTrack.setIsTrackerOnly(setTrackerOnly);
convTrack.setIsArbitratedEcalSeeded(setArbitratedEcalSeeded);
convTrack.setIsArbitratedMerged(setArbitratedMerged);
convTrack.setIsArbitratedMergedEcalGeneral(setArbitratedMergedEcalGeneral);
//fill trajectory association if configured, using correct map depending on track type
if (useTrajectory) {
if (gsftracktrajmap.size()) {
convTrack.setTrajRef(gsftracktrajmap.find(trackBaseRef.castTo<reco::GsfTrackRef>())->second);
}
else {
convTrack.setTrajRef(tracktrajmap.find(trackBaseRef.castTo<reco::TrackRef>())->second);
}
}
outputTrks->push_back(convTrack);
}
e.put(std::move(outputTrks));
return;
}//end produce
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h"
#include "itkQuadEdgeMeshEulerOperatorsTestHelper.h"
int itkQuadEdgeMeshEulerOperatorSplitEdgeTest( int, char * [] )
{
using MeshType = itk::QuadEdgeMesh< double, 3 >;
using MeshPointer = MeshType::Pointer;
using QEType = MeshType::QEType;
using SplitEdge =
itk::QuadEdgeMeshEulerOperatorSplitEdgeFunction< MeshType, QEType>;
/////////////////////////////////////////
//
// Split Edge
//
/////////////////////////////////////////
std::cout << "Checking SplitEdge." << std::endl;
MeshPointer mesh = MeshType::New();
CreateSquareTriangularMesh<MeshType>( mesh );
SplitEdge::Pointer splitEdge = SplitEdge::New( );
std::cout << " " << "Test No Mesh Input";
if( splitEdge->Evaluate( (QEType*)1 ) )
{
std::cout << "FAILED." << std::endl;
return EXIT_FAILURE;
}
std::cout << "OK" << std::endl;
(void)splitEdge->GetNameOfClass();
splitEdge->SetInput( mesh );
std::cout << " " << "Test No QE Input";
if( splitEdge->Evaluate( (QEType*)nullptr ) )
{
std::cout << "FAILED." << std::endl;
return EXIT_FAILURE;
}
std::cout << "OK" << std::endl;
std::cout << " ";
std::cout << "Split an internal edge (possible).";
if( !splitEdge->Evaluate( mesh->FindEdge( 6, 12 ) ) )
{
std::cout << "FAILED." << std::endl;
return EXIT_FAILURE;
}
if( ! AssertTopologicalInvariants< MeshType >
( mesh, 26, 57, 32, 1, 0 ) )
{
std::cout << "FAILED." << std::endl;
return EXIT_FAILURE;
}
std::cout << ".OK" << std::endl;
std::cout << "Checking SplitEdge." << "OK" << std::endl << std::endl;
return EXIT_SUCCESS;
}
|
/* This file is part of CosmoLattice, available at www.cosmolattice.net .
Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg.
Released under the MIT license, see LICENSE.md. */
// File info: Main contributor(s): Daniel G. Figueroa, Adrien Florio, Francisco Torrenti, Year: 2020
#include "CosmoInterface/evolvers/kernels/scalarsingletkernels.h"
namespace {
TempLat::TDDContainer<TempLat::ScalarSingletKernels> test;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <validation.h>
#include <arith_uint256.h>
#include <chain.h>
#include <chainparams.h>
#include <checkqueue.h>
#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <cuckoocache.h>
#include <deploymentstatus.h>
#include <flatfile.h>
#include <hash.h>
#include <index/blockfilterindex.h>
#include <logging.h>
#include <logging/timer.h>
#include <node/blockstorage.h>
#include <node/coinstats.h>
#include <node/ui_interface.h>
#include <node/utxo_snapshot.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <policy/settings.h>
#include <pow.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <random.h>
#include <reverse_iterator.h>
#include <script/script.h>
#include <script/sigcache.h>
#include <shutdown.h>
#include <signet.h>
#include <timedata.h>
#include <tinyformat.h>
#include <txdb.h>
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
#include <util/check.h> // For NDEBUG compile time check
#include <util/hasher.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/trace.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <numeric>
#include <optional>
#include <string>
#include <boost/algorithm/string/replace.hpp>
#define MICRO 0.000001
#define MILLI 0.001
/**
* An extra transaction can be added to a package, as long as it only has one
* ancestor and is no larger than this. Not really any reason to make this
* configurable as it doesn't materially change DoS parameters.
*/
static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
/** Maximum kilobytes for transactions to store for processing during reorg */
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
/** Time to wait between writing blocks/block index to disk. */
static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
/** Time to wait between flushing chainstate to disk. */
static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
/** Maximum age of our tip for us to be considered current for fee estimation */
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
const std::vector<std::string> CHECKLEVEL_DOC {
"level 0 reads the blocks from disk",
"level 1 verifies block validity",
"level 2 verifies undo data",
"level 3 checks disconnection of tip blocks",
"level 4 tries to reconnect the blocks",
"each level includes the checks of the previous levels",
};
bool CBlockIndexWorkComparator::operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
// First sort by most total work, ...
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ...
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks
// loaded from disk, as those all have id 0).
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks.
return false;
}
/**
* Mutex to guard access to validation specific variables, such as reading
* or changing the chainstate.
*
* This may also need to be locked when updating the transaction pool, e.g. on
* AcceptToMemoryPool. See CTxMemPool::cs comment for details.
*
* The transaction pool has a separate lock to allow reading from it and the
* chainstate at the same time.
*/
RecursiveMutex cs_main;
CBlockIndex *pindexBestHeader = nullptr;
Mutex g_best_block_mutex;
std::condition_variable g_best_block_cv;
uint256 g_best_block;
bool g_parallel_script_checks{false};
bool fRequireStandard = true;
bool fCheckBlockIndex = false;
bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
uint256 hashAssumeValid;
arith_uint256 nMinimumChainWork;
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
// Internal stuff
namespace {
CBlockIndex* pindexBestInvalid = nullptr;
} // namespace
// Internal stuff from blockstorage ...
extern RecursiveMutex cs_LastBlockFile;
extern std::vector<CBlockFileInfo> vinfoBlockFile;
extern int nLastBlockFile;
extern bool fCheckForPruning;
extern std::set<CBlockIndex*> setDirtyBlockIndex;
extern std::set<int> setDirtyFileInfo;
void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false);
// ... TODO move fully to blockstorage
CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
{
AssertLockHeld(cs_main);
BlockMap::const_iterator it = m_block_index.find(hash);
return it == m_block_index.end() ? nullptr : it->second;
}
CBlockIndex* BlockManager::FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
AssertLockHeld(cs_main);
// Find the latest block common to locator and chain - we expect that
// locator.vHave is sorted descending by height.
for (const uint256& hash : locator.vHave) {
CBlockIndex* pindex = LookupBlockIndex(hash);
if (pindex) {
if (chain.Contains(pindex))
return pindex;
if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
return chain.Tip();
}
}
}
return chain.Genesis();
}
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
std::vector<CScriptCheck>* pvChecks = nullptr)
EXCLUSIVE_LOCKS_REQUIRED(cs_main);
bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags)
{
AssertLockHeld(cs_main);
assert(active_chain_tip); // TODO: Make active_chain_tip a reference
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0);
// CheckFinalTx() uses active_chain_tip.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than active_chain_tip.Height().
const int nBlockHeight = active_chain_tip->nHeight + 1;
// BIP113 requires that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
? active_chain_tip->GetMedianTimePast()
: GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime);
}
bool TestLockPointValidity(CChain& active_chain, const LockPoints* lp)
{
AssertLockHeld(cs_main);
assert(lp);
// If there are relative lock times then the maxInputBlock will be set
// If there are no relative lock times, the LockPoints don't depend on the chain
if (lp->maxInputBlock) {
// Check whether active_chain is an extension of the block at which the LockPoints
// calculation was valid. If not LockPoints are no longer valid
if (!active_chain.Contains(lp->maxInputBlock)) {
return false;
}
}
// LockPoints still valid
return true;
}
bool CheckSequenceLocks(CBlockIndex* tip,
const CCoinsView& coins_view,
const CTransaction& tx,
int flags,
LockPoints* lp,
bool useExistingLockPoints)
{
assert(tip != nullptr);
CBlockIndex index;
index.pprev = tip;
// CheckSequenceLocks() uses active_chainstate.m_chain.Height()+1 to evaluate
// height based locks because when SequenceLocks() is called within
// ConnectBlock(), the height of the block *being*
// evaluated is what is used.
// Thus if we want to know if a transaction can be part of the
// *next* block, we need to use one more than active_chainstate.m_chain.Height()
index.nHeight = tip->nHeight + 1;
std::pair<int, int64_t> lockPair;
if (useExistingLockPoints) {
assert(lp);
lockPair.first = lp->height;
lockPair.second = lp->time;
}
else {
std::vector<int> prevheights;
prevheights.resize(tx.vin.size());
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
Coin coin;
if (!coins_view.GetCoin(txin.prevout, coin)) {
return error("%s: Missing input", __func__);
}
if (coin.nHeight == MEMPOOL_HEIGHT) {
// Assume all mempool transaction confirm in the next block
prevheights[txinIndex] = tip->nHeight + 1;
} else {
prevheights[txinIndex] = coin.nHeight;
}
}
lockPair = CalculateSequenceLocks(tx, flags, prevheights, index);
if (lp) {
lp->height = lockPair.first;
lp->time = lockPair.second;
// Also store the hash of the block with the highest height of
// all the blocks which have sequence locked prevouts.
// This hash needs to still be on the chain
// for these LockPoint calculations to be valid
// Note: It is impossible to correctly calculate a maxInputBlock
// if any of the sequence locked inputs depend on unconfirmed txs,
// except in the special case where the relative lock time/height
// is 0, which is equivalent to no sequence lock. Since we assume
// input height of tip+1 for mempool txs and test the resulting
// lockPair from CalculateSequenceLocks against tip+1. We know
// EvaluateSequenceLocks will fail if there was a non-zero sequence
// lock on a mempool input, so we can use the return value of
// CheckSequenceLocks to indicate the LockPoints validity
int maxInputHeight = 0;
for (const int height : prevheights) {
// Can ignore mempool inputs since we'll fail if they had non-zero locks
if (height != tip->nHeight+1) {
maxInputHeight = std::max(maxInputHeight, height);
}
}
lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
}
}
return EvaluateSequenceLocks(index, lockPair);
}
// Returns the script flags which should be checked for a given block
static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache, size_t limit, std::chrono::seconds age)
EXCLUSIVE_LOCKS_REQUIRED(pool.cs, ::cs_main)
{
int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
if (expired != 0) {
LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
}
std::vector<COutPoint> vNoSpendsRemaining;
pool.TrimToSize(limit, &vNoSpendsRemaining);
for (const COutPoint& removed : vNoSpendsRemaining)
coins_cache.Uncache(removed);
}
static bool IsCurrentForFeeEstimation(CChainState& active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
AssertLockHeld(cs_main);
if (active_chainstate.IsInitialBlockDownload())
return false;
if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
return false;
if (active_chainstate.m_chain.Height() < pindexBestHeader->nHeight - 1)
return false;
return true;
}
void CChainState::MaybeUpdateMempoolForReorg(
DisconnectedBlockTransactions& disconnectpool,
bool fAddToMempool)
{
if (!m_mempool) return;
AssertLockHeld(cs_main);
AssertLockHeld(m_mempool->cs);
std::vector<uint256> vHashUpdate;
// disconnectpool's insertion_order index sorts the entries from
// oldest to newest, but the oldest entry will be the last tx from the
// latest mined block that was disconnected.
// Iterate disconnectpool in reverse, so that we add transactions
// back to the mempool starting with the earliest transaction that had
// been previously seen in a block.
auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
// ignore validation errors in resurrected transactions
if (!fAddToMempool || (*it)->IsCoinBase() ||
AcceptToMemoryPool(
*this, *m_mempool, *it, true /* bypass_limits */).m_result_type !=
MempoolAcceptResult::ResultType::VALID) {
// If the transaction doesn't make it in to the mempool, remove any
// transactions that depend on it (which would now be orphans).
m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
} else if (m_mempool->exists((*it)->GetHash())) {
vHashUpdate.push_back((*it)->GetHash());
}
++it;
}
disconnectpool.queuedTx.clear();
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
// no in-mempool children, which is generally not true when adding
// previously-confirmed transactions back to the mempool.
// UpdateTransactionsFromBlock finds descendants of any transactions in
// the disconnectpool that were added back and cleans up the mempool state.
m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
// We also need to remove any now-immature transactions
m_mempool->removeForReorg(*this, STANDARD_LOCKTIME_VERIFY_FLAGS);
// Re-limit mempool size, in case we added any transactions
LimitMempoolSize(
*m_mempool,
this->CoinsTip(),
gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
}
/**
* Checks to avoid mempool polluting consensus critical paths since cached
* signature and script validity results will be reused if we validate this
* transaction again during block validation.
* */
static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state,
const CCoinsViewCache& view, const CTxMemPool& pool,
unsigned int flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip)
EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
{
AssertLockHeld(cs_main);
AssertLockHeld(pool.cs);
assert(!tx.IsCoinBase());
for (const CTxIn& txin : tx.vin) {
const Coin& coin = view.AccessCoin(txin.prevout);
// This coin was checked in PreChecks and MemPoolAccept
// has been holding cs_main since then.
Assume(!coin.IsSpent());
if (coin.IsSpent()) return false;
// If the Coin is available, there are 2 possibilities:
// it is available in our current ChainstateActive UTXO set,
// or it's a UTXO provided by a transaction in our mempool.
// Ensure the scriptPubKeys in Coins from CoinsView are correct.
const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
if (txFrom) {
assert(txFrom->GetHash() == txin.prevout.hash);
assert(txFrom->vout.size() > txin.prevout.n);
assert(txFrom->vout[txin.prevout.n] == coin.out);
} else {
const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
assert(!coinFromUTXOSet.IsSpent());
assert(coinFromUTXOSet.out == coin.out);
}
}
// Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata);
}
namespace {
class MemPoolAccept
{
public:
explicit MemPoolAccept(CTxMemPool& mempool, CChainState& active_chainstate) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate),
m_limit_ancestors(gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
m_limit_ancestor_size(gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
m_limit_descendants(gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
m_limit_descendant_size(gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
}
// We put the arguments we're handed into a struct, so we can pass them
// around easier.
struct ATMPArgs {
const CChainParams& m_chainparams;
const int64_t m_accept_time;
const bool m_bypass_limits;
/*
* Return any outpoints which were not previously present in the coins
* cache, but were added as a result of validating the tx for mempool
* acceptance. This allows the caller to optionally remove the cache
* additions if the associated transaction ends up being rejected by
* the mempool.
*/
std::vector<COutPoint>& m_coins_to_uncache;
const bool m_test_accept;
/** Whether we allow transactions to replace mempool transactions by BIP125 rules. If false,
* any transaction spending the same inputs as a transaction in the mempool is considered
* a conflict. */
const bool m_allow_bip125_replacement{true};
};
// Single transaction acceptance
MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
/**
* Multiple transaction acceptance. Transactions may or may not be interdependent,
* but must not conflict with each other. Parents must come before children if any
* dependencies exist.
*/
PackageMempoolAcceptResult AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
private:
// All the intermediate state that gets passed between the various levels
// of checking a given transaction.
struct Workspace {
explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
std::set<uint256> m_conflicts;
CTxMemPool::setEntries m_all_conflicting;
CTxMemPool::setEntries m_ancestors;
std::unique_ptr<CTxMemPoolEntry> m_entry;
std::list<CTransactionRef> m_replaced_transactions;
CAmount m_base_fees;
CAmount m_modified_fees;
/** Total modified fees of all transactions being replaced. */
CAmount m_conflicting_fees{0};
/** Total virtual size of all transactions being replaced. */
size_t m_conflicting_size{0};
const CTransactionRef& m_ptx;
const uint256& m_hash;
TxValidationState m_state;
};
// Run the policy checks on a given transaction, excluding any script checks.
// Looks up inputs, calculates feerate, considers replacement, evaluates
// package limits, etc. As this function can be invoked for "free" by a peer,
// only tests that are fast should be done here (to avoid CPU DoS).
bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
// Run the script checks using our policy flags. As this can be slow, we should
// only invoke this on transactions that have otherwise passed policy checks.
bool PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
// Re-run the script checks, using consensus flags, and try to cache the
// result in the scriptcache. This should be done after
// PolicyScriptChecks(). This requires that all inputs either be in our
// utxo set or in the mempool.
bool ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
// Try to add the transaction to the mempool, removing any conflicts first.
// Returns true if the transaction is in the mempool after any size
// limiting is performed, false otherwise.
bool Finalize(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
// Compare a package's feerate against minimum allowed.
bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
{
CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
}
if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
}
return true;
}
private:
CTxMemPool& m_pool;
CCoinsViewCache m_view;
CCoinsViewMemPool m_viewmempool;
CCoinsView m_dummy;
CChainState& m_active_chainstate;
// The package limits in effect at the time of invocation.
const size_t m_limit_ancestors;
const size_t m_limit_ancestor_size;
// These may be modified while evaluating a transaction (eg to account for
// in-mempool conflicts; see below).
size_t m_limit_descendants;
size_t m_limit_descendant_size;
};
bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
{
const CTransactionRef& ptx = ws.m_ptx;
const CTransaction& tx = *ws.m_ptx;
const uint256& hash = ws.m_hash;
// Copy/alias what we need out of args
const int64_t nAcceptTime = args.m_accept_time;
const bool bypass_limits = args.m_bypass_limits;
std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
// Alias what we need out of ws
TxValidationState& state = ws.m_state;
std::set<uint256>& setConflicts = ws.m_conflicts;
CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
CAmount& nModifiedFees = ws.m_modified_fees;
CAmount& nConflictingFees = ws.m_conflicting_fees;
size_t& nConflictingSize = ws.m_conflicting_size;
if (!CheckTransaction(tx, state)) {
return false; // state filled in by CheckTransaction
}
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
std::string reason;
if (fRequireStandard && !IsStandardTx(tx, reason))
return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
// Do not work on transactions that are too small.
// A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
// Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
// 64-byte transactions.
if (::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) < MIN_STANDARD_TX_NONWITNESS_SIZE)
return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
// Only accept nLockTime-using transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
if (!CheckFinalTx(m_active_chainstate.m_chain.Tip(), tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
if (m_pool.exists(GenTxid(true, tx.GetWitnessHash()))) {
// Exact transaction already exists in the mempool.
return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
} else if (m_pool.exists(GenTxid(false, tx.GetHash()))) {
// Transaction with the same non-witness data but different witness (same txid, different
// wtxid) already exists in the mempool.
return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
}
// Check for conflicts with in-memory transactions
for (const CTxIn &txin : tx.vin)
{
const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
if (ptxConflicting) {
if (!args.m_allow_bip125_replacement) {
// Transaction conflicts with a mempool tx, but we're not allowing replacements.
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
}
if (!setConflicts.count(ptxConflicting->GetHash()))
{
// Transactions that don't explicitly signal replaceability are
// *not* replaceable with the current logic, even if one of their
// unconfirmed ancestors signals replaceability. This diverges
// from BIP125's inherited signaling description (see CVE-2021-31876).
// Applications relying on first-seen mempool behavior should
// check all unconfirmed ancestors; otherwise an opt-in ancestor
// might be replaced, causing removal of this descendant.
if (!SignalsOptInRBF(*ptxConflicting)) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
}
setConflicts.insert(ptxConflicting->GetHash());
}
}
}
LockPoints lp;
m_view.SetBackend(m_viewmempool);
const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
// do all inputs exist?
for (const CTxIn& txin : tx.vin) {
if (!coins_cache.HaveCoinInCache(txin.prevout)) {
coins_to_uncache.push_back(txin.prevout);
}
// Note: this call may add txin.prevout to the coins cache
// (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
// later (via coins_to_uncache) if this tx turns out to be invalid.
if (!m_view.HaveCoin(txin.prevout)) {
// Are inputs missing because we already have the tx?
for (size_t out = 0; out < tx.vout.size(); out++) {
// Optimistically just do efficient check of cache for outputs
if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
}
}
// Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
}
}
// This is const, but calls into the back end CoinsViews. The CCoinsViewDB at the bottom of the
// hierarchy brings the best block into scope. See CCoinsViewDB::GetBestBlock().
m_view.GetBestBlock();
// we have all inputs cached now, so switch back to dummy (to protect
// against bugs where we pull more inputs from disk that miss being added
// to coins_to_uncache)
m_view.SetBackend(m_dummy);
// Only accept BIP68 sequence locked transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
// Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
// backend was removed, it no longer pulls coins from the mempool.
if (!CheckSequenceLocks(m_active_chainstate.m_chain.Tip(), m_view, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_blockman.GetSpendHeight(m_view), ws.m_base_fees)) {
return false; // state filled in by CheckTxInputs
}
// Check for non-standard pay-to-script-hash in inputs
const bool taproot_active = DeploymentActiveAfter(m_active_chainstate.m_chain.Tip(), args.m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_TAPROOT);
if (fRequireStandard && !AreInputsStandard(tx, m_view, taproot_active)) {
return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
}
// Check for non-standard witnesses.
if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
// nModifiedFees includes any fee deltas from PrioritiseTransaction
nModifiedFees = ws.m_base_fees;
m_pool.ApplyDelta(hash, nModifiedFees);
// Keep track of transactions that spend a coinbase, which we re-scan
// during reorgs to ensure COINBASE_MATURITY is still met.
bool fSpendsCoinbase = false;
for (const CTxIn &txin : tx.vin) {
const Coin &coin = m_view.AccessCoin(txin.prevout);
if (coin.IsCoinBase()) {
fSpendsCoinbase = true;
break;
}
}
entry.reset(new CTxMemPoolEntry(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(),
fSpendsCoinbase, nSigOpsCost, lp));
unsigned int nSize = entry->GetTxSize();
if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
strprintf("%d", nSigOpsCost));
// No transactions are allowed below minRelayTxFee except from disconnected
// blocks
if (!bypass_limits && !CheckFeeRate(nSize, nModifiedFees, state)) return false;
const CTxMemPool::setEntries setIterConflicting = m_pool.GetIterSet(setConflicts);
// Calculate in-mempool ancestors, up to a limit.
if (setConflicts.size() == 1) {
// In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
// would meet the chain limits after the conflicts have been removed. However, there isn't a practical
// way to do this short of calculating the ancestor and descendant sets with an overlay cache of
// changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
// very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
// conflicts here. Importantly, we need to ensure that some transactions which were accepted using
// the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
// for off-chain contract systems (see link in the comment below).
//
// Specifically, the subset of RBF transactions which we allow despite chain limits are those which
// conflict directly with exactly one other transaction (but may evict children of said transaction),
// and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
// check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
// amended, we may need to move that check to here instead of removing it wholesale.
//
// Such transactions are clearly not merging any existing packages, so we are only concerned with
// ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
// not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
// to.
//
// To check these we first check if we meet the RBF criteria, above, and increment the descendant
// limits by the direct conflict and its descendants (as these are recalculated in
// CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
// removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
// the ancestor limits should be the same for both our new transaction and any conflicts).
// We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
// into force here (as we're only adding a single transaction).
assert(setIterConflicting.size() == 1);
CTxMemPool::txiter conflict = *setIterConflicting.begin();
m_limit_descendants += 1;
m_limit_descendant_size += conflict->GetSizeWithDescendants();
}
std::string errString;
if (!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
setAncestors.clear();
// If CalculateMemPoolAncestors fails second time, we want the original error string.
std::string dummy_err_string;
// Contracting/payment channels CPFP carve-out:
// If the new transaction is relatively small (up to 40k weight)
// and has at most one ancestor (ie ancestor limit of 2, including
// the new transaction), allow it if its parent has exactly the
// descendant limit descendants.
//
// This allows protocols which rely on distrusting counterparties
// being able to broadcast descendants of an unconfirmed transaction
// to be secure by simply only having two immediately-spendable
// outputs - one for each counterparty. For more info on the uses for
// this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
if (nSize > EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
}
}
// A transaction that spends outputs that would be replaced by it is invalid. Now
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
if (const auto err_string{EntriesAndTxidsDisjoint(setAncestors, setConflicts, hash)}) {
// We classify this as a consensus error because a transaction depending on something it
// conflicts with would be inconsistent.
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
}
if (!setConflicts.empty()) {
CFeeRate newFeeRate(nModifiedFees, nSize);
// It's possible that the replacement pays more fees than its direct conflicts but not more
// than all conflicts (i.e. the direct conflicts have high-fee descendants). However, if the
// replacement doesn't pay more fees than its direct conflicts, then we can be sure it's not
// more economically rational to mine. Before we go digging through the mempool for all
// transactions that would need to be removed (direct conflicts and all descendants), check
// that the replacement transaction pays more than its direct conflicts.
if (const auto err_string{PaysMoreThanConflicts(setIterConflicting, newFeeRate, hash)}) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
}
// Calculate all conflicting entries and enforce BIP125 Rule #5.
if (const auto err_string{GetEntriesForConflicts(tx, m_pool, setIterConflicting, allConflicting)}) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
"too many potential replacements", *err_string);
}
// Enforce BIP125 Rule #2.
if (const auto err_string{HasNoNewUnconfirmed(tx, m_pool, setIterConflicting)}) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
"replacement-adds-unconfirmed", *err_string);
}
// Check if it's economically rational to mine this transaction rather than the ones it
// replaces and pays for its own relay fees. Enforce BIP125 Rules #3 and #4.
for (CTxMemPool::txiter it : allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
if (const auto err_string{PaysForRBF(nConflictingFees, nModifiedFees, nSize, ::incrementalRelayFee, hash)}) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
}
}
return true;
}
bool MemPoolAccept::PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
{
const CTransaction& tx = *ws.m_ptx;
TxValidationState& state = ws.m_state;
constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
// Check input scripts and signatures.
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, txdata)) {
// SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
// need to turn both off, and compare against just turning off CLEANSTACK
// to see if the failure is specifically due to witness validation.
TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
!CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
// Only the witness is missing, so the transaction itself may be fine.
state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
state.GetRejectReason(), state.GetDebugMessage());
}
return false; // state filled in by CheckInputScripts
}
return true;
}
bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
{
const CTransaction& tx = *ws.m_ptx;
const uint256& hash = ws.m_hash;
TxValidationState& state = ws.m_state;
const CChainParams& chainparams = args.m_chainparams;
// Check again against the current block tip's script verification
// flags to cache our script execution flags. This is, of course,
// useless if the next block has different script flags from the
// previous one, but because the cache tracks script flags for us it
// will auto-invalidate and we'll just have a few blocks of extra
// misses on soft-fork activation.
//
// This is also useful in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks (using TestBlockValidity), however allowing such
// transactions into the mempool can be exploited as a DoS attack.
unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(m_active_chainstate.m_chain.Tip(), chainparams.GetConsensus());
if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags, txdata, m_active_chainstate.CoinsTip())) {
return error("%s: BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s",
__func__, hash.ToString(), state.ToString());
}
return true;
}
bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
{
const CTransaction& tx = *ws.m_ptx;
const uint256& hash = ws.m_hash;
TxValidationState& state = ws.m_state;
const bool bypass_limits = args.m_bypass_limits;
CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
const CAmount& nModifiedFees = ws.m_modified_fees;
const CAmount& nConflictingFees = ws.m_conflicting_fees;
const size_t& nConflictingSize = ws.m_conflicting_size;
std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
// Remove conflicting transactions from the mempool
for (CTxMemPool::txiter it : allConflicting)
{
LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
it->GetTx().GetHash().ToString(),
hash.ToString(),
FormatMoney(nModifiedFees - nConflictingFees),
(int)entry->GetTxSize() - (int)nConflictingSize);
ws.m_replaced_transactions.push_back(it->GetSharedTx());
}
m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
// This transaction should only count for fee estimation if:
// - it's not being re-added during a reorg which bypasses typical mempool fee limits
// - the node is not behind
// - the transaction is not dependent on any other transactions in the mempool
bool validForFeeEstimation = !bypass_limits && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
// Store transaction in memory
m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
// trim mempool and check if tx was trimmed
if (!bypass_limits) {
LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
if (!m_pool.exists(hash))
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
}
return true;
}
MempoolAcceptResult MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
{
AssertLockHeld(cs_main);
LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
Workspace ws(ptx);
if (!PreChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
// Only compute the precomputed transaction data if we need to verify
// scripts (ie, other policy checks pass). We perform the inexpensive
// checks first and avoid hashing and signature verification unless those
// checks pass, to mitigate CPU exhaustion denial-of-service attacks.
PrecomputedTransactionData txdata;
if (!PolicyScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
if (!ConsensusScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
// Tx was accepted, but not added
if (args.m_test_accept) {
return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
}
if (!Finalize(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
}
PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
{
AssertLockHeld(cs_main);
// These context-free package limits can be done before taking the mempool lock.
PackageValidationState package_state;
if (!CheckPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
std::vector<Workspace> workspaces{};
workspaces.reserve(txns.size());
std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
[](const auto& tx) { return Workspace(tx); });
std::map<const uint256, const MempoolAcceptResult> results;
LOCK(m_pool.cs);
// Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
for (Workspace& ws : workspaces) {
if (!PreChecks(args, ws)) {
package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
// Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
return PackageMempoolAcceptResult(package_state, std::move(results));
}
// Make the coins created by this transaction available for subsequent transactions in the
// package to spend. Since we already checked conflicts in the package and we don't allow
// replacements, we don't need to track the coins spent. Note that this logic will need to be
// updated if package replace-by-fee is allowed in the future.
assert(!args.m_allow_bip125_replacement);
m_viewmempool.PackageAddTransaction(ws.m_ptx);
}
// Apply package mempool ancestor/descendant limits. Skip if there is only one transaction,
// because it's unnecessary. Also, CPFP carve out can increase the limit for individual
// transactions, but this exemption is not extended to packages in CheckPackageLimits().
std::string err_string;
if (txns.size() > 1 &&
!m_pool.CheckPackageLimits(txns, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants,
m_limit_descendant_size, err_string)) {
// All transactions must have individually passed mempool ancestor and descendant limits
// inside of PreChecks(), so this is separate from an individual transaction error.
package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-mempool-limits", err_string);
return PackageMempoolAcceptResult(package_state, std::move(results));
}
for (Workspace& ws : workspaces) {
PrecomputedTransactionData txdata;
if (!PolicyScriptChecks(args, ws, txdata)) {
// Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
return PackageMempoolAcceptResult(package_state, std::move(results));
}
if (args.m_test_accept) {
// When test_accept=true, transactions that pass PolicyScriptChecks are valid because there are
// no further mempool checks (passing PolicyScriptChecks implies passing ConsensusScriptChecks).
results.emplace(ws.m_ptx->GetWitnessHash(),
MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees));
}
}
return PackageMempoolAcceptResult(package_state, std::move(results));
}
} // anon namespace
/** (try to) add transaction to memory pool with a specified acceptance time **/
static MempoolAcceptResult AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool,
CChainState& active_chainstate,
const CTransactionRef &tx, int64_t nAcceptTime,
bool bypass_limits, bool test_accept)
EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
std::vector<COutPoint> coins_to_uncache;
MemPoolAccept::ATMPArgs args { chainparams, nAcceptTime, bypass_limits, coins_to_uncache,
test_accept, /* m_allow_bip125_replacement */ true };
const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransaction(tx, args);
if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
// Remove coins that were not present in the coins cache before calling
// AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
// number of invalid transactions that attempt to overrun the in-memory coins cache
// (`CCoinsViewCache::cacheCoins`).
for (const COutPoint& hashTx : coins_to_uncache)
active_chainstate.CoinsTip().Uncache(hashTx);
}
// After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
BlockValidationState state_dummy;
active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
return result;
}
MempoolAcceptResult AcceptToMemoryPool(CChainState& active_chainstate, CTxMemPool& pool, const CTransactionRef& tx,
bool bypass_limits, bool test_accept)
{
return AcceptToMemoryPoolWithTime(Params(), pool, active_chainstate, tx, GetTime(), bypass_limits, test_accept);
}
PackageMempoolAcceptResult ProcessNewPackage(CChainState& active_chainstate, CTxMemPool& pool,
const Package& package, bool test_accept)
{
AssertLockHeld(cs_main);
assert(test_accept); // Only allow package accept dry-runs (testmempoolaccept RPC).
assert(!package.empty());
assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
std::vector<COutPoint> coins_to_uncache;
const CChainParams& chainparams = Params();
MemPoolAccept::ATMPArgs args { chainparams, GetTime(), /* bypass_limits */ false, coins_to_uncache,
test_accept, /* m_allow_bip125_replacement */ false };
const PackageMempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactions(package, args);
// Uncache coins pertaining to transactions that were not submitted to the mempool.
for (const COutPoint& hashTx : coins_to_uncache) {
active_chainstate.CoinsTip().Uncache(hashTx);
}
return result;
}
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
{
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
CAmount nSubsidy = 50 * COIN;
// Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
nSubsidy >>= halvings;
return nSubsidy;
}
CoinsViews::CoinsViews(
std::string ldb_name,
size_t cache_size_bytes,
bool in_memory,
bool should_wipe) : m_dbview(
gArgs.GetDataDirNet() / ldb_name, cache_size_bytes, in_memory, should_wipe),
m_catcherview(&m_dbview) {}
void CoinsViews::InitCache()
{
m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
}
CChainState::CChainState(
CTxMemPool* mempool,
BlockManager& blockman,
ChainstateManager& chainman,
std::optional<uint256> from_snapshot_blockhash)
: m_mempool(mempool),
m_params(::Params()),
m_blockman(blockman),
m_chainman(chainman),
m_from_snapshot_blockhash(from_snapshot_blockhash) {}
void CChainState::InitCoinsDB(
size_t cache_size_bytes,
bool in_memory,
bool should_wipe,
std::string leveldb_name)
{
if (m_from_snapshot_blockhash) {
leveldb_name += "_" + m_from_snapshot_blockhash->ToString();
}
m_coins_views = std::make_unique<CoinsViews>(
leveldb_name, cache_size_bytes, in_memory, should_wipe);
}
void CChainState::InitCoinsCache(size_t cache_size_bytes)
{
assert(m_coins_views != nullptr);
m_coinstip_cache_size_bytes = cache_size_bytes;
m_coins_views->InitCache();
}
// Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
// is a performance-related implementation detail. This function must be marked
// `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
// can call it.
//
bool CChainState::IsInitialBlockDownload() const
{
// Optimization: pre-test latch before taking the lock.
if (m_cached_finished_ibd.load(std::memory_order_relaxed))
return false;
LOCK(cs_main);
if (m_cached_finished_ibd.load(std::memory_order_relaxed))
return false;
if (fImporting || fReindex)
return true;
if (m_chain.Tip() == nullptr)
return true;
if (m_chain.Tip()->nChainWork < nMinimumChainWork)
return true;
if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
return true;
LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
m_cached_finished_ibd.store(true, std::memory_order_relaxed);
return false;
}
static void AlertNotify(const std::string& strMessage)
{
uiInterface.NotifyAlertChanged();
#if HAVE_SYSTEM
std::string strCmd = gArgs.GetArg("-alertnotify", "");
if (strCmd.empty()) return;
// Alert text should be plain ascii coming from a trusted source, but to
// be safe we first strip anything not in safeChars, then add single quotes around
// the whole string before passing it to the shell:
std::string singleQuote("'");
std::string safeStatus = SanitizeString(strMessage);
safeStatus = singleQuote+safeStatus+singleQuote;
boost::replace_all(strCmd, "%s", safeStatus);
std::thread t(runCommand, strCmd);
t.detach(); // thread runs free
#endif
}
void CChainState::CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before finishing our initial sync)
if (IsInitialBlockDownload()) {
return;
}
if (pindexBestInvalid && pindexBestInvalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
SetfLargeWorkInvalidChainFound(true);
} else {
SetfLargeWorkInvalidChainFound(false);
}
}
// Called both upon regular invalid block discovery *and* InvalidateBlock
void CChainState::InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
if (pindexBestHeader != nullptr && pindexBestHeader->GetAncestor(pindexNew->nHeight) == pindexNew) {
pindexBestHeader = m_chain.Tip();
}
LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
CBlockIndex *tip = m_chain.Tip();
assert (tip);
LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
FormatISO8601DateTime(tip->GetBlockTime()));
CheckForkWarningConditions();
}
// Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
// which does its own setBlockIndexCandidates management.
void CChainState::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state)
{
if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
pindex->nStatus |= BLOCK_FAILED_VALID;
m_blockman.m_failed_blocks.insert(pindex);
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase()) {
txundo.vprevout.reserve(tx.vin.size());
for (const CTxIn &txin : tx.vin) {
txundo.vprevout.emplace_back();
bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
assert(is_spent);
}
}
// add outputs
AddCoins(inputs, tx, nHeight);
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
{
CTxUndo txundo;
UpdateCoins(tx, inputs, txundo, nHeight);
}
bool CScriptCheck::operator()() {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
}
int BlockManager::GetSpendHeight(const CCoinsViewCache& inputs)
{
AssertLockHeld(cs_main);
CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
return pindexPrev->nHeight + 1;
}
static CuckooCache::cache<uint256, SignatureCacheHasher> g_scriptExecutionCache;
static CSHA256 g_scriptExecutionCacheHasher;
void InitScriptExecutionCache() {
// Setup the salted hasher
uint256 nonce = GetRandHash();
// We want the nonce to be 64 bytes long to force the hasher to process
// this chunk, which makes later hash computations more efficient. We
// just write our 32-byte entropy twice to fill the 64 bytes.
g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
}
/**
* Check whether all of this transaction's input scripts succeed.
*
* This involves ECDSA signature checks so can be computationally intensive. This function should
* only be called after the cheap sanity checks in CheckTxInputs passed.
*
* If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
* script checks which are not necessary (eg due to script execution cache hits) are, obviously,
* not pushed onto pvChecks/run.
*
* Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
* which are matched. This is useful for checking blocks where we will likely never need the cache
* entry again.
*
* Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
* callers should probably reset it to CONSENSUS in such cases.
*
* Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
*/
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
std::vector<CScriptCheck>* pvChecks)
{
if (tx.IsCoinBase()) return true;
if (pvChecks) {
pvChecks->reserve(tx.vin.size());
}
// First check if script executions have been cached with the same
// flags. Note that this assumes that the inputs provided are
// correct (ie that the transaction hash which is in tx's prevouts
// properly commits to the scriptPubKey in the inputs view of that
// transaction).
uint256 hashCacheEntry;
CSHA256 hasher = g_scriptExecutionCacheHasher;
hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
return true;
}
if (!txdata.m_spent_outputs_ready) {
std::vector<CTxOut> spent_outputs;
spent_outputs.reserve(tx.vin.size());
for (const auto& txin : tx.vin) {
const COutPoint& prevout = txin.prevout;
const Coin& coin = inputs.AccessCoin(prevout);
assert(!coin.IsSpent());
spent_outputs.emplace_back(coin.out);
}
txdata.Init(tx, std::move(spent_outputs));
}
assert(txdata.m_spent_outputs.size() == tx.vin.size());
for (unsigned int i = 0; i < tx.vin.size(); i++) {
// We very carefully only pass in things to CScriptCheck which
// are clearly committed to by tx' witness hash. This provides
// a sanity check that our caching is not introducing consensus
// failures through additional data in, eg, the coins being
// spent being checked as a part of CScriptCheck.
// Verify signature
CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, ensure we return NOT_STANDARD
// instead of CONSENSUS to avoid downstream users
// splitting the network between upgraded and
// non-upgraded nodes by banning CONSENSUS-failing
// data providers.
CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
if (check2())
return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// MANDATORY flag failures correspond to
// TxValidationResult::TX_CONSENSUS. Because CONSENSUS
// failures are the most serious case of validation
// failures, we may need to consider using
// RECENT_CONSENSUS_CHANGE for any script failure that
// could be due to non-upgraded nodes which we may want to
// support, to avoid splitting the network (but this
// depends on the details of how net_processing handles
// such errors).
return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
if (cacheFullScriptStore && !pvChecks) {
// We executed all of the provided scripts, and were told to
// cache the result. Do so now.
g_scriptExecutionCache.insert(hashCacheEntry);
}
return true;
}
bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage)
{
AbortNode(strMessage, userMessage);
return state.Error(strMessage);
}
/**
* Restore the UTXO in a Coin at a given COutPoint
* @param undo The Coin to be restored.
* @param view The coins view to which to apply the changes.
* @param out The out point that corresponds to the tx input.
* @return A DisconnectResult as an int
*/
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
{
bool fClean = true;
if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
if (undo.nHeight == 0) {
// Missing undo metadata (height and coinbase). Older versions included this
// information only in undo records for the last spend of a transactions'
// outputs. This implies that it must be present for some other output of the same tx.
const Coin& alternate = AccessByTxid(view, out.hash);
if (!alternate.IsSpent()) {
undo.nHeight = alternate.nHeight;
undo.fCoinBase = alternate.fCoinBase;
} else {
return DISCONNECT_FAILED; // adding output for transaction without known metadata
}
}
// If the coin already exists as an unspent coin in the cache, then the
// possible_overwrite parameter to AddCoin must be set to true. We have
// already checked whether an unspent coin exists above using HaveCoin, so
// we don't need to guess. When fClean is false, an unspent coin already
// existed and it is an overwrite.
view.AddCoin(out, std::move(undo), !fClean);
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* When FAILED is returned, view is left in an indeterminate state. */
DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
{
bool fClean = true;
CBlockUndo blockUndo;
if (!UndoReadFromDisk(blockUndo, pindex)) {
error("DisconnectBlock(): failure reading undo data");
return DISCONNECT_FAILED;
}
if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
error("DisconnectBlock(): block and undo data inconsistent");
return DISCONNECT_FAILED;
}
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = *(block.vtx[i]);
uint256 hash = tx.GetHash();
bool is_coinbase = tx.IsCoinBase();
// Check that all outputs are available and match the outputs in the block itself
// exactly.
for (size_t o = 0; o < tx.vout.size(); o++) {
if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
COutPoint out(hash, o);
Coin coin;
bool is_spent = view.SpendCoin(out, &coin);
if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
fClean = false; // transaction output mismatch
}
}
}
// restore inputs
if (i > 0) { // not coinbases
CTxUndo &txundo = blockUndo.vtxundo[i-1];
if (txundo.vprevout.size() != tx.vin.size()) {
error("DisconnectBlock(): transaction and undo data inconsistent");
return DISCONNECT_FAILED;
}
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
fClean = fClean && res != DISCONNECT_UNCLEAN;
}
// At this point, all of txundo.vprevout should have been moved out.
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void StartScriptCheckWorkerThreads(int threads_num)
{
scriptcheckqueue.StartWorkerThreads(threads_num);
}
void StopScriptCheckWorkerThreads()
{
scriptcheckqueue.StopWorkerThreads();
}
/**
* Threshold condition checker that triggers when unknown versionbits are seen on the network.
*/
class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
{
private:
int bit;
public:
explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
{
return pindex->nHeight >= params.MinBIP9WarningHeight &&
((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
((pindex->nVersion >> bit) & 1) != 0 &&
((g_versionbitscache.ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
}
};
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main);
static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams)
{
unsigned int flags = SCRIPT_VERIFY_NONE;
// BIP16 didn't become active until Apr 1 2012 (on mainnet, and
// retroactively applied to testnet)
// However, only one historical block violated the P2SH rules (on both
// mainnet and testnet), so for simplicity, always leave P2SH
// on except for the one violating block.
if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
*pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
{
// Enforce WITNESS rules whenever P2SH is in effect
flags |= SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS;
}
// Enforce the DERSIG (BIP66) rule
if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_DERSIG)) {
flags |= SCRIPT_VERIFY_DERSIG;
}
// Enforce CHECKLOCKTIMEVERIFY (BIP65)
if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CLTV)) {
flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
}
// Enforce CHECKSEQUENCEVERIFY (BIP112)
if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CSV)) {
flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
}
// Enforce Taproot (BIP340-BIP342)
if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_TAPROOT)) {
flags |= SCRIPT_VERIFY_TAPROOT;
}
// Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_SEGWIT)) {
flags |= SCRIPT_VERIFY_NULLDUMMY;
}
return flags;
}
static int64_t nTimeCheck = 0;
static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeTotal = 0;
static int64_t nBlocksTotal = 0;
/** Apply the effects of this block (with given index) on the UTXO set represented by coins.
* Validity checks that depend on the UTXO set are also done; ConnectBlock()
* can fail if those validity checks fail (among other reasons). */
bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
CCoinsViewCache& view, bool fJustCheck)
{
AssertLockHeld(cs_main);
assert(pindex);
assert(*pindex->phashBlock == block.GetHash());
int64_t nTimeStart = GetTimeMicros();
// Check it again in case a previous version let a bad block in
// NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
// ContextualCheckBlockHeader() here. This means that if we add a new
// consensus rule that is enforced in one of those two functions, then we
// may have let in a block that violates the rule prior to updating the
// software, and we would NOT be enforcing the rule here. Fully solving
// upgrade from one software version to the next after a consensus rule
// change is potentially tricky and issue-specific (see NeedsRedownload()
// for one approach that was used for BIP 141 deployment).
// Also, currently the rule against blocks more than 2 hours in the future
// is enforced in ContextualCheckBlockHeader(); we wouldn't want to
// re-enforce that rule here (at least until we make it impossible for
// GetAdjustedTime() to go backward).
if (!CheckBlock(block, state, m_params.GetConsensus(), !fJustCheck, !fJustCheck)) {
if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
// We don't write down blocks to disk if they may have been
// corrupted, so this should be impossible unless we're having hardware
// problems.
return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
}
return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
}
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
assert(hashPrevBlock == view.GetBestBlock());
nBlocksTotal++;
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (block.GetHash() == m_params.GetConsensus().hashGenesisBlock) {
if (!fJustCheck)
view.SetBestBlock(pindex->GetBlockHash());
return true;
}
bool fScriptChecks = true;
if (!hashAssumeValid.IsNull()) {
// We've been configured with the hash of a block which has been externally verified to have a valid history.
// A suitable default value is included with the software and updated from time to time. Because validity
// relative to a piece of software is an objective fact these defaults can be easily reviewed.
// This setting doesn't force the selection of any particular chain but makes validating some faster by
// effectively caching the result of part of the verification.
BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
if (it != m_blockman.m_block_index.end()) {
if (it->second->GetAncestor(pindex->nHeight) == pindex &&
pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
pindexBestHeader->nChainWork >= nMinimumChainWork) {
// This block is a member of the assumed verified chain and an ancestor of the best header.
// Script verification is skipped when connecting blocks under the
// assumevalid block. Assuming the assumevalid block is valid this
// is safe because block merkle hashes are still computed and checked,
// Of course, if an assumed valid block is invalid due to false scriptSigs
// this optimization would allow an invalid chain to be accepted.
// The equivalent time check discourages hash power from extorting the network via DOS attack
// into accepting an invalid block through telling users they must manually set assumevalid.
// Requiring a software change or burying the invalid block, regardless of the setting, makes
// it hard to hide the implication of the demand. This also avoids having release candidates
// that are hardly doing any signature verification at all in testing without having to
// artificially set the default assumed verified block further back.
// The test against nMinimumChainWork prevents the skipping when denied access to any chain at
// least as good as the expected chain.
fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_params.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
}
}
}
int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes during their
// initial block download.
bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
(pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
// Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
// with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
// time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
// before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
// duplicate transactions descending from the known pairs either.
// If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
// BIP34 requires that a block at height X (block X) has its coinbase
// scriptSig start with a CScriptNum of X (indicated height X). The above
// logic of no longer requiring BIP30 once BIP34 activates is flawed in the
// case that there is a block X before the BIP34 height of 227,931 which has
// an indicated height Y where Y is greater than X. The coinbase for block
// X would also be a valid coinbase for block Y, which could be a BIP30
// violation. An exhaustive search of all mainnet coinbases before the
// BIP34 height which have an indicated height greater than the block height
// reveals many occurrences. The 3 lowest indicated heights found are
// 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
// heights would be the first opportunity for BIP30 to be violated.
// The search reveals a great many blocks which have an indicated height
// greater than 1,983,702, so we simply remove the optimization to skip
// BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
// that block in another 25 years or so, we should take advantage of a
// future consensus change to do a new and improved version of BIP34 that
// will actually prevent ever creating any duplicate coinbases in the
// future.
static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
// There is no potential to create a duplicate coinbase at block 209,921
// because this is still before the BIP34 height and so explicit BIP30
// checking is still active.
// The final case is block 176,684 which has an indicated height of
// 490,897. Unfortunately, this issue was not discovered until about 2 weeks
// before block 490,897 so there was not much opportunity to address this
// case other than to carefully analyze it and determine it would not be a
// problem. Block 490,897 was, in fact, mined with a different coinbase than
// block 176,684, but it is important to note that even if it hadn't been or
// is remined on an alternate fork with a duplicate coinbase, we would still
// not run into a BIP30 violation. This is because the coinbase for 176,684
// is spent in block 185,956 in transaction
// d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
// spending transaction can't be duplicated because it also spends coinbase
// 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
// coinbase has an indicated height of over 4.2 billion, and wouldn't be
// duplicatable until that height, and it's currently impossible to create a
// chain that long. Nevertheless we may wish to consider a future soft fork
// which retroactively prevents block 490,897 from creating a duplicate
// coinbase. The two historical BIP30 violations often provide a confusing
// edge case when manipulating the UTXO and it would be simpler not to have
// another edge case to deal with.
// testnet3 has no blocks before the BIP34 height with indicated heights
// post BIP34 before approximately height 486,000,000 and presumably will
// be reset before it reaches block 1,983,702 and starts doing unnecessary
// BIP30 checking again.
assert(pindex->pprev);
CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(m_params.GetConsensus().BIP34Height);
//Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == m_params.GetConsensus().BIP34Hash));
// TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
// consensus change that ensures coinbases at those heights can not
// duplicate earlier coinbases.
if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
for (const auto& tx : block.vtx) {
for (size_t o = 0; o < tx->vout.size(); o++) {
if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
}
}
}
}
// Enforce BIP68 (sequence locks)
int nLockTimeFlags = 0;
if (DeploymentActiveAt(*pindex, m_params.GetConsensus(), Consensus::DEPLOYMENT_CSV)) {
nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
}
// Get the script flags for this block
unsigned int flags = GetBlockScriptFlags(pindex, m_params.GetConsensus());
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
CBlockUndo blockundo;
// Precomputed transaction data pointers must not be invalidated
// until after `control` has run the script checks (potentially
// in multiple threads). Preallocate the vector size so a new allocation
// doesn't invalidate pointers into the vector, and keep txsdata in scope
// for as long as `control`.
CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
std::vector<int> prevheights;
CAmount nFees = 0;
int nInputs = 0;
int64_t nSigOpsCost = 0;
blockundo.vtxundo.reserve(block.vtx.size() - 1);
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const CTransaction &tx = *(block.vtx[i]);
nInputs += tx.vin.size();
if (!tx.IsCoinBase())
{
CAmount txfee = 0;
TxValidationState tx_state;
if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
// Any transaction validation failure in ConnectBlock is a block consensus failure
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
tx_state.GetRejectReason(), tx_state.GetDebugMessage());
return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
}
nFees += txfee;
if (!MoneyRange(nFees)) {
LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
}
// Check that transaction is BIP68 final
// BIP68 lock checks (as opposed to nLockTime checks) must
// be in ConnectBlock because they require the UTXO set
prevheights.resize(tx.vin.size());
for (size_t j = 0; j < tx.vin.size(); j++) {
prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
}
if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
}
}
// GetTransactionSigOpCost counts 3 types of sigops:
// * legacy (always)
// * p2sh (when P2SH enabled in flags and excludes coinbase)
// * witness (when witness enabled in flags and excludes coinbase)
nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
}
if (!tx.IsCoinBase())
{
std::vector<CScriptCheck> vChecks;
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
TxValidationState tx_state;
if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
// Any transaction validation failure in ConnectBlock is a block consensus failure
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
tx_state.GetRejectReason(), tx_state.GetDebugMessage());
return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
tx.GetHash().ToString(), state.ToString());
}
control.Add(vChecks);
}
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
}
int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, m_params.GetConsensus());
if (block.vtx[0]->GetValueOut() > blockReward) {
LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
}
if (!control.Wait()) {
LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
}
int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
if (fJustCheck)
return true;
if (!WriteUndoDataForBlock(blockundo, state, pindex, m_params)) {
return false;
}
if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
assert(pindex->phashBlock);
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
TRACE6(validation, block_connected,
block.GetHash().data(),
pindex->nHeight,
block.vtx.size(),
nInputs,
nSigOpsCost,
GetTimeMicros() - nTimeStart // in microseconds (µs)
);
return true;
}
CoinsCacheSizeState CChainState::GetCoinsCacheSizeState()
{
return this->GetCoinsCacheSizeState(
m_coinstip_cache_size_bytes,
gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
}
CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
size_t max_coins_cache_size_bytes,
size_t max_mempool_size_bytes)
{
const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
int64_t nTotalSpace =
max_coins_cache_size_bytes + std::max<int64_t>(max_mempool_size_bytes - nMempoolUsage, 0);
//! No need to periodic flush if at least this much space still available.
static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024; // 10MB
int64_t large_threshold =
std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
if (cacheSize > nTotalSpace) {
LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
return CoinsCacheSizeState::CRITICAL;
} else if (cacheSize > large_threshold) {
return CoinsCacheSizeState::LARGE;
}
return CoinsCacheSizeState::OK;
}
bool CChainState::FlushStateToDisk(
BlockValidationState &state,
FlushStateMode mode,
int nManualPruneHeight)
{
LOCK(cs_main);
assert(this->CanFlushToDisk());
static std::chrono::microseconds nLastWrite{0};
static std::chrono::microseconds nLastFlush{0};
std::set<int> setFilesToPrune;
bool full_flush_completed = false;
const size_t coins_count = CoinsTip().GetCacheSize();
const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
try {
{
bool fFlushForPrune = false;
bool fDoFullFlush = false;
CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
LOCK(cs_LastBlockFile);
if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
// make sure we don't prune above the blockfilterindexes bestblocks
// pruning is height-based
int last_prune = m_chain.Height(); // last height we can prune
ForEachBlockFilterIndex([&](BlockFilterIndex& index) {
last_prune = std::max(1, std::min(last_prune, index.GetSummary().best_block_height));
});
if (nManualPruneHeight > 0) {
LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
} else {
LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
m_blockman.FindFilesToPrune(setFilesToPrune, m_params.PruneAfterHeight(), m_chain.Height(), last_prune, IsInitialBlockDownload());
fCheckForPruning = false;
}
if (!setFilesToPrune.empty()) {
fFlushForPrune = true;
if (!fHavePruned) {
m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
fHavePruned = true;
}
}
}
const auto nNow = GetTime<std::chrono::microseconds>();
// Avoid writing/flushing immediately after startup.
if (nLastWrite.count() == 0) {
nLastWrite = nNow;
}
if (nLastFlush.count() == 0) {
nLastFlush = nNow;
}
// The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
// The cache is over the limit, we have to write now.
bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
// Combine all conditions that result in a full cache flush.
fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
// Write blocks and block index to disk.
if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index
if (!CheckDiskSpace(gArgs.GetBlocksDirPath())) {
return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
}
{
LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
}
// Then update all block file information (which may refer to block and undo files).
{
LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
vFiles.reserve(setDirtyFileInfo.size());
for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
setDirtyFileInfo.erase(it++);
}
std::vector<const CBlockIndex*> vBlocks;
vBlocks.reserve(setDirtyBlockIndex.size());
for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
vBlocks.push_back(*it);
setDirtyBlockIndex.erase(it++);
}
if (!m_blockman.m_block_tree_db->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
return AbortNode(state, "Failed to write to block index database");
}
}
// Finally remove any pruned files
if (fFlushForPrune) {
LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
UnlinkPrunedFiles(setFilesToPrune);
}
nLastWrite = nNow;
}
// Flush best chain related state. This can only be done if the blocks / block index write was also done.
if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
LOG_TIME_MILLIS_WITH_CATEGORY(strprintf("write coins cache to disk (%d coins, %.2fkB)",
coins_count, coins_mem_usage / 1000), BCLog::BENCH);
// Typical Coin structures on disk are around 48 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(gArgs.GetDataDirNet(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
}
// Flush the chainstate (which may refer to block index entries).
if (!CoinsTip().Flush())
return AbortNode(state, "Failed to write to coin database");
nLastFlush = nNow;
full_flush_completed = true;
}
}
if (full_flush_completed) {
// Update best block in wallet (so we can detect restored wallets).
GetMainSignals().ChainStateFlushed(m_chain.GetLocator());
}
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error while flushing: ") + e.what());
}
return true;
}
void CChainState::ForceFlushStateToDisk()
{
BlockValidationState state;
if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
}
}
void CChainState::PruneAndFlush()
{
BlockValidationState state;
fCheckForPruning = true;
if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
}
}
static void DoWarning(const bilingual_str& warning)
{
static bool fWarned = false;
SetMiscWarning(warning);
if (!fWarned) {
AlertNotify(warning.original);
fWarned = true;
}
}
/** Private helper function that concatenates warning messages. */
static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
{
if (!res.empty()) res += Untranslated(", ");
res += warn;
}
static void UpdateTipLog(
const CCoinsViewCache& coins_tip,
const CBlockIndex* tip,
const CChainParams& params,
const std::string& func_name,
const std::string& prefix,
const std::string& warning_messages) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
{
AssertLockHeld(::cs_main);
LogPrintf("%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
prefix, func_name,
tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
log(tip->nChainWork.getdouble()) / log(2.0), (unsigned long)tip->nChainTx,
FormatISO8601DateTime(tip->GetBlockTime()),
GuessVerificationProgress(params.TxData(), tip),
coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
coins_tip.GetCacheSize(),
!warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
}
void CChainState::UpdateTip(const CBlockIndex* pindexNew)
{
const auto& coins_tip = this->CoinsTip();
// The remainder of the function isn't relevant if we are not acting on
// the active chainstate, so return if need be.
if (this != &m_chainman.ActiveChainstate()) {
// Only log every so often so that we don't bury log messages at the tip.
constexpr int BACKGROUND_LOG_INTERVAL = 2000;
if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "[background validation] ", "");
}
return;
}
// New best block
if (m_mempool) {
m_mempool->AddTransactionsUpdated(1);
}
{
LOCK(g_best_block_mutex);
g_best_block = pindexNew->GetBlockHash();
g_best_block_cv.notify_all();
}
bilingual_str warning_messages;
if (!this->IsInitialBlockDownload()) {
const CBlockIndex* pindex = pindexNew;
for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
WarningBitsConditionChecker checker(bit);
ThresholdState state = checker.GetStateFor(pindex, m_params.GetConsensus(), warningcache[bit]);
if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
if (state == ThresholdState::ACTIVE) {
DoWarning(warning);
} else {
AppendWarning(warning_messages, warning);
}
}
}
}
UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "", warning_messages.original);
}
/** Disconnect m_chain's tip.
* After calling, the mempool will be in an inconsistent state, with
* transactions from disconnected blocks being added to disconnectpool. You
* should make the mempool consistent again by calling MaybeUpdateMempoolForReorg.
* with cs_main held.
*
* If disconnectpool is nullptr, then no disconnected transactions are added to
* disconnectpool (note that the caller is responsible for mempool consistency
* in any case).
*/
bool CChainState::DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool)
{
AssertLockHeld(cs_main);
if (m_mempool) AssertLockHeld(m_mempool->cs);
CBlockIndex *pindexDelete = m_chain.Tip();
assert(pindexDelete);
// Read block from disk.
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
if (!ReadBlockFromDisk(block, pindexDelete, m_params.GetConsensus())) {
return error("DisconnectTip(): Failed to read block");
}
// Apply the block atomically to the chain state.
int64_t nStart = GetTimeMicros();
{
CCoinsViewCache view(&CoinsTip());
assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
bool flushed = view.Flush();
assert(flushed);
}
LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
return false;
}
if (disconnectpool && m_mempool) {
// Save transactions to re-add to mempool at end of reorg
for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
disconnectpool->addTransaction(*it);
}
while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
// Drop the earliest entry, and remove its children from the mempool.
auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
disconnectpool->removeEntry(it);
}
}
m_chain.SetTip(pindexDelete->pprev);
UpdateTip(pindexDelete->pprev);
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
GetMainSignals().BlockDisconnected(pblock, pindexDelete);
return true;
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
struct PerBlockConnectTrace {
CBlockIndex* pindex = nullptr;
std::shared_ptr<const CBlock> pblock;
PerBlockConnectTrace() {}
};
/**
* Used to track blocks whose transactions were applied to the UTXO state as a
* part of a single ActivateBestChainStep call.
*
* This class is single-use, once you call GetBlocksConnected() you have to throw
* it away and make a new one.
*/
class ConnectTrace {
private:
std::vector<PerBlockConnectTrace> blocksConnected;
public:
explicit ConnectTrace() : blocksConnected(1) {}
void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
assert(!blocksConnected.back().pindex);
assert(pindex);
assert(pblock);
blocksConnected.back().pindex = pindex;
blocksConnected.back().pblock = std::move(pblock);
blocksConnected.emplace_back();
}
std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
// We always keep one extra block at the end of our list because
// blocks are added after all the conflicted transactions have
// been filled in. Thus, the last entry should always be an empty
// one waiting for the transactions from the next block. We pop
// the last entry here to make sure the list we return is sane.
assert(!blocksConnected.back().pindex);
blocksConnected.pop_back();
return blocksConnected;
}
};
/**
* Connect a new block to m_chain. pblock is either nullptr or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*
* The block is added to connectTrace if connection succeeds.
*/
bool CChainState::ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool)
{
AssertLockHeld(cs_main);
if (m_mempool) AssertLockHeld(m_mempool->cs);
assert(pindexNew->pprev == m_chain.Tip());
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
std::shared_ptr<const CBlock> pthisBlock;
if (!pblock) {
std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
if (!ReadBlockFromDisk(*pblockNew, pindexNew, m_params.GetConsensus())) {
return AbortNode(state, "Failed to read block");
}
pthisBlock = pblockNew;
} else {
pthisBlock = pblock;
}
const CBlock& blockConnecting = *pthisBlock;
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
{
CCoinsViewCache view(&CoinsTip());
bool rv = ConnectBlock(blockConnecting, state, pindexNew, view);
GetMainSignals().BlockChecked(blockConnecting, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
}
nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
assert(nBlocksTotal > 0);
LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
bool flushed = view.Flush();
assert(flushed);
}
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
return false;
}
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
// Remove conflicting transactions from the mempool.;
if (m_mempool) {
m_mempool->removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
disconnectpool.removeForBlock(blockConnecting.vtx);
}
// Update m_chain & related variables.
m_chain.SetTip(pindexNew);
UpdateTip(pindexNew);
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/
CBlockIndex* CChainState::FindMostWorkChain() {
do {
CBlockIndex *pindexNew = nullptr;
// Find the best candidate header.
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return nullptr;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid.
// Just going until the active chain is an optimization, as we know all blocks in it are valid already.
CBlockIndex *pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !m_chain.Contains(pindexTest)) {
assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for
// which block files have been deleted. Remove those as candidates
// for the most work chain if we come across them; we can't switch
// to a chain unless we have all the non-active-chain parent blocks.
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew;
// Remove the entire chain from the set.
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to m_blocks_unlinked,
// so that if the block arrives in the future we can try adding
// to setBlockIndexCandidates again.
m_blockman.m_blocks_unlinked.insert(
std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while(true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
void CChainState::PruneBlockIndexCandidates() {
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails.
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
setBlockIndexCandidates.erase(it++);
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty());
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
*
* @returns true unless a system error occurred
*/
bool CChainState::ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
{
AssertLockHeld(cs_main);
if (m_mempool) AssertLockHeld(m_mempool->cs);
const CBlockIndex* pindexOldTip = m_chain.Tip();
const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain.
bool fBlocksDisconnected = false;
DisconnectedBlockTransactions disconnectpool;
while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
if (!DisconnectTip(state, &disconnectpool)) {
// This is likely a fatal error, but keep the mempool consistent,
// just in case. Only remove from the mempool in this case.
MaybeUpdateMempoolForReorg(disconnectpool, false);
// If we're unable to disconnect a block during normal operation,
// then that is a failure of our local system -- we should abort
// rather than stay on a less work chain.
AbortNode(state, "Failed to disconnect block; see debug.log for details");
return false;
}
fBlocksDisconnected = true;
}
// Build list of new blocks to connect (in descending height order).
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
for (CBlockIndex* pindexConnect : reverse_iterate(vpindexToConnect)) {
if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
InvalidChainFound(vpindexToConnect.front());
}
state = BlockValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else {
// A system error occurred (disk space, database error, ...).
// Make the mempool consistent with the current tip, just in case
// any observers try to use it before shutdown.
MaybeUpdateMempoolForReorg(disconnectpool, false);
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock.
fContinue = false;
break;
}
}
}
}
if (fBlocksDisconnected) {
// If any blocks were disconnected, disconnectpool may be non empty. Add
// any disconnected transactions back to the mempool.
MaybeUpdateMempoolForReorg(disconnectpool, true);
}
if (m_mempool) m_mempool->check(*this);
CheckForkWarningConditions();
return true;
}
static SynchronizationState GetSynchronizationState(bool init)
{
if (!init) return SynchronizationState::POST_INIT;
if (::fReindex) return SynchronizationState::INIT_REINDEX;
return SynchronizationState::INIT_DOWNLOAD;
}
static bool NotifyHeaderTip(CChainState& chainstate) LOCKS_EXCLUDED(cs_main) {
bool fNotify = false;
bool fInitialBlockDownload = false;
static CBlockIndex* pindexHeaderOld = nullptr;
CBlockIndex* pindexHeader = nullptr;
{
LOCK(cs_main);
pindexHeader = pindexBestHeader;
if (pindexHeader != pindexHeaderOld) {
fNotify = true;
fInitialBlockDownload = chainstate.IsInitialBlockDownload();
pindexHeaderOld = pindexHeader;
}
}
// Send block tip changed notifications without cs_main
if (fNotify) {
uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
}
return fNotify;
}
static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main) {
AssertLockNotHeld(cs_main);
if (GetMainSignals().CallbacksPending() > 10) {
SyncWithValidationInterfaceQueue();
}
}
bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
{
// Note that while we're often called here from ProcessNewBlock, this is
// far from a guarantee. Things in the P2P/RPC will often end up calling
// us in the middle of ProcessNewBlock - do not assume pblock is set
// sanely for performance or correctness!
AssertLockNotHeld(cs_main);
// ABC maintains a fair degree of expensive-to-calculate internal state
// because this function periodically releases cs_main so that it does not lock up other threads for too long
// during large connects - and to allow for e.g. the callback queue to drain
// we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
LOCK(m_cs_chainstate);
CBlockIndex *pindexMostWork = nullptr;
CBlockIndex *pindexNewTip = nullptr;
int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT);
do {
// Block until the validation queue drains. This should largely
// never happen in normal operation, however may happen during
// reindex, causing memory blowup if we run too far ahead.
// Note that if a validationinterface callback ends up calling
// ActivateBestChain this may lead to a deadlock! We should
// probably have a DEBUG_LOCKORDER test for this in the future.
LimitValidationInterfaceQueue();
{
LOCK(cs_main);
// Lock transaction pool for at least as long as it takes for connectTrace to be consumed
LOCK(MempoolMutex());
CBlockIndex* starting_tip = m_chain.Tip();
bool blocks_connected = false;
do {
// We absolutely may not unlock cs_main until we've made forward progress
// (with the exception of shutdown due to hardware issues, low disk space, etc).
ConnectTrace connectTrace; // Destructed before cs_main is unlocked
if (pindexMostWork == nullptr) {
pindexMostWork = FindMostWorkChain();
}
// Whether we have anything to do at all.
if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
break;
}
bool fInvalidFound = false;
std::shared_ptr<const CBlock> nullBlockPtr;
if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
// A system error occurred
return false;
}
blocks_connected = true;
if (fInvalidFound) {
// Wipe cache, we may need another branch now.
pindexMostWork = nullptr;
}
pindexNewTip = m_chain.Tip();
for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
assert(trace.pblock && trace.pindex);
GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
}
} while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
if (!blocks_connected) return true;
const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
bool fInitialDownload = IsInitialBlockDownload();
// Notify external listeners about the new tip.
// Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
if (pindexFork != pindexNewTip) {
// Notify ValidationInterface subscribers
GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
// Always notify the UI if a new block tip was connected
uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
}
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
// We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
// never shutdown before connecting the genesis block during LoadChainTip(). Previously this
// caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
// that the best block hash is non-null.
if (ShutdownRequested()) break;
} while (pindexNewTip != pindexMostWork);
CheckBlockIndex();
// Write changes periodically to disk, after relay.
if (!FlushStateToDisk(state, FlushStateMode::PERIODIC)) {
return false;
}
return true;
}
bool CChainState::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
{
{
LOCK(cs_main);
if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
// Nothing to do, this block is not at the tip.
return true;
}
if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) {
// The chain has been extended since the last call, reset the counter.
nBlockReverseSequenceId = -1;
}
nLastPreciousChainwork = m_chain.Tip()->nChainWork;
setBlockIndexCandidates.erase(pindex);
pindex->nSequenceId = nBlockReverseSequenceId;
if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
// We can't keep reducing the counter if somebody really wants to
// call preciousblock 2**31-1 times on the same set of tips...
nBlockReverseSequenceId--;
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
setBlockIndexCandidates.insert(pindex);
PruneBlockIndexCandidates();
}
}
return ActivateBestChain(state, std::shared_ptr<const CBlock>());
}
bool CChainState::InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
{
// Genesis block can't be invalidated
assert(pindex);
if (pindex->nHeight == 0) return false;
CBlockIndex* to_mark_failed = pindex;
bool pindex_was_in_chain = false;
int disconnected = 0;
// We do not allow ActivateBestChain() to run while InvalidateBlock() is
// running, as that could cause the tip to change while we disconnect
// blocks.
LOCK(m_cs_chainstate);
// We'll be acquiring and releasing cs_main below, to allow the validation
// callbacks to run. However, we should keep the block index in a
// consistent state as we disconnect blocks -- in particular we need to
// add equal-work blocks to setBlockIndexCandidates as we disconnect.
// To avoid walking the block index repeatedly in search of candidates,
// build a map once so that we can look up candidate blocks by chain
// work as we go.
std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
{
LOCK(cs_main);
for (const auto& entry : m_blockman.m_block_index) {
CBlockIndex *candidate = entry.second;
// We don't need to put anything in our active chain into the
// multimap, because those candidates will be found and considered
// as we disconnect.
// Instead, consider only non-active-chain blocks that have at
// least as much work as where we expect the new tip to end up.
if (!m_chain.Contains(candidate) &&
!CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
candidate->HaveTxsDownloaded()) {
candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
}
}
}
// Disconnect (descendants of) pindex, and mark them invalid.
while (true) {
if (ShutdownRequested()) break;
// Make sure the queue of validation callbacks doesn't grow unboundedly.
LimitValidationInterfaceQueue();
LOCK(cs_main);
// Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
// called after DisconnectTip without unlocking in between
LOCK(MempoolMutex());
if (!m_chain.Contains(pindex)) break;
pindex_was_in_chain = true;
CBlockIndex *invalid_walk_tip = m_chain.Tip();
// ActivateBestChain considers blocks already in m_chain
// unconditionally valid already, so force disconnect away from it.
DisconnectedBlockTransactions disconnectpool;
bool ret = DisconnectTip(state, &disconnectpool);
// DisconnectTip will add transactions to disconnectpool.
// Adjust the mempool to be consistent with the new tip, adding
// transactions back to the mempool if disconnecting was successful,
// and we're not doing a very deep invalidation (in which case
// keeping the mempool up to date is probably futile anyway).
MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
if (!ret) return false;
assert(invalid_walk_tip->pprev == m_chain.Tip());
// We immediately mark the disconnected blocks as invalid.
// This prevents a case where pruned nodes may fail to invalidateblock
// and be left unable to start as they have no tip candidates (as there
// are no blocks that meet the "have data and are not invalid per
// nStatus" criteria for inclusion in setBlockIndexCandidates).
invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(invalid_walk_tip);
setBlockIndexCandidates.erase(invalid_walk_tip);
setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
// We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
// need to be BLOCK_FAILED_CHILD instead.
to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(to_mark_failed);
}
// Add any equal or more work headers to setBlockIndexCandidates
auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
while (candidate_it != candidate_blocks_by_work.end()) {
if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
setBlockIndexCandidates.insert(candidate_it->second);
candidate_it = candidate_blocks_by_work.erase(candidate_it);
} else {
++candidate_it;
}
}
// Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
// iterations, or, if it's the last one, call InvalidChainFound on it.
to_mark_failed = invalid_walk_tip;
}
CheckBlockIndex();
{
LOCK(cs_main);
if (m_chain.Contains(to_mark_failed)) {
// If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
return false;
}
// Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(to_mark_failed);
setBlockIndexCandidates.erase(to_mark_failed);
m_blockman.m_failed_blocks.insert(to_mark_failed);
// If any new blocks somehow arrived while we were disconnecting
// (above), then the pre-calculation of what should go into
// setBlockIndexCandidates may have missed entries. This would
// technically be an inconsistency in the block index, but if we clean
// it up here, this should be an essentially unobservable error.
// Loop back over all block index entries and add any missing entries
// to setBlockIndexCandidates.
BlockMap::iterator it = m_blockman.m_block_index.begin();
while (it != m_blockman.m_block_index.end()) {
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
setBlockIndexCandidates.insert(it->second);
}
it++;
}
InvalidChainFound(to_mark_failed);
}
// Only notify about a new block tip if the active chain was modified.
if (pindex_was_in_chain) {
uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
}
return true;
}
void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
AssertLockHeld(cs_main);
int nHeight = pindex->nHeight;
// Remove the invalidity flag from this block and all its descendants.
BlockMap::iterator it = m_blockman.m_block_index.begin();
while (it != m_blockman.m_block_index.end()) {
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
it->second->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(it->second);
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
setBlockIndexCandidates.insert(it->second);
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = nullptr;
}
m_blockman.m_failed_blocks.erase(it->second);
}
it++;
}
// Remove the invalidity flag from all ancestors too.
while (pindex != nullptr) {
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex);
m_blockman.m_failed_blocks.erase(pindex);
}
pindex = pindex->pprev;
}
}
CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = m_block_index.find(hash);
if (it != m_block_index.end())
return it->second;
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block);
// We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage.
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
if (miPrev != m_block_index.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
pindexNew->BuildSkip();
}
pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew;
setDirtyBlockIndex.insert(pindexNew);
return pindexNew;
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
{
pindexNew->nTx = block.vtx.size();
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA;
if (DeploymentActiveAt(*pindexNew, m_params.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
pindexNew->nStatus |= BLOCK_OPT_WITNESS;
}
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
std::deque<CBlockIndex*> queue;
queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected.
while (!queue.empty()) {
CBlockIndex *pindex = queue.front();
queue.pop_front();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
pindex->nSequenceId = nBlockSequenceId++;
if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
setBlockIndexCandidates.insert(pindex);
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
while (range.first != range.second) {
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second);
range.first++;
m_blockman.m_blocks_unlinked.erase(it);
}
}
} else {
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
}
}
}
static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
return true;
}
bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
{
// These are checks that are independent of context.
if (block.fChecked)
return true;
// Check that the header is valid (particularly PoW). This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
return false;
// Signet only: check block solution
if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
}
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
// Note that witness malleability is checked in ContextualCheckBlock, so no
// checks that use witness data may be performed here.
// Size limits
if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i]->IsCoinBase())
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
// Check transactions
// Must check for duplicate inputs (see CVE-2018-17144)
for (const auto& tx : block.vtx) {
TxValidationState tx_state;
if (!CheckTransaction(*tx, tx_state)) {
// CheckBlock() does context-free validation checks. The only
// possible failures are consensus failures.
assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
}
}
unsigned int nSigOps = 0;
for (const auto& tx : block.vtx)
{
nSigOps += GetLegacySigOpCount(*tx);
}
if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
if (fCheckPOW && fCheckMerkleRoot)
block.fChecked = true;
return true;
}
void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
{
int commitpos = GetWitnessCommitmentIndex(block);
static const std::vector<unsigned char> nonce(32, 0x00);
if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
CMutableTransaction tx(*block.vtx[0]);
tx.vin[0].scriptWitness.stack.resize(1);
tx.vin[0].scriptWitness.stack[0] = nonce;
block.vtx[0] = MakeTransactionRef(std::move(tx));
}
}
std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
{
std::vector<unsigned char> commitment;
int commitpos = GetWitnessCommitmentIndex(block);
std::vector<unsigned char> ret(32, 0x00);
if (commitpos == NO_WITNESS_COMMITMENT) {
uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
CTxOut out;
out.nValue = 0;
out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
out.scriptPubKey[0] = OP_RETURN;
out.scriptPubKey[1] = 0x24;
out.scriptPubKey[2] = 0xaa;
out.scriptPubKey[3] = 0x21;
out.scriptPubKey[4] = 0xa9;
out.scriptPubKey[5] = 0xed;
memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
CMutableTransaction tx(*block.vtx[0]);
tx.vout.push_back(out);
block.vtx[0] = MakeTransactionRef(std::move(tx));
}
UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
return commitment;
}
CBlockIndex* BlockManager::GetLastCheckpoint(const CCheckpointData& data)
{
const MapCheckpoints& checkpoints = data.mapCheckpoints;
for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
{
const uint256& hash = i.second;
CBlockIndex* pindex = LookupBlockIndex(hash);
if (pindex) {
return pindex;
}
}
return nullptr;
}
/** Context-dependent validity checks.
* By "context", we mean only the previous block headers, but not the UTXO
* set; UTXO-related validity checks are done in ConnectBlock().
* NOTE: This function is not currently invoked by ConnectBlock(), so we
* should consider upgrade issues if we change which consensus rules are
* enforced in this function (eg by adding a new consensus rule). See comment
* in ConnectBlock().
* Note that -reindex-chainstate skips the validation that happens here!
*/
static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
assert(pindexPrev != nullptr);
const int nHeight = pindexPrev->nHeight + 1;
// Check proof of work
const Consensus::Params& consensusParams = params.GetConsensus();
if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
// Check against checkpoints
if (fCheckpointsEnabled) {
// Don't accept any forks from the main chain prior to last checkpoint.
// GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
// BlockIndex().
CBlockIndex* pcheckpoint = blockman.GetLastCheckpoint(params.Checkpoints());
if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
}
}
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
// Check timestamp
if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
// Reject blocks with outdated version
if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
(block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_DERSIG)) ||
(block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CLTV))) {
return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
strprintf("rejected nVersion=0x%08x block", block.nVersion));
}
return true;
}
/** NOTE: This function is not currently invoked by ConnectBlock(), so we
* should consider upgrade issues if we change which consensus rules are
* enforced in this function (eg by adding a new consensus rule). See comment
* in ConnectBlock().
* Note that -reindex-chainstate skips the validation that happens here!
*/
static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
// Enforce BIP113 (Median Time Past).
int nLockTimeFlags = 0;
if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV)) {
assert(pindexPrev != nullptr);
nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
}
int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
? pindexPrev->GetMedianTimePast()
: block.GetBlockTime();
// Check that all transactions are finalized
for (const auto& tx : block.vtx) {
if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
}
}
// Enforce rule that the coinbase starts with serialized block height
if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB))
{
CScript expect = CScript() << nHeight;
if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
}
}
// Validation for witness commitments.
// * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
// coinbase (where 0x0000....0000 is used instead).
// * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
// * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
// * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
// {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
// multiple, the last one is used.
bool fHaveWitness = false;
if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != NO_WITNESS_COMMITMENT) {
bool malleated = false;
uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
// The malleation check is ignored; as the transaction tree itself
// already does not permit it, it is impossible to trigger in the
// witness tree.
if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
}
CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
}
fHaveWitness = true;
}
}
// No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
if (!fHaveWitness) {
for (const auto& tx : block.vtx) {
if (tx->HasWitness()) {
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
}
}
}
// After the coinbase witness reserved value and commitment are verified,
// we can check if the block weight passes (before we've checked the
// coinbase witness, it would be possible for the weight to be too
// large by filling up the coinbase witness, which doesn't change
// the block hash, so we couldn't mark the block as permanently
// failed).
if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
}
return true;
}
bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator miSelf = m_block_index.find(hash);
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
if (miSelf != m_block_index.end()) {
// Block header is already known.
CBlockIndex* pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK) {
LogPrint(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
}
return true;
}
if (!CheckBlockHeader(block, state, chainparams.GetConsensus())) {
LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
return false;
}
// Get prev block index
CBlockIndex* pindexPrev = nullptr;
BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
if (mi == m_block_index.end()) {
LogPrint(BCLog::VALIDATION, "%s: %s prev block not found\n", __func__, hash.ToString());
return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
}
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
}
if (!ContextualCheckBlockHeader(block, state, *this, chainparams, pindexPrev, GetAdjustedTime())) {
LogPrint(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
return false;
}
/* Determine if this block descends from any block which has been found
* invalid (m_failed_blocks), then mark pindexPrev and any blocks between
* them as failed. For example:
*
* D3
* /
* B2 - C2
* / \
* A D2 - E2 - F2
* \
* B1 - C1 - D1 - E1
*
* In the case that we attempted to reorg from E1 to F2, only to find
* C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
* but NOT D3 (it was not in any of our candidate sets at the time).
*
* In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
* in LoadBlockIndex.
*/
if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
// The above does not mean "invalid": it checks if the previous block
// hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
// optimization, in the common case of adding a new block to the tip,
// we don't need to iterate over the failed blocks list.
for (const CBlockIndex* failedit : m_failed_blocks) {
if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
assert(failedit->nStatus & BLOCK_FAILED_VALID);
CBlockIndex* invalid_walk = pindexPrev;
while (invalid_walk != failedit) {
invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(invalid_walk);
invalid_walk = invalid_walk->pprev;
}
LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
}
}
}
}
CBlockIndex* pindex = AddToBlockIndex(block);
if (ppindex)
*ppindex = pindex;
return true;
}
// Exposed wrapper for AcceptBlockHeader
bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
{
AssertLockNotHeld(cs_main);
{
LOCK(cs_main);
for (const CBlockHeader& header : headers) {
CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
bool accepted = m_blockman.AcceptBlockHeader(
header, state, chainparams, &pindex);
ActiveChainstate().CheckBlockIndex();
if (!accepted) {
return false;
}
if (ppindex) {
*ppindex = pindex;
}
}
}
if (NotifyHeaderTip(ActiveChainstate())) {
if (ActiveChainstate().IsInitialBlockDownload() && ppindex && *ppindex) {
LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", (*ppindex)->nHeight, 100.0/((*ppindex)->nHeight+(GetAdjustedTime() - (*ppindex)->GetBlockTime()) / Params().GetConsensus().nPowTargetSpacing) * (*ppindex)->nHeight);
}
}
return true;
}
/** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
{
const CBlock& block = *pblock;
if (fNewBlock) *fNewBlock = false;
AssertLockHeld(cs_main);
CBlockIndex *pindexDummy = nullptr;
CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
bool accepted_header = m_blockman.AcceptBlockHeader(block, state, m_params, &pindex);
CheckBlockIndex();
if (!accepted_header)
return false;
// Try to process all requested blocks that we don't have, but only
// process an unrequested block if it's new and has enough work to
// advance our tip, and isn't too many blocks ahead.
bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
// Blocks that are too out-of-order needlessly limit the effectiveness of
// pruning, because pruning will not delete block files that contain any
// blocks which are too close in height to the tip. Apply this test
// regardless of whether pruning is enabled; it should generally be safe to
// not process unrequested blocks.
bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
// TODO: Decouple this function from the block download logic by removing fRequested
// This requires some new chain data structure to efficiently look up if a
// block is in a chain leading to a candidate for best tip, despite not
// being such a candidate itself.
// TODO: deal better with return value and error conditions for duplicate
// and unrequested blocks.
if (fAlreadyHave) return true;
if (!fRequested) { // If we didn't ask for it:
if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
if (fTooFarAhead) return true; // Block height is too high
// Protect against DoS attacks from low-work chains.
// If our tip is behind, a peer could try to send us
// low-work blocks on a fake chain that we would never
// request; don't process these.
if (pindex->nChainWork < nMinimumChainWork) return true;
}
if (!CheckBlock(block, state, m_params.GetConsensus()) ||
!ContextualCheckBlock(block, state, m_params.GetConsensus(), pindex->pprev)) {
if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
}
return error("%s: %s", __func__, state.ToString());
}
// Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
// (but if it does not build on our best tip, let the SendMessages loop relay it)
if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
GetMainSignals().NewPoWValidBlock(pindex, pblock);
// Write block to history file
if (fNewBlock) *fNewBlock = true;
try {
FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, m_chain, m_params, dbp);
if (blockPos.IsNull()) {
state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
return false;
}
ReceivedBlockTransactions(block, pindex, blockPos);
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error: ") + e.what());
}
FlushStateToDisk(state, FlushStateMode::NONE);
CheckBlockIndex();
return true;
}
bool ChainstateManager::ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block)
{
AssertLockNotHeld(cs_main);
{
CBlockIndex *pindex = nullptr;
if (new_block) *new_block = false;
BlockValidationState state;
// CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
// Therefore, the following critical section must include the CheckBlock() call as well.
LOCK(cs_main);
// Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
// CheckBlock() fails. This is protective against consensus failure if there are any unknown forms of block
// malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
// https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html. Because CheckBlock() is
// not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
bool ret = CheckBlock(*block, state, chainparams.GetConsensus());
if (ret) {
// Store to disk
ret = ActiveChainstate().AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block);
}
if (!ret) {
GetMainSignals().BlockChecked(*block, state);
return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
}
}
NotifyHeaderTip(ActiveChainstate());
BlockValidationState state; // Only used to report errors, not invalidity - ignore it
if (!ActiveChainstate().ActivateBestChain(state, block)) {
return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
}
return true;
}
bool TestBlockValidity(BlockValidationState& state,
const CChainParams& chainparams,
CChainState& chainstate,
const CBlock& block,
CBlockIndex* pindexPrev,
bool fCheckPOW,
bool fCheckMerkleRoot)
{
AssertLockHeld(cs_main);
assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
CCoinsViewCache viewNew(&chainstate.CoinsTip());
uint256 block_hash(block.GetHash());
CBlockIndex indexDummy(block);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
indexDummy.phashBlock = &block_hash;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainparams, pindexPrev, GetAdjustedTime()))
return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew, true)) {
return false;
}
assert(state.IsValid());
return true;
}
/**
* BLOCK PRUNING CODE
*/
void BlockManager::PruneOneBlockFile(const int fileNumber)
{
AssertLockHeld(cs_main);
LOCK(cs_LastBlockFile);
for (const auto& entry : m_block_index) {
CBlockIndex* pindex = entry.second;
if (pindex->nFile == fileNumber) {
pindex->nStatus &= ~BLOCK_HAVE_DATA;
pindex->nStatus &= ~BLOCK_HAVE_UNDO;
pindex->nFile = 0;
pindex->nDataPos = 0;
pindex->nUndoPos = 0;
setDirtyBlockIndex.insert(pindex);
// Prune from m_blocks_unlinked -- any block we prune would have
// to be downloaded again in order to consider its chain, at which
// point it would be considered as a candidate for
// m_blocks_unlinked or setBlockIndexCandidates.
auto range = m_blocks_unlinked.equal_range(pindex->pprev);
while (range.first != range.second) {
std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
range.first++;
if (_it->second == pindex) {
m_blocks_unlinked.erase(_it);
}
}
}
}
vinfoBlockFile[fileNumber].SetNull();
setDirtyFileInfo.insert(fileNumber);
}
void BlockManager::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
{
assert(fPruneMode && nManualPruneHeight > 0);
LOCK2(cs_main, cs_LastBlockFile);
if (chain_tip_height < 0) {
return;
}
// last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP);
int count = 0;
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
continue;
}
PruneOneBlockFile(fileNumber);
setFilesToPrune.insert(fileNumber);
count++;
}
LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
}
/* This function is called from the RPC code for pruneblockchain */
void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight)
{
BlockValidationState state;
if (!active_chainstate.FlushStateToDisk(
state, FlushStateMode::NONE, nManualPruneHeight)) {
LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
}
}
void BlockManager::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
{
LOCK2(cs_main, cs_LastBlockFile);
if (chain_tip_height < 0 || nPruneTarget == 0) {
return;
}
if ((uint64_t)chain_tip_height <= nPruneAfterHeight) {
return;
}
unsigned int nLastBlockWeCanPrune = std::min(prune_height, chain_tip_height - static_cast<int>(MIN_BLOCKS_TO_KEEP));
uint64_t nCurrentUsage = CalculateCurrentUsage();
// We don't check to prune until after we've allocated new space for files
// So we should leave a buffer under our target to account for another allocation
// before the next pruning.
uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
uint64_t nBytesToPrune;
int count = 0;
if (nCurrentUsage + nBuffer >= nPruneTarget) {
// On a prune event, the chainstate DB is flushed.
// To avoid excessive prune events negating the benefit of high dbcache
// values, we should not prune too rapidly.
// So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
if (is_ibd) {
// Since this is only relevant during IBD, we use a fixed 10%
nBuffer += nPruneTarget / 10;
}
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
if (vinfoBlockFile[fileNumber].nSize == 0) {
continue;
}
if (nCurrentUsage + nBuffer < nPruneTarget) { // are we below our target?
break;
}
// don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
continue;
}
PruneOneBlockFile(fileNumber);
// Queue up the files for removal
setFilesToPrune.insert(fileNumber);
nCurrentUsage -= nBytesToPrune;
count++;
}
}
LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
nLastBlockWeCanPrune, count);
}
CBlockIndex * BlockManager::InsertBlockIndex(const uint256& hash)
{
AssertLockHeld(cs_main);
if (hash.IsNull())
return nullptr;
// Return existing
BlockMap::iterator mi = m_block_index.find(hash);
if (mi != m_block_index.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool BlockManager::LoadBlockIndex(
const Consensus::Params& consensus_params,
std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
{
if (!m_block_tree_db->LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); })) {
return false;
}
// Calculate nChainWork
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(m_block_index.size());
for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
{
if (ShutdownRequested()) return false;
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
// We can link the chain of blocks for which we've received transactions at some point.
// Pruned nodes may have deleted the block.
if (pindex->nTx > 0) {
if (pindex->pprev) {
if (pindex->pprev->HaveTxsDownloaded()) {
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
} else {
pindex->nChainTx = 0;
m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
}
} else {
pindex->nChainTx = pindex->nTx;
}
}
if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
pindex->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindex);
}
if (pindex->IsAssumedValid() ||
(pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
(pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
block_index_candidates.insert(pindex);
}
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex;
if (pindex->pprev)
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex;
}
return true;
}
void BlockManager::Unload() {
m_failed_blocks.clear();
m_blocks_unlinked.clear();
for (const BlockMap::value_type& entry : m_block_index) {
delete entry.second;
}
m_block_index.clear();
}
bool BlockManager::LoadBlockIndexDB(std::set<CBlockIndex*, CBlockIndexWorkComparator>& setBlockIndexCandidates)
{
if (!LoadBlockIndex(
::Params().GetConsensus(),
setBlockIndexCandidates)) {
return false;
}
// Load block file info
m_block_tree_db->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
m_block_tree_db->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
vinfoBlockFile.push_back(info);
} else {
break;
}
}
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
std::set<int> setBlkDataFiles;
for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index) {
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
setBlkDataFiles.insert(pindex->nFile);
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
{
FlatFilePos pos(*it, 0);
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
return false;
}
}
// Check whether we have ever pruned block & undo files
m_block_tree_db->ReadFlag("prunedblockfiles", fHavePruned);
if (fHavePruned)
LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
// Check whether we need to continue reindexing
bool fReindexing = false;
m_block_tree_db->ReadReindexing(fReindexing);
if(fReindexing) fReindex = true;
return true;
}
void CChainState::LoadMempool(const ArgsManager& args)
{
if (!m_mempool) return;
if (args.GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
::LoadMempool(*m_mempool, *this);
}
m_mempool->SetIsLoaded(!ShutdownRequested());
}
bool CChainState::LoadChainTip()
{
AssertLockHeld(cs_main);
const CCoinsViewCache& coins_cache = CoinsTip();
assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
const CBlockIndex* tip = m_chain.Tip();
if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
return true;
}
// Load pointer to end of best chain
CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
if (!pindex) {
return false;
}
m_chain.SetTip(pindex);
PruneBlockIndexCandidates();
tip = m_chain.Tip();
LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
tip->GetBlockHash().ToString(),
m_chain.Height(),
FormatISO8601DateTime(tip->GetBlockTime()),
GuessVerificationProgress(m_params.TxData(), tip));
return true;
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, false);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100, false);
}
bool CVerifyDB::VerifyDB(
CChainState& chainstate,
const CChainParams& chainparams,
CCoinsView& coinsview,
int nCheckLevel, int nCheckDepth)
{
AssertLockHeld(cs_main);
if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr)
return true;
// Verify blocks in the best chain
if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height())
nCheckDepth = chainstate.m_chain.Height();
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(&coinsview);
CBlockIndex* pindex;
CBlockIndex* pindexFailure = nullptr;
int nGoodTransactions = 0;
BlockValidationState state;
int reportDone = 0;
LogPrintf("[0%%]..."); /* Continued */
const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};
for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
if (reportDone < percentageDone/10) {
// report every 10% step
LogPrintf("[%d%%]...", percentageDone); /* Continued */
reportDone = percentageDone/10;
}
uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
if (pindex->nHeight <= chainstate.m_chain.Height()-nCheckDepth)
break;
if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
// If pruning or running under an assumeutxo snapshot, only go
// back as far as we have data.
LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
break;
}
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
if (!pindex->GetUndoPos().IsNull()) {
if (!UndoReadFromDisk(undo, pindex)) {
return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
if (nCheckLevel >= 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
assert(coins.GetBestBlock() == pindex->GetBlockHash());
DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
if (res == DISCONNECT_FAILED) {
return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
if (res == DISCONNECT_UNCLEAN) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else {
nGoodTransactions += block.vtx.size();
}
}
if (ShutdownRequested()) return true;
}
if (pindexFailure)
return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// store block count as we move pindex at check level >= 4
int block_count = chainstate.m_chain.Height() - pindex->nHeight;
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
while (pindex != chainstate.m_chain.Tip()) {
const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
if (reportDone < percentageDone/10) {
// report every 10% step
LogPrintf("[%d%%]...", percentageDone); /* Continued */
reportDone = percentageDone/10;
}
uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
pindex = chainstate.m_chain.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
}
if (ShutdownRequested()) return true;
}
}
LogPrintf("[DONE].\n");
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
return true;
}
/** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs)
{
// TODO: merge with ConnectBlock
CBlock block;
if (!ReadBlockFromDisk(block, pindex, m_params.GetConsensus())) {
return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
for (const CTransactionRef& tx : block.vtx) {
if (!tx->IsCoinBase()) {
for (const CTxIn &txin : tx->vin) {
inputs.SpendCoin(txin.prevout);
}
}
// Pass check = true as every addition may be an overwrite.
AddCoins(inputs, *tx, pindex->nHeight, true);
}
return true;
}
bool CChainState::ReplayBlocks()
{
LOCK(cs_main);
CCoinsView& db = this->CoinsDB();
CCoinsViewCache cache(&db);
std::vector<uint256> hashHeads = db.GetHeadBlocks();
if (hashHeads.empty()) return true; // We're already in a consistent state.
if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
LogPrintf("Replaying blocks\n");
const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
const CBlockIndex* pindexNew; // New tip during the interrupted flush.
const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
return error("ReplayBlocks(): reorganization to unknown block requested");
}
pindexNew = m_blockman.m_block_index[hashHeads[0]];
if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
return error("ReplayBlocks(): reorganization from unknown block requested");
}
pindexOld = m_blockman.m_block_index[hashHeads[1]];
pindexFork = LastCommonAncestor(pindexOld, pindexNew);
assert(pindexFork != nullptr);
}
// Rollback along the old branch.
while (pindexOld != pindexFork) {
if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
CBlock block;
if (!ReadBlockFromDisk(block, pindexOld, m_params.GetConsensus())) {
return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
}
LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
if (res == DISCONNECT_FAILED) {
return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
}
// If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
// overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
// applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
// the result is still a version of the UTXO set with the effects of that block undone.
}
pindexOld = pindexOld->pprev;
}
// Roll forward from the forking point to the new tip.
int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
if (!RollforwardBlock(pindex, cache)) return false;
}
cache.SetBestBlock(pindexNew->GetBlockHash());
cache.Flush();
uiInterface.ShowProgress("", 100, false);
return true;
}
bool CChainState::NeedsRedownload() const
{
AssertLockHeld(cs_main);
// At and above m_params.SegwitHeight, segwit consensus rules must be validated
CBlockIndex* block{m_chain.Tip()};
while (block != nullptr && DeploymentActiveAt(*block, m_params.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
// block is insufficiently validated for a segwit client
return true;
}
block = block->pprev;
}
return false;
}
void CChainState::UnloadBlockIndex() {
nBlockSequenceId = 1;
setBlockIndexCandidates.clear();
}
// May NOT be used after any connections are up as much
// of the peer-processing logic assumes a consistent
// block index state
void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman)
{
LOCK(cs_main);
chainman.Unload();
pindexBestInvalid = nullptr;
pindexBestHeader = nullptr;
if (mempool) mempool->clear();
vinfoBlockFile.clear();
nLastBlockFile = 0;
setDirtyBlockIndex.clear();
setDirtyFileInfo.clear();
g_versionbitscache.Clear();
for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
warningcache[b].clear();
}
fHavePruned = false;
}
bool ChainstateManager::LoadBlockIndex()
{
AssertLockHeld(cs_main);
// Load block index from databases
bool needs_init = fReindex;
if (!fReindex) {
bool ret = m_blockman.LoadBlockIndexDB(ActiveChainstate().setBlockIndexCandidates);
if (!ret) return false;
needs_init = m_blockman.m_block_index.empty();
}
if (needs_init) {
// Everything here is for *new* reindex/DBs. Thus, though
// LoadBlockIndexDB may have set fReindex if we shut down
// mid-reindex previously, we don't check fReindex and
// instead only check it prior to LoadBlockIndexDB to set
// needs_init.
LogPrintf("Initializing databases...\n");
}
return true;
}
bool CChainState::LoadGenesisBlock()
{
LOCK(cs_main);
// Check whether we're already initialized by checking for genesis in
// m_blockman.m_block_index. Note that we can't use m_chain here, since it is
// set based on the coins db, not the block index db, which is the only
// thing loaded at this point.
if (m_blockman.m_block_index.count(m_params.GenesisBlock().GetHash()))
return true;
try {
const CBlock& block = m_params.GenesisBlock();
FlatFilePos blockPos = SaveBlockToDisk(block, 0, m_chain, m_params, nullptr);
if (blockPos.IsNull())
return error("%s: writing genesis block to disk failed", __func__);
CBlockIndex *pindex = m_blockman.AddToBlockIndex(block);
ReceivedBlockTransactions(block, pindex, blockPos);
} catch (const std::runtime_error& e) {
return error("%s: failed to write genesis block: %s", __func__, e.what());
}
return true;
}
void CChainState::LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex)
static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
uint64_t nRewind = blkdat.GetPos();
while (!blkdat.eof()) {
if (ShutdownRequested()) return;
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
blkdat.FindByte(m_params.MessageStart()[0]);
nRewind = blkdat.GetPos()+1;
blkdat >> buf;
if (memcmp(buf, m_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
continue;
}
// read size
blkdat >> nSize;
if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64_t nBlockPos = blkdat.GetPos();
if (dbp)
dbp->nPos = nBlockPos;
blkdat.SetLimit(nBlockPos + nSize);
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
blkdat >> block;
nRewind = blkdat.GetPos();
uint256 hash = block.GetHash();
{
LOCK(cs_main);
// detect out of order blocks, and store them for later
if (hash != m_params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(block.hashPrevBlock)) {
LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString());
if (dbp)
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
continue;
}
// process in case the block isn't known yet
CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
BlockValidationState state;
if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr)) {
nLoaded++;
}
if (state.IsError()) {
break;
}
} else if (hash != m_params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
}
}
// Activate the genesis block so normal node progress can continue
if (hash == m_params.GetConsensus().hashGenesisBlock) {
BlockValidationState state;
if (!ActivateBestChain(state, nullptr)) {
break;
}
}
NotifyHeaderTip(*this);
// Recursively process earlier encountered successors of this block
std::deque<uint256> queue;
queue.push_back(hash);
while (!queue.empty()) {
uint256 head = queue.front();
queue.pop_front();
std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, FlatFilePos>::iterator it = range.first;
std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
if (ReadBlockFromDisk(*pblockrecursive, it->second, m_params.GetConsensus())) {
LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
head.ToString());
LOCK(cs_main);
BlockValidationState dummy;
if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr)) {
nLoaded++;
queue.push_back(pblockrecursive->GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
NotifyHeaderTip(*this);
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
}
}
} catch (const std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
}
void CChainState::CheckBlockIndex()
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
// tests when iterating the block tree require that m_chain has been initialized.)
if (m_chain.Height() < 0) {
assert(m_blockman.m_block_index.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*,CBlockIndex*> forward;
for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
forward.insert(std::make_pair(entry.second->pprev, entry.second));
}
assert(forward.size() == m_blockman.m_block_index.size());
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
CBlockIndex *pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != nullptr) {
nNodes++;
if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
// Assumed-valid index entries will not have data since we haven't downloaded the
// full block yet.
if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA) && !pindex->IsAssumedValid()) {
pindexFirstMissing = pindex;
}
if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
// Skip validity flag checks for BLOCK_ASSUMED_VALID index entries, since these
// *_VALID_MASK flags will not be present for index entries we are temporarily assuming
// valid.
if (pindexFirstNotTransactionsValid == nullptr &&
(pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
pindexFirstNotTransactionsValid = pindex;
}
if (pindexFirstNotChainValid == nullptr &&
(pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
pindexFirstNotChainValid = pindex;
}
if (pindexFirstNotScriptsValid == nullptr &&
(pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
pindexFirstNotScriptsValid = pindex;
}
}
// Begin: actual consistency checks.
if (pindex->pprev == nullptr) {
// Genesis block checks.
assert(pindex->GetBlockHash() == m_params.GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
}
if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
// VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
// HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
// Unless these indexes are assumed valid and pending block download on a
// background chainstate.
if (!fHavePruned && !pindex->IsAssumedValid()) {
// If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(pindexFirstMissing == pindexFirstNeverProcessed);
} else {
// If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
}
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
if (pindex->IsAssumedValid()) {
// Assumed-valid blocks should have some nTx value.
assert(pindex->nTx > 0);
// Assumed-valid blocks should connect to the main chain.
assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
} else {
// Otherwise there should only be an nTx value if we have
// actually seen a block's transactions.
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
}
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == nullptr) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
if (pindexFirstInvalid == nullptr) {
const bool is_active = this == &m_chainman.ActiveChainstate();
// If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. m_chain.Tip() must also be there
// even if some data has been pruned.
//
// Don't perform this check for the background chainstate since
// its setBlockIndexCandidates shouldn't have some entries (i.e. those past the
// snapshot block) which do exist in the block index for the active chainstate.
if (is_active && (pindexFirstMissing == nullptr || pindex == m_chain.Tip())) {
assert(setBlockIndexCandidates.count(pindex));
}
// If some parent is missing, then it could be that this block was in
// setBlockIndexCandidates but had to be removed because of the missing data.
// In this case it must be in m_blocks_unlinked -- see test below.
}
} else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in m_blocks_unlinked.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
// If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
assert(foundInUnlinked);
}
if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
// We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
assert(fHavePruned); // We must have pruned.
// This block may have entered m_blocks_unlinked if:
// - it has a descendant that at some point had more work than the
// tip, and
// - we tried switching to that descendant but were missing
// data for some intermediate block between m_chain and the
// tip.
// So if this block is itself better than m_chain.Tip() and it wasn't in
// setBlockIndexCandidates, then it must be in m_blocks_unlinked.
if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
if (pindexFirstInvalid == nullptr) {
assert(foundInUnlinked);
}
}
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
std::string CChainState::ToString()
{
CBlockIndex* tip = m_chain.Tip();
return strprintf("Chainstate [%s] @ height %d (%s)",
m_from_snapshot_blockhash ? "snapshot" : "ibd",
tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
}
bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
{
if (coinstip_size == m_coinstip_cache_size_bytes &&
coinsdb_size == m_coinsdb_cache_size_bytes) {
// Cache sizes are unchanged, no need to continue.
return true;
}
size_t old_coinstip_size = m_coinstip_cache_size_bytes;
m_coinstip_cache_size_bytes = coinstip_size;
m_coinsdb_cache_size_bytes = coinsdb_size;
CoinsDB().ResizeCache(coinsdb_size);
LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
BlockValidationState state;
bool ret;
if (coinstip_size > old_coinstip_size) {
// Likely no need to flush if cache sizes have grown.
ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);
} else {
// Otherwise, flush state to disk and deallocate the in-memory coins map.
ret = FlushStateToDisk(state, FlushStateMode::ALWAYS);
CoinsTip().ReallocateCache();
}
return ret;
}
static const uint64_t MEMPOOL_DUMP_VERSION = 1;
bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function)
{
const CChainParams& chainparams = Params();
int64_t nExpiryTimeout = gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")};
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
return false;
}
int64_t count = 0;
int64_t expired = 0;
int64_t failed = 0;
int64_t already_there = 0;
int64_t unbroadcast = 0;
int64_t nNow = GetTime();
try {
uint64_t version;
file >> version;
if (version != MEMPOOL_DUMP_VERSION) {
return false;
}
uint64_t num;
file >> num;
while (num--) {
CTransactionRef tx;
int64_t nTime;
int64_t nFeeDelta;
file >> tx;
file >> nTime;
file >> nFeeDelta;
CAmount amountdelta = nFeeDelta;
if (amountdelta) {
pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
}
if (nTime > nNow - nExpiryTimeout) {
LOCK(cs_main);
if (AcceptToMemoryPoolWithTime(chainparams, pool, active_chainstate, tx, nTime, false /* bypass_limits */,
false /* test_accept */).m_result_type == MempoolAcceptResult::ResultType::VALID) {
++count;
} else {
// mempool may contain the transaction already, e.g. from
// wallet(s) having loaded it while we were processing
// mempool transactions; consider these as valid, instead of
// failed, but mark them as 'already there'
if (pool.exists(tx->GetHash())) {
++already_there;
} else {
++failed;
}
}
} else {
++expired;
}
if (ShutdownRequested())
return false;
}
std::map<uint256, CAmount> mapDeltas;
file >> mapDeltas;
for (const auto& i : mapDeltas) {
pool.PrioritiseTransaction(i.first, i.second);
}
std::set<uint256> unbroadcast_txids;
file >> unbroadcast_txids;
unbroadcast = unbroadcast_txids.size();
for (const auto& txid : unbroadcast_txids) {
// Ensure transactions were accepted to mempool then add to
// unbroadcast set.
if (pool.get(txid) != nullptr) pool.AddUnbroadcastTx(txid);
}
} catch (const std::exception& e) {
LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
return false;
}
LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there, %i waiting for initial broadcast\n", count, failed, expired, already_there, unbroadcast);
return true;
}
bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function, bool skip_file_commit)
{
int64_t start = GetTimeMicros();
std::map<uint256, CAmount> mapDeltas;
std::vector<TxMempoolInfo> vinfo;
std::set<uint256> unbroadcast_txids;
static Mutex dump_mutex;
LOCK(dump_mutex);
{
LOCK(pool.cs);
for (const auto &i : pool.mapDeltas) {
mapDeltas[i.first] = i.second;
}
vinfo = pool.infoAll();
unbroadcast_txids = pool.GetUnbroadcastTxs();
}
int64_t mid = GetTimeMicros();
try {
FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat.new", "wb")};
if (!filestr) {
return false;
}
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
uint64_t version = MEMPOOL_DUMP_VERSION;
file << version;
file << (uint64_t)vinfo.size();
for (const auto& i : vinfo) {
file << *(i.tx);
file << int64_t{count_seconds(i.m_time)};
file << int64_t{i.nFeeDelta};
mapDeltas.erase(i.tx->GetHash());
}
file << mapDeltas;
LogPrintf("Writing %d unbroadcast transactions to disk.\n", unbroadcast_txids.size());
file << unbroadcast_txids;
if (!skip_file_commit && !FileCommit(file.Get()))
throw std::runtime_error("FileCommit failed");
file.fclose();
if (!RenameOver(gArgs.GetDataDirNet() / "mempool.dat.new", gArgs.GetDataDirNet() / "mempool.dat")) {
throw std::runtime_error("Rename failed");
}
int64_t last = GetTimeMicros();
LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
} catch (const std::exception& e) {
LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
return false;
}
return true;
}
//! Guess how far we are in the verification process at the given block index
//! require cs_main if pindex has not been validated yet (because nChainTx might be unset)
double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
if (pindex == nullptr)
return 0.0;
int64_t nNow = time(nullptr);
double fTxTotal;
if (pindex->nChainTx <= data.nTxCount) {
fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
} else {
fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
}
return std::min<double>(pindex->nChainTx / fTxTotal, 1.0);
}
std::optional<uint256> ChainstateManager::SnapshotBlockhash() const
{
LOCK(::cs_main);
if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
// If a snapshot chainstate exists, it will always be our active.
return m_active_chainstate->m_from_snapshot_blockhash;
}
return std::nullopt;
}
std::vector<CChainState*> ChainstateManager::GetAll()
{
LOCK(::cs_main);
std::vector<CChainState*> out;
if (!IsSnapshotValidated() && m_ibd_chainstate) {
out.push_back(m_ibd_chainstate.get());
}
if (m_snapshot_chainstate) {
out.push_back(m_snapshot_chainstate.get());
}
return out;
}
CChainState& ChainstateManager::InitializeChainstate(
CTxMemPool* mempool, const std::optional<uint256>& snapshot_blockhash)
{
bool is_snapshot = snapshot_blockhash.has_value();
std::unique_ptr<CChainState>& to_modify =
is_snapshot ? m_snapshot_chainstate : m_ibd_chainstate;
if (to_modify) {
throw std::logic_error("should not be overwriting a chainstate");
}
to_modify.reset(new CChainState(mempool, m_blockman, *this, snapshot_blockhash));
// Snapshot chainstates and initial IBD chaintates always become active.
if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
LogPrintf("Switching active chainstate to %s\n", to_modify->ToString());
m_active_chainstate = to_modify.get();
} else {
throw std::logic_error("unexpected chainstate activation");
}
return *to_modify;
}
const AssumeutxoData* ExpectedAssumeutxo(
const int height, const CChainParams& chainparams)
{
const MapAssumeutxo& valid_assumeutxos_map = chainparams.Assumeutxo();
const auto assumeutxo_found = valid_assumeutxos_map.find(height);
if (assumeutxo_found != valid_assumeutxos_map.end()) {
return &assumeutxo_found->second;
}
return nullptr;
}
bool ChainstateManager::ActivateSnapshot(
CAutoFile& coins_file,
const SnapshotMetadata& metadata,
bool in_memory)
{
uint256 base_blockhash = metadata.m_base_blockhash;
if (this->SnapshotBlockhash()) {
LogPrintf("[snapshot] can't activate a snapshot-based chainstate more than once\n");
return false;
}
int64_t current_coinsdb_cache_size{0};
int64_t current_coinstip_cache_size{0};
// Cache percentages to allocate to each chainstate.
//
// These particular percentages don't matter so much since they will only be
// relevant during snapshot activation; caches are rebalanced at the conclusion of
// this function. We want to give (essentially) all available cache capacity to the
// snapshot to aid the bulk load later in this function.
static constexpr double IBD_CACHE_PERC = 0.01;
static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
{
LOCK(::cs_main);
// Resize the coins caches to ensure we're not exceeding memory limits.
//
// Allocate the majority of the cache to the incoming snapshot chainstate, since
// (optimistically) getting to its tip will be the top priority. We'll need to call
// `MaybeRebalanceCaches()` once we're done with this function to ensure
// the right allocation (including the possibility that no snapshot was activated
// and that we should restore the active chainstate caches to their original size).
//
current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
// Temporarily resize the active coins cache to make room for the newly-created
// snapshot chain.
this->ActiveChainstate().ResizeCoinsCaches(
static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
}
auto snapshot_chainstate = WITH_LOCK(::cs_main,
return std::make_unique<CChainState>(
/* mempool */ nullptr, m_blockman, *this, base_blockhash));
{
LOCK(::cs_main);
snapshot_chainstate->InitCoinsDB(
static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
in_memory, false, "chainstate");
snapshot_chainstate->InitCoinsCache(
static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
}
const bool snapshot_ok = this->PopulateAndValidateSnapshot(
*snapshot_chainstate, coins_file, metadata);
if (!snapshot_ok) {
WITH_LOCK(::cs_main, this->MaybeRebalanceCaches());
return false;
}
{
LOCK(::cs_main);
assert(!m_snapshot_chainstate);
m_snapshot_chainstate.swap(snapshot_chainstate);
const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
assert(chaintip_loaded);
m_active_chainstate = m_snapshot_chainstate.get();
LogPrintf("[snapshot] successfully activated snapshot %s\n", base_blockhash.ToString());
LogPrintf("[snapshot] (%.2f MB)\n",
m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
this->MaybeRebalanceCaches();
}
return true;
}
bool ChainstateManager::PopulateAndValidateSnapshot(
CChainState& snapshot_chainstate,
CAutoFile& coins_file,
const SnapshotMetadata& metadata)
{
// It's okay to release cs_main before we're done using `coins_cache` because we know
// that nothing else will be referencing the newly created snapshot_chainstate yet.
CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
uint256 base_blockhash = metadata.m_base_blockhash;
CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
if (!snapshot_start_block) {
// Needed for GetUTXOStats and ExpectedAssumeutxo to determine the height and to avoid a crash when base_blockhash.IsNull()
LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
base_blockhash.ToString());
return false;
}
int base_height = snapshot_start_block->nHeight;
auto maybe_au_data = ExpectedAssumeutxo(base_height, ::Params());
if (!maybe_au_data) {
LogPrintf("[snapshot] assumeutxo height in snapshot metadata not recognized " /* Continued */
"(%d) - refusing to load snapshot\n", base_height);
return false;
}
const AssumeutxoData& au_data = *maybe_au_data;
COutPoint outpoint;
Coin coin;
const uint64_t coins_count = metadata.m_coins_count;
uint64_t coins_left = metadata.m_coins_count;
LogPrintf("[snapshot] loading coins from snapshot %s\n", base_blockhash.ToString());
int64_t flush_now{0};
int64_t coins_processed{0};
while (coins_left > 0) {
try {
coins_file >> outpoint;
coins_file >> coin;
} catch (const std::ios_base::failure&) {
LogPrintf("[snapshot] bad snapshot format or truncated snapshot after deserializing %d coins\n",
coins_count - coins_left);
return false;
}
if (coin.nHeight > base_height ||
outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
) {
LogPrintf("[snapshot] bad snapshot data after deserializing %d coins\n",
coins_count - coins_left);
return false;
}
coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
--coins_left;
++coins_processed;
if (coins_processed % 1000000 == 0) {
LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
coins_processed,
static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
coins_cache.DynamicMemoryUsage() / (1000 * 1000));
}
// Batch write and flush (if we need to) every so often.
//
// If our average Coin size is roughly 41 bytes, checking every 120,000 coins
// means <5MB of memory imprecision.
if (coins_processed % 120000 == 0) {
if (ShutdownRequested()) {
return false;
}
const auto snapshot_cache_state = WITH_LOCK(::cs_main,
return snapshot_chainstate.GetCoinsCacheSizeState());
if (snapshot_cache_state >=
CoinsCacheSizeState::CRITICAL) {
LogPrintf("[snapshot] flushing coins cache (%.2f MB)... ", /* Continued */
coins_cache.DynamicMemoryUsage() / (1000 * 1000));
flush_now = GetTimeMillis();
// This is a hack - we don't know what the actual best block is, but that
// doesn't matter for the purposes of flushing the cache here. We'll set this
// to its correct value (`base_blockhash`) below after the coins are loaded.
coins_cache.SetBestBlock(GetRandHash());
coins_cache.Flush();
LogPrintf("done (%.2fms)\n", GetTimeMillis() - flush_now);
}
}
}
// Important that we set this. This and the coins_cache accesses above are
// sort of a layer violation, but either we reach into the innards of
// CCoinsViewCache here or we have to invert some of the CChainState to
// embed them in a snapshot-activation-specific CCoinsViewCache bulk load
// method.
coins_cache.SetBestBlock(base_blockhash);
bool out_of_coins{false};
try {
coins_file >> outpoint;
} catch (const std::ios_base::failure&) {
// We expect an exception since we should be out of coins.
out_of_coins = true;
}
if (!out_of_coins) {
LogPrintf("[snapshot] bad snapshot - coins left over after deserializing %d coins\n",
coins_count);
return false;
}
LogPrintf("[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
coins_count,
coins_cache.DynamicMemoryUsage() / (1000 * 1000),
base_blockhash.ToString());
LogPrintf("[snapshot] flushing snapshot chainstate to disk\n");
// No need to acquire cs_main since this chainstate isn't being used yet.
coins_cache.Flush(); // TODO: if #17487 is merged, add erase=false here for better performance.
assert(coins_cache.GetBestBlock() == base_blockhash);
CCoinsStats stats{CoinStatsHashType::HASH_SERIALIZED};
auto breakpoint_fnc = [] { /* TODO insert breakpoint here? */ };
// As above, okay to immediately release cs_main here since no other context knows
// about the snapshot_chainstate.
CCoinsViewDB* snapshot_coinsdb = WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
if (!GetUTXOStats(snapshot_coinsdb, WITH_LOCK(::cs_main, return std::ref(m_blockman)), stats, breakpoint_fnc)) {
LogPrintf("[snapshot] failed to generate coins stats\n");
return false;
}
// Assert that the deserialized chainstate contents match the expected assumeutxo value.
if (AssumeutxoHash{stats.hashSerialized} != au_data.hash_serialized) {
LogPrintf("[snapshot] bad snapshot content hash: expected %s, got %s\n",
au_data.hash_serialized.ToString(), stats.hashSerialized.ToString());
return false;
}
snapshot_chainstate.m_chain.SetTip(snapshot_start_block);
// The remainder of this function requires modifying data protected by cs_main.
LOCK(::cs_main);
// Fake various pieces of CBlockIndex state:
CBlockIndex* index = nullptr;
for (int i = 0; i <= snapshot_chainstate.m_chain.Height(); ++i) {
index = snapshot_chainstate.m_chain[i];
// Fake nTx so that LoadBlockIndex() loads assumed-valid CBlockIndex
// entries (among other things)
if (!index->nTx) {
index->nTx = 1;
}
// Fake nChainTx so that GuessVerificationProgress reports accurately
index->nChainTx = index->pprev ? index->pprev->nChainTx + index->nTx : 1;
// Mark unvalidated block index entries beneath the snapshot base block as assumed-valid.
if (!index->IsValid(BLOCK_VALID_SCRIPTS)) {
// This flag will be removed once the block is fully validated by a
// background chainstate.
index->nStatus |= BLOCK_ASSUMED_VALID;
}
// Fake BLOCK_OPT_WITNESS so that CChainState::NeedsRedownload()
// won't ask to rewind the entire assumed-valid chain on startup.
if (index->pprev && DeploymentActiveAt(*index, ::Params().GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
index->nStatus |= BLOCK_OPT_WITNESS;
}
setDirtyBlockIndex.insert(index);
// Changes to the block index will be flushed to disk after this call
// returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
// called, since we've added a snapshot chainstate and therefore will
// have to downsize the IBD chainstate, which will result in a call to
// `FlushStateToDisk(ALWAYS)`.
}
assert(index);
index->nChainTx = au_data.nChainTx;
snapshot_chainstate.setBlockIndexCandidates.insert(snapshot_start_block);
LogPrintf("[snapshot] validated snapshot (%.2f MB)\n",
coins_cache.DynamicMemoryUsage() / (1000 * 1000));
return true;
}
CChainState& ChainstateManager::ActiveChainstate() const
{
LOCK(::cs_main);
assert(m_active_chainstate);
return *m_active_chainstate;
}
bool ChainstateManager::IsSnapshotActive() const
{
LOCK(::cs_main);
return m_snapshot_chainstate && m_active_chainstate == m_snapshot_chainstate.get();
}
void ChainstateManager::Unload()
{
for (CChainState* chainstate : this->GetAll()) {
chainstate->m_chain.SetTip(nullptr);
chainstate->UnloadBlockIndex();
}
m_blockman.Unload();
}
void ChainstateManager::Reset()
{
LOCK(::cs_main);
m_ibd_chainstate.reset();
m_snapshot_chainstate.reset();
m_active_chainstate = nullptr;
m_snapshot_validated = false;
}
void ChainstateManager::MaybeRebalanceCaches()
{
if (m_ibd_chainstate && !m_snapshot_chainstate) {
LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
// Allocate everything to the IBD chainstate.
m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
}
else if (m_snapshot_chainstate && !m_ibd_chainstate) {
LogPrintf("[snapshot] allocating all cache to the snapshot chainstate\n");
// Allocate everything to the snapshot chainstate.
m_snapshot_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
}
else if (m_ibd_chainstate && m_snapshot_chainstate) {
// If both chainstates exist, determine who needs more cache based on IBD status.
//
// Note: shrink caches first so that we don't inadvertently overwhelm available memory.
if (m_snapshot_chainstate->IsInitialBlockDownload()) {
m_ibd_chainstate->ResizeCoinsCaches(
m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
m_snapshot_chainstate->ResizeCoinsCaches(
m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
} else {
m_snapshot_chainstate->ResizeCoinsCaches(
m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
m_ibd_chainstate->ResizeCoinsCaches(
m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
}
}
}
|
#ifndef ALEPH_TOPOLOGY_MORSE_SMALE_COMPLEX__
#define ALEPH_TOPOLOGY_MORSE_SMALE_COMPLEX__
#include <algorithm>
#include <vector>
// TODO: Remove after debugging
#include <iostream>
#include <aleph/topology/UnionFind.hh>
namespace aleph
{
namespace topology
{
template <class Mesh> class MorseSmaleComplex
{
public:
void operator()( const Mesh& M )
{
std::cerr << "\n";
auto&& vertices = M.vertices();
for( auto&& vertex : vertices )
{
auto higherNeigbours = M.getHigherNeighbours( vertex );
auto lowerNeighbours = M.getLowerNeighbours( vertex );
std::size_t nl = 0;
std::size_t nu = 0;
std::tie( nl, nu ) = contiguousSegments( M, vertex );
std::cerr << "[" << vertex << "]: ";
if( higherNeigbours.empty() )
std::cerr << "Maximum\n";
else if( lowerNeighbours.empty() )
std::cerr << "Minimum\n";
else
{
std::cerr << "Saddle\n";
std::cerr << " +: ";
for( auto&& n : higherNeigbours )
std::cerr << n << " " ;
std::cerr << "\n";
std::cerr << " -: ";
for( auto&& n : lowerNeighbours )
std::cerr << n << " " ;
std::cerr << "\n";
}
std::cerr << " nl: " << nl << "\n"
<< " nu: " << nu << "\n\n";
}
}
private:
/**
Calculates the number of contiguous segments in the link of
a vertex, with respect to the given mesh.
*/
static std::pair<std::size_t, std::size_t> contiguousSegments( const Mesh& M, typename Mesh::Index id )
{
using Index = typename Mesh::Index;
auto data = M.data(id);
auto link = M.link(id);
std::vector<Index> upperLink;
std::vector<Index> lowerLink;
std::copy_if( link.begin(), link.end(), std::back_inserter( upperLink ), [&data, &M] ( Index& u ) { return M.data(u) >= data; } );
std::copy_if( link.begin(), link.end(), std::back_inserter( lowerLink ), [&data, &M] ( Index& u ) { return M.data(u) <= data; } );
auto&& numConnectedComponents = [&M, &id] ( const std::vector<Index>& link )
{
auto curr = link.begin();
auto next = std::next( curr );
UnionFind<Index> uf( link.begin(), link.end() );
for( ; curr != link.end(); )
{
if( next == link.end() )
next = link.begin();
auto u = id;
auto v = *curr++;
auto w = *next++;
if( M.hasEdge(u,v) )
{
if( M.hasEdge(v,w) )
uf.merge(v,w);
}
else
throw std::runtime_error( "Edge to link centre vertex does not exist" );
}
std::vector<Index> roots;
uf.roots( std::back_inserter(roots) );
return roots.size();
};
return std::make_pair( numConnectedComponents( lowerLink ), numConnectedComponents( upperLink ) );
}
};
} // namespace topology
} // namespace aleph
#endif
|
/*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitAnimation.h"
#include "Animation.h"
#include "AnimationBase.h"
#include "RenderStyle.h"
using namespace std;
namespace WebCore {
WebKitAnimation::WebKitAnimation(PassRefPtr<KeyframeAnimation> keyframeAnimation)
: m_keyframeAnimation(keyframeAnimation)
{
}
String WebKitAnimation::name() const
{
return m_keyframeAnimation->animation()->name();
}
double WebKitAnimation::duration() const
{
return m_keyframeAnimation->duration();
}
double WebKitAnimation::elapsedTime() const
{
return m_keyframeAnimation->getElapsedTime();
}
void WebKitAnimation::setElapsedTime(double time)
{
m_keyframeAnimation->setElapsedTime(time);
}
double WebKitAnimation::delay() const
{
return m_keyframeAnimation->animation()->delay();
}
int WebKitAnimation::iterationCount() const
{
return m_keyframeAnimation->animation()->iterationCount();
}
bool WebKitAnimation::paused() const
{
return m_keyframeAnimation->paused();
}
bool WebKitAnimation::ended() const
{
int iterations = iterationCount();
if (iterations == Animation::IterationCountInfinite)
return false;
return m_keyframeAnimation->getElapsedTime() > (m_keyframeAnimation->duration() * iterations);
}
WebKitAnimation::Direction WebKitAnimation::direction() const
{
if (m_keyframeAnimation->animation()->direction() == Animation::AnimationDirectionNormal)
return DIRECTION_NORMAL;
return DIRECTION_ALTERNATE;
}
WebKitAnimation::FillMode WebKitAnimation::fillMode() const
{
switch (m_keyframeAnimation->animation()->fillMode()) {
case AnimationFillModeNone:
return FILL_NONE;
break;
case AnimationFillModeForwards:
return FILL_FORWARDS;
break;
case AnimationFillModeBackwards:
return FILL_BACKWARDS;
break;
default:
return FILL_BOTH;
break;
}
}
void WebKitAnimation::pause()
{
m_keyframeAnimation->pause();
}
void WebKitAnimation::play()
{
m_keyframeAnimation->play();
}
}
|
// A. A pile of stones
#include <iostream>
#include <algorithm>
#include <string>
int main(){
int n;
std::cin >> n;
std::string s;
std::cin >> s;
int ans = 0;
for (auto el: s){
if (el == '+') ++ans;
else ans = std::max(0, --ans);
}
std::cout << ans << std::endl;
return 0;
}
|
// *****************************************************************************
// *****************************************************************************
// Copyright 2012, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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.
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #1 $
// $Date: 2017/06/06 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#ifndef LEFZLIB_H
typedef void* lefGZFile;
/*
* Name: lefGZipOpen
* Description: Open a gzip file
* Returns: A file pointer
*/
extern lefGZFile lefGZipOpen(const char* gzipFile, const char* mode);
/*
* Name: lefGZipClose
* Description: Close a gzip file
* Returns: 0 if no errors
*/
extern int lefGZipClose(lefGZFile filePtr);
/*
* Name: lefrReadGZip
* Description: Parse a lef gzip file
* Returns: 0 if no errors
*/
extern int lefrReadGZip(lefGZFile file, const char* gzipFile, void* uData);
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2017-2020 The PIVX developers
// Copyright (c) 2020-2021 The PCTM developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bignum.h"
/** C++ wrapper for BIGNUM (Gmp bignum) */
CBigNum::CBigNum()
{
mpz_init(bn);
}
CBigNum::CBigNum(const CBigNum& b)
{
mpz_init(bn);
mpz_set(bn, b.bn);
}
CBigNum& CBigNum::operator=(const CBigNum& b)
{
mpz_set(bn, b.bn);
return (*this);
}
CBigNum::~CBigNum()
{
mpz_clear(bn);
}
//CBigNum(char n) is not portable. Use 'signed char' or 'unsigned char'.
CBigNum::CBigNum(signed char n) { mpz_init(bn); if (n >= 0) mpz_set_ui(bn, n); else mpz_set_si(bn, n); }
CBigNum::CBigNum(short n) { mpz_init(bn); if (n >= 0) mpz_set_ui(bn, n); else mpz_set_si(bn, n); }
CBigNum::CBigNum(int n) { mpz_init(bn); if (n >= 0) mpz_set_ui(bn, n); else mpz_set_si(bn, n); }
CBigNum::CBigNum(long n) { mpz_init(bn); if (n >= 0) mpz_set_ui(bn, n); else mpz_set_si(bn, n); }
CBigNum::CBigNum(long long n) { mpz_init(bn); mpz_set_si(bn, n); }
CBigNum::CBigNum(unsigned char n) { mpz_init(bn); mpz_set_ui(bn, n); }
CBigNum::CBigNum(unsigned short n) { mpz_init(bn); mpz_set_ui(bn, n); }
CBigNum::CBigNum(unsigned int n) { mpz_init(bn); mpz_set_ui(bn, n); }
CBigNum::CBigNum(unsigned long n) { mpz_init(bn); mpz_set_ui(bn, n); }
CBigNum::CBigNum(uint256 n) { mpz_init(bn); setuint256(n); }
CBigNum::CBigNum(const std::vector<unsigned char>& vch)
{
mpz_init(bn);
setvch(vch);
}
/** PRNGs use OpenSSL for consistency with seed initialization **/
/** Generates a cryptographically secure random number between zero and range-1 (inclusive)
* i.e. 0 <= returned number < range
* @param range The upper bound on the number.
* @return
*/
CBigNum CBigNum::randBignum(const CBigNum& range)
{
if (range < 2)
return 0;
size_t size = (mpz_sizeinbase (range.bn, 2) + CHAR_BIT-1) / CHAR_BIT;
std::vector<unsigned char> buf(size);
RandAddSeed();
GetRandBytes(buf.data(), size);
CBigNum ret(buf);
if (ret < 0)
mpz_neg(ret.bn, ret.bn);
return (ret % range);
}
/** Generates a cryptographically secure random k-bit number
* @param k The bit length of the number.
* @return
*/
CBigNum CBigNum::randKBitBignum(const uint32_t k)
{
std::vector<unsigned char> buf((k+7)/8);
RandAddSeed();
GetRandBytes(buf.data(), (k+7)/8);
CBigNum ret(buf);
if (ret < 0)
mpz_neg(ret.bn, ret.bn);
return ret % (BN_ONE << k);
}
/**Returns the size in bits of the underlying bignum.
*
* @return the size
*/
int CBigNum::bitSize() const
{
return mpz_sizeinbase(bn, 2);
}
void CBigNum::setulong(unsigned long n)
{
mpz_set_ui(bn, n);
}
unsigned long CBigNum::getulong() const
{
return mpz_get_ui(bn);
}
unsigned int CBigNum::getuint() const
{
return mpz_get_ui(bn);
}
int CBigNum::getint() const
{
unsigned long n = getulong();
if (mpz_cmp(bn, BN_ZERO.bn) >= 0) {
return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : n);
} else {
return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n);
}
}
void CBigNum::setuint256(uint256 n)
{
mpz_import(bn, n.size(), -1, 1, 0, 0, (unsigned char*)&n);
}
uint256 CBigNum::getuint256() const
{
if(bitSize() > 256) {
throw std::range_error("cannot convert to uint256, bignum longer than 256 bits");
}
uint256 n = UINT256_ZERO;
mpz_export((unsigned char*)&n, NULL, -1, 1, 0, 0, bn);
return n;
}
void CBigNum::setvch(const std::vector<unsigned char>& vch)
{
std::vector<unsigned char> vch2 = vch;
unsigned char sign = 0;
if (vch2.size() > 0) {
sign = vch2[vch2.size()-1] & 0x80;
vch2[vch2.size()-1] = vch2[vch2.size()-1] & 0x7f;
mpz_import(bn, vch2.size(), -1, 1, 0, 0, &vch2[0]);
if (sign)
mpz_neg(bn, bn);
}
else {
mpz_set_si(bn, 0);
}
}
std::vector<unsigned char> CBigNum::getvch() const
{
if (mpz_cmp(bn, BN_ZERO.bn) == 0) {
return std::vector<unsigned char>(0);
}
size_t size = (mpz_sizeinbase (bn, 2) + CHAR_BIT-1) / CHAR_BIT;
if (size <= 0)
return std::vector<unsigned char>();
std::vector<unsigned char> v(size + 1);
mpz_export(&v[0], &size, -1, 1, 0, 0, bn);
if (v[v.size()-2] & 0x80) {
if (mpz_sgn(bn)<0) {
v[v.size()-1] = 0x80;
} else {
v[v.size()-1] = 0x00;
}
} else {
v.pop_back();
if (mpz_sgn(bn)<0) {
v[v.size()-1] |= 0x80;
}
}
return v;
}
void CBigNum::SetDec(const std::string& str)
{
const char* psz = str.c_str();
mpz_set_str(bn, psz, 10);
}
bool CBigNum::SetHexBool(const std::string& str)
{
const char* psz = str.c_str();
int ret = 1 + mpz_set_str(bn, psz, 16);
return (bool) ret;
}
std::string CBigNum::ToString(int nBase) const
{
char* c_str = mpz_get_str(NULL, nBase, bn);
std::string str(c_str);
// Free c_str with the right free function:
void (*freefunc)(void *, size_t);
mp_get_memory_functions (NULL, NULL, &freefunc);
freefunc(c_str, strlen(c_str) + 1);
return str;
}
/**
* exponentiation this^e
* @param e the exponent
* @return
*/
CBigNum CBigNum::pow(const CBigNum& e) const
{
CBigNum ret;
long unsigned int ei = mpz_get_ui (e.bn);
mpz_pow_ui(ret.bn, bn, ei);
return ret;
}
/**
* modular multiplication: (this * b) mod m
* @param b operand
* @param m modulus
*/
CBigNum CBigNum::mul_mod(const CBigNum& b, const CBigNum& m) const
{
CBigNum ret;
mpz_mul (ret.bn, bn, b.bn);
mpz_mod (ret.bn, ret.bn, m.bn);
return ret;
}
/**
* modular exponentiation: this^e mod n
* @param e exponent
* @param m modulus
*/
CBigNum CBigNum::pow_mod(const CBigNum& e, const CBigNum& m) const
{
CBigNum ret;
if (e > BN_ZERO && mpz_odd_p(m.bn))
mpz_powm_sec (ret.bn, bn, e.bn, m.bn);
else
mpz_powm (ret.bn, bn, e.bn, m.bn);
return ret;
}
/**
* Calculates the inverse of this element mod m.
* i.e. i such this*i = 1 mod m
* @param m the modu
* @return the inverse
*/
CBigNum CBigNum::inverse(const CBigNum& m) const
{
CBigNum ret;
mpz_invert(ret.bn, bn, m.bn);
return ret;
}
/**
* Generates a random (safe) prime of numBits bits
* @param numBits the number of bits
* @param safe true for a safe prime
* @return the prime
*/
CBigNum CBigNum::generatePrime(const unsigned int numBits, bool safe)
{
CBigNum rand = randKBitBignum(numBits);
CBigNum prime;
mpz_nextprime(prime.bn, rand.bn);
return prime;
}
/**
* Calculates the greatest common divisor (GCD) of two numbers.
* @param m the second element
* @return the GCD
*/
CBigNum CBigNum::gcd( const CBigNum& b) const
{
CBigNum ret;
mpz_gcd(ret.bn, bn, b.bn);
return ret;
}
/**
* Miller-Rabin primality test on this element
* @param checks: optional, the number of Miller-Rabin tests to run
* default causes error rate of 2^-80.
* @return true if prime
*/
bool CBigNum::isPrime(const int checks) const
{
int ret = mpz_probab_prime_p(bn, checks);
return ret;
}
bool CBigNum::isOne() const
{
return mpz_cmp(bn, BN_ONE.bn) == 0;
}
bool CBigNum::operator!() const
{
return mpz_cmp(bn, BN_ZERO.bn) == 0;
}
CBigNum& CBigNum::operator+=(const CBigNum& b)
{
mpz_add(bn, bn, b.bn);
return *this;
}
CBigNum& CBigNum::operator-=(const CBigNum& b)
{
mpz_sub(bn, bn, b.bn);
return *this;
}
CBigNum& CBigNum::operator*=(const CBigNum& b)
{
mpz_mul(bn, bn, b.bn);
return *this;
}
CBigNum& CBigNum::operator<<=(unsigned int shift)
{
mpz_mul_2exp(bn, bn, shift);
return *this;
}
CBigNum& CBigNum::operator>>=(unsigned int shift)
{
mpz_div_2exp(bn, bn, shift);
return *this;
}
CBigNum& CBigNum::operator++()
{
// prefix operator
mpz_add(bn, bn, BN_ONE.bn);
return *this;
}
CBigNum& CBigNum::operator--()
{
// prefix operator
mpz_sub(bn, bn, BN_ONE.bn);
return *this;
}
|
#include "Game.hpp"
#include "Shared.hpp"
#include <algorithm>
using namespace std;
using namespace RakNet;
using namespace Values;
RakNetGUID Game::server;
Guarded<Game::CellRefs> Game::cellRefs;
Guarded<Player::CellContext> Game::cellContext;
Guarded<Game::UninitializedObjects> Game::uninitObj;
Guarded<Game::DeletedObjects> Game::deletedObj;
Guarded<Game::DeletedObjects> Game::deletedStatic;
Game::BaseRaces Game::baseRaces;
Game::Globals Game::globals;
Game::Weather Game::weather;
Game::PlayerBase Game::playerBase;
Game::SpawnFunc Game::spawnFunc;
Player::CellContext Game::spawnContext;
bool Game::GUIMode;
#ifdef VAULTMP_DEBUG
DebugInput<Game> Game::debug;
#endif
void Game::AdjustZAngle(float& Z, float diff)
{
Z += diff;
if (Z > 360.0f)
Z -= 360.0f;
else if (Z < 0.00f)
Z += 360.0f;
}
void Game::CommandHandler(unsigned int key, const vector<double>& info, double result, bool error)
{
Func opcode = getFrom<Func>(info.at(0));
if (!error)
{
#ifdef VAULTMP_DEBUG
//debug.print("Executing command ", hex, opcode, " on reference ", info.size() > 1 ? getFrom<unsigned int>(info.at(1)) : 0);
#endif
weak_ptr<Lockable> shared;
if (key)
{
switch (opcode)
{
case Func::CenterOnCell:
case Func::CenterOnWorld:
case Func::ForceRespawn:
case Func::PlaceAtMeHealthPercent:
shared = Lockable::Poll(key);
break;
default:
Lockable::Retrieve(key);
}
}
switch (opcode)
{
case Func::PlaceAtMeHealthPercent:
if (key)
FutureSet(shared, getFrom<unsigned int>(result));
break;
case Func::GetPosAngle:
{
float* data = getFrom<float*>(result);
GameFactory::Operate<Object, EXCEPTION_FACTORY_VALIDATED>(getFrom<unsigned int>(info.at(1)), [&info, data](FactoryObject& object) {
GetAngle(object, data[0], data[1], data[2]);
GetPos(object, data[3], data[4], data[5]);
});
break;
}
case Func::GetActivate:
{
if (!result)
break;
unsigned int refID = *getFrom<unsigned int*>(result);
GameFactory::Operate<Reference, RETURN_FACTORY_VALIDATED>({refID, PLAYER_REFERENCE}, [result](FactoryReferences& references) {
GetActivate(references[0], references[1]);
});
break;
}
case Func::GetFireWeapon:
GameFactory::Operate<Player, EXCEPTION_FACTORY_VALIDATED>(PLAYER_REFERENCE, [](FactoryPlayer& player) {
GetFireWeapon(player);
}); break;
case Func::GetActorState:
GameFactory::Operate<Actor, EXCEPTION_FACTORY_VALIDATED>(getFrom<unsigned int>(info.at(1)), [&info, result](FactoryActor& actor) mutable {
GetActorState(actor,
*reinterpret_cast<unsigned int*>(&result),
*reinterpret_cast<unsigned char*>(((unsigned) &result) + 4),
*reinterpret_cast<unsigned char*>(((unsigned) &result) + 6),
*reinterpret_cast<unsigned char*>(((unsigned) &result) + 5),
*reinterpret_cast<unsigned char*>(((unsigned) &result) + 7));
}); break;
case Func::GetParentCell:
GameFactory::Operate<Player, EXCEPTION_FACTORY_VALIDATED>(getFrom<unsigned int>(info.at(1)), [result](FactoryPlayer& player) {
GetParentCell(player, getFrom<unsigned int>(result));
}); break;
case Func::GetControl:
GameFactory::Operate<Player, EXCEPTION_FACTORY_VALIDATED>(PLAYER_REFERENCE, [&info, result](FactoryPlayer& player) {
GetControl(player, getFrom<int>(info.at(1)), result);
}); break;
case Func::GUIChat:
{
if (!result)
break;
GetMessage(getFrom<char*>(result));
break;
}
case Func::GUIMode:
{
if (!result)
break;
GetWindowMode(*getFrom<bool*>(result));
break;
}
case Func::GUIText:
{
if (!result)
break;
char* data = getFrom<char*>(result);
string name = data;
string text = data + name.length() + 1;
GetWindowText(move(name), move(text));
break;
}
case Func::GUIClick:
{
if (!result)
break;
GetWindowClick(getFrom<char*>(result));
break;
}
case Func::GUICheckbox:
{
if (!result)
break;
char* data = getFrom<char*>(result);
string name = data;
GetCheckboxSelected(name, *reinterpret_cast<bool*>(data + name.length() + 1));
break;
}
case Func::GUISelect:
{
if (!result)
break;
char* data = getFrom<char*>(result);
string name = data;
data += name.length() + 1;
vector<const char*> selections;
while (*data)
{
selections.emplace_back(data);
data += strlen(data) + 1;
}
GetListboxSelections(name, selections);
break;
}
case Func::GUIReturn:
{
if (!result)
break;
GetWindowReturn(getFrom<char*>(result));
break;
}
case Func::CenterOnCell:
case Func::CenterOnWorld:
case Func::ForceRespawn:
FutureSet(shared, true);
break;
case Func::SetPosFast:
case Func::SetAngle:
case Func::ForceActorValue:
case Func::DamageActorValue:
case Func::RestoreActorValue:
case Func::SetActorValue:
case Func::PlayGroup:
case Func::PlayIdle:
case Func::Kill:
case Func::MoveTo:
case Func::Enable:
case Func::Disable:
case Func::SetRestrained:
case Func::SetAlert:
case Func::SetForceSneak:
case Func::AddItemHealthPercent:
case Func::RemoveItem:
case Func::EquipItem:
case Func::UnequipItem:
case Func::FireWeapon:
case Func::EnablePlayerControls:
case Func::DisablePlayerControls:
case Func::SetINISetting:
case Func::Lock:
case Func::Unlock:
case Func::SetOwnership:
case Func::Activate:
case Func::GUICreateWindow:
case Func::GUICreateButton:
case Func::GUICreateText:
case Func::GUICreateEdit:
case Func::GUIRemoveWindow:
case Func::GUIPos:
case Func::GUISize:
case Func::GUIVisible:
case Func::GUILocked:
case Func::GUIMaxLen:
case Func::GUIValid:
case Func::GUICreateCheckbox:
case Func::GUICreateRadio:
case Func::GUIRadioGroup:
case Func::GUICreateListbox:
case Func::GUICreateItem:
case Func::GUIRemoveItem:
case Func::GUISelectChange:
case Func::GUISelectText:
case Func::GUISelectMulti:
case Func::SetGlobalValue:
case Func::MarkForDelete:
case Func::AgeRace:
case Func::MatchRace:
case Func::SexChange:
case Func::ForceWeather:
case Func::SetRefCount:
case Func::SetCurrentHealth:
case Func::UIMessage:
case Func::DisableControl:
case Func::EnableControl:
case Func::DisableKey:
case Func::EnableKey:
case Func::SetName:
case Func::PlaceAtMePrepare:
break;
default:
throw VaultException("Unhandled function %04hX", opcode).stacktrace();
}
}
else
{
#ifdef VAULTMP_DEBUG
debug.note("Command ", hex, static_cast<unsigned short>(opcode), " failed (");
for (const auto& value : info)
debug.note(*reinterpret_cast<const unsigned long long*>(&value), ", ");
debug.print(")");
#endif
switch (opcode)
{
case Func::PlaceAtMeHealthPercent:
PlaceAtMe(getFrom<unsigned int>(info.at(1)), getFrom<unsigned int>(info.at(2)), getFrom<unsigned int>(info.at(3)), key);
break;
default:
break;
}
}
}
NetworkResponse Game::Authenticate(const string& password)
{
return GameFactory::Operate<Player>(PLAYER_REFERENCE, [&password](Player* player) {
return NetworkResponse{Network::CreateResponse(
PacketFactory::Create<pTypes::ID_GAME_AUTH>(player->GetName(), password),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
};
});
}
void Game::Initialize()
{
cellRefs.Operate([](CellRefs& cellRefs) { cellRefs.clear(); });
cellContext.Operate([](Player::CellContext& cellContext) { cellContext = {{0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}}; });
uninitObj.Operate([](UninitializedObjects& uninitObj) { uninitObj.clear(); });
deletedObj.Operate([](DeletedObjects& deletedObj) { deletedObj.clear(); });
deletedStatic.Operate([](DeletedObjects& deletedStatic) { deletedStatic.clear(); });
baseRaces.clear();
globals.clear();
weather = 0x00000000;
playerBase = 0x00000000;
spawnFunc = SpawnFunc();
spawnContext = {{0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}};
GUIMode = false;
}
void Game::Startup()
{
NetworkID id = GameFactory::Lookup<Player>(PLAYER_REFERENCE);
static RawParameter self_ref(GameFactory::Operate<Player>(id, [](Player* player) {
return player->GetReferenceParam();
}));
Interface::Dynamic([]() {
SetINISetting("bSaveOnInteriorExteriorSwitch:GamePlay", "0");
SetINISetting("bSaveOnTravel:GamePlay", "0");
SetINISetting("bSaveOnWait:GamePlay", "0");
SetINISetting("bSaveOnRest:GamePlay", "0");
SetGlobalValue(Global_TimeScale, 0);
Interface::ExecuteCommand(Func::GetControl, {RawParameter(API::controls)});
ToggleControl(false, ControlCode_Quickload);
ToggleControl(false, ControlCode_VATS);
ToggleControl(false, ControlCode_Rest);
ToggleControl(false, ControlCode_MenuMode);
ToggleKey(false, ScanCode_Escape);
ToggleKey(false, ScanCode_Console);
EnablePlayerControls();
});
Interface::Setup([id]() {
Interface::SetupCommand(Func::GetPosAngle, {self_ref});
Interface::SetupCommand(Func::GetPosAngle, {self_ref});
Interface::SetupCommand(Func::GetPosAngle, {self_ref});
Interface::SetupCommand(Func::GetPosAngle, {self_ref});
Interface::SetupCommand(Func::GetPosAngle, {self_ref});
Interface::SetupCommand(Func::GetPosAngle, {Player::CreateFunctor(FLAG_ENABLED | FLAG_NOTSELF | FLAG_ALIVE)}, 30);
Interface::SetupCommand(Func::GetActorState, {Player::CreateFunctor(FLAG_SELF | FLAG_ENABLED), Player::CreateFunctor(FLAG_MOVCONTROLS, id)});
Interface::SetupCommand(Func::GetParentCell, {Player::CreateFunctor(FLAG_SELF | FLAG_ALIVE)}, 30);
});
while (!GameFactory::Operate<Player>(id, [](Player* player) {
return get<0>(player->GetGamePos());
})) this_thread::sleep_for(chrono::milliseconds(10));
}
template <typename T>
void Game::FutureSet(const weak_ptr<Lockable>& data, T&& t)
{
shared_ptr<Lockable> shared = data.lock();
Lockable* locked = shared.get();
if (locked == nullptr)
throw VaultException("Storage has expired").stacktrace();
Shared<T>* store = dynamic_cast<Shared<T>*>(locked);
if (store == nullptr)
throw VaultException("Storage is corrupted").stacktrace();
(**store) = forward<T>(t);
try
{
store->set_promise();
}
catch (...) {} // for resolving a weird bug with promise already satisfied, investigate
}
/*
void Game::AsyncDispatch(function<void()>&& func)
{
thread t(move(func));
t.detach();
}
void Game::JobDispatch(chrono::milliseconds&& time, function<void()>&& func)
{
Interface::PushJob(chrono::steady_clock::now() + time, move(func));
}
*/
void Game::DelayOrExecute(const FactoryObject& reference, function<void(unsigned int)>&& func, unsigned int key)
{
if (!reference->GetReference())
{
if (key)
Lockable::Retrieve(key);
return;
}
if (!IsInContext(reference->GetGameCell()))
{
if (key)
Lockable::Retrieve(key);
function<void()> task = bind(func, 0x00000000);
reference->Enqueue(task);
}
else
func(key);
}
void Game::LoadGame(string savegame)
{
static string last_savegame;
if (savegame.empty())
savegame = last_savegame;
else
{
Utils::RemoveExtension(savegame);
last_savegame = savegame;
}
auto store = make_shared<Shared<bool>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([&savegame, key]() {
Interface::ExecuteCommand(Func::Load, {RawParameter(savegame)}, key);
});
try
{
store->get_future(chrono::seconds(60));
}
catch (exception& e)
{
throw VaultException("Loading of savegame %s failed (%s)", savegame.c_str(), e.what()).stacktrace();
}
// ready state
}
void Game::CenterOnCell(const string& cell, bool spawn)
{
bool first = false;
if (spawn)
{
first = !spawnFunc.operator bool();
spawnFunc = bind(CenterOnCell, cell, false);
if (!first)
return;
}
auto store = make_shared<Shared<bool>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([&cell, key]() {
Interface::ExecuteCommand(Func::CenterOnCell, {RawParameter(cell)}, key);
});
try
{
store->get_future(chrono::seconds(60));
}
catch (exception& e)
{
throw VaultException("Loading of cell %s failed (%s)", cell.c_str(), e.what()).stacktrace();
}
if (first)
LoadEnvironment();
// ready state
}
void Game::CenterOnExterior(signed int x, signed int y, bool spawn)
{
bool first = false;
if (spawn)
{
first = !spawnFunc.operator bool();
spawnFunc = bind(CenterOnExterior, x, y, false);
if (!first)
return;
}
auto store = make_shared<Shared<bool>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([x, y, key]() {
Interface::ExecuteCommand(Func::CenterOnExterior, {RawParameter(x), RawParameter(y)}, key);
});
try
{
store->get_future(chrono::seconds(60));
}
catch (exception& e)
{
throw VaultException("Loading of cell (%d,%d) failed (%s)", x, y, e.what()).stacktrace();
}
if (first)
LoadEnvironment();
// ready state
}
void Game::CenterOnWorld(unsigned int baseID, signed int x, signed int y, bool spawn)
{
bool first = false;
if (spawn)
{
first = !spawnFunc.operator bool();
spawnFunc = bind(CenterOnWorld, baseID, x, y, false);
if (!first)
return;
}
auto store = make_shared<Shared<bool>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([baseID, x, y, key]() {
Interface::ExecuteCommand(Func::CenterOnWorld, {RawParameter(baseID), RawParameter(x), RawParameter(y)}, key);
});
try
{
store->get_future(chrono::seconds(60));
}
catch (exception& e)
{
throw VaultException("Loading of world (%08X,%d,%d) failed (%s)", baseID, x, y, e.what()).stacktrace();
}
if (first)
LoadEnvironment();
// ready state
}
void Game::SetINISetting(const string& key, const string& value)
{
Interface::Dynamic([&key, &value]() {
Interface::ExecuteCommand(Func::SetINISetting, {RawParameter(key), RawParameter(value)});
});
}
void Game::SetGlobalValue(unsigned int global, signed int value)
{
Interface::Dynamic([global, value]() {
Interface::ExecuteCommand(Func::SetGlobalValue, {RawParameter(global), RawParameter(value)});
});
}
void Game::LoadEnvironment()
{
for (const auto& global : globals)
SetGlobalValue(global.first, global.second);
if (weather)
SetWeather(weather);
uninitObj.Operate([](UninitializedObjects& uninitObj) {
uninitObj.clear();
});
deletedObj.Operate([](DeletedObjects& deletedObj) {
deletedStatic.Operate([&deletedObj](DeletedObjects& deletedStatic) {
deletedObj = deletedStatic;
});
for (unsigned int cell : spawnContext)
if (cell)
{
for (unsigned int refID : deletedObj[cell])
RemoveObject(refID);
deletedObj[cell].clear();
}
});
vector<NetworkID> reference = GameFactory::GetByType(ALL_OBJECTS);
for (NetworkID id : reference)
GameFactory::Operate<Object, EXCEPTION_FACTORY_VALIDATED>(id, [](FactoryObject& object) {
if (!object->IsPersistent() || object->GetReference() == PLAYER_REFERENCE)
{
cellRefs.Operate([&object](CellRefs& cellRefs) {
cellRefs[object->GetNetworkCell()][object.GetType()].erase(object->GetReference());
});
if (object->GetReference() != PLAYER_REFERENCE)
object->SetReference(0x00000000);
else
{
object->SetNetworkCell(spawnContext[0]);
object->SetGameCell(spawnContext[0]);
}
}
NewDispatch(object);
});
}
void Game::NewDispatch(FactoryObject& reference)
{
unsigned int type = reference.GetType();
switch (type)
{
case ID_OBJECT:
NewObject(reference);
break;
case ID_ITEM:
{
auto item = vaultcast_swap<Item>(move(reference)).get();
if (!item->GetItemContainer())
NewItem(item);
break;
}
case ID_CONTAINER:
NewContainer(vaultcast_swap<Container>(move(reference)).get());
break;
case ID_ACTOR:
NewActor(vaultcast_swap<Actor>(move(reference)).get());
break;
case ID_PLAYER:
NewPlayer(vaultcast_swap<Player>(move(reference)).get());
break;
default:
throw VaultException("Can't create object of unknown type %08X", type).stacktrace();
}
}
void Game::UIMessage(const string& message, unsigned char emoticon)
{
Interface::Dynamic([&message, emoticon]() {
Interface::ExecuteCommand(Func::UIMessage, {RawParameter(message), RawParameter(emoticon)});
});
}
void Game::ChatMessage(const string& message)
{
Interface::Dynamic([&message]() {
Interface::ExecuteCommand(Func::GUIChat, {RawParameter(message)});
});
}
void Game::NewObject(FactoryObject& reference)
{
if (IsInContext(reference->GetNetworkCell()))
NewObject_(reference);
else
{
reference->SetEnabled(false);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
sub.insert(reference->IsPersistent() ? sub.begin() : sub.end(), reference->GetNetworkID());
});
}
}
void Game::NewObject_(FactoryObject& reference)
{
reference->Release();
unsigned int refID = reference->GetReference();
if (!reference->GetReference())
{
auto store = make_shared<Shared<unsigned int>>();
unsigned int key = Lockable::Share(store);
float condition;
{
auto item = vaultcast<Item>(reference);
condition = item ? (item->GetItemCondition() / 100.0) : 1.00;
}
unsigned int baseID = reference->GetBase();
unsigned int anchorID = GetAnchor(reference->GetNetworkCell());
Interface::Dynamic([&reference, anchorID, baseID, condition, key]() {
const auto& angle = reference->GetAngle();
const auto& pos = reference->GetNetworkPos();
Interface::ExecuteCommand(Func::PlaceAtMePrepare, {RawParameter(get<0>(angle)), RawParameter(get<1>(angle)), RawParameter(get<2>(angle)), RawParameter(get<0>(pos)), RawParameter(get<1>(pos)), RawParameter(get<2>(pos))});
PlaceAtMe(anchorID, baseID, condition, 1, key);
});
NetworkID id = reference->GetNetworkID();
GameFactory::Free(reference);
try
{
refID = store->get_future(chrono::seconds(5));
}
catch (exception& e)
{
throw VaultException("Object creation with baseID %08X and NetworkID %llu failed (%s)", baseID, id, e.what()).stacktrace();
}
reference = GameFactory::Get<Object>(id).get();
reference->SetReference(refID);
}
reference->SetEnabled(true);
reference->SetGameCell(reference->GetNetworkCell());
cellRefs.Operate([&reference, refID](CellRefs& cellRefs) {
cellRefs[reference->GetNetworkCell()][reference.GetType()].insert(refID);
});
SetName(reference);
//if (reference->GetLockLevel() != Lock_Unlocked)
SetLock(reference);
if (reference->GetOwner())
SetOwner(reference);
// maybe more
}
void Game::NewVolatile(FactoryObject& reference, unsigned int baseID, float aX, float aY, float aZ)
{
if (!IsInContext(reference->GetNetworkCell()))
return;
Interface::Dynamic([&reference, baseID, aX, aY, aZ]() {
const auto& pos = reference->GetNetworkPos();
Interface::ExecuteCommand(Func::PlaceAtMePrepare, {RawParameter(aX), RawParameter(aY), RawParameter(aZ), RawParameter(get<0>(pos)), RawParameter(get<1>(pos)), RawParameter(get<2>(pos))});
PlaceAtMe(reference, baseID, 1.00f, 1);
});
}
void Game::NewItem(FactoryItem& reference)
{
NetworkID item = reference->GetNetworkID();
NetworkID container = reference->GetItemContainer();
if (container)
{
GameFactory::Free(reference);
GameFactory::Operate<Container, EXCEPTION_FACTORY_VALIDATED>(container, [item](FactoryContainer& container) {
container->AddItem(item);
GameFactory::Operate<Item, EXCEPTION_FACTORY_VALIDATED>(item, [&container](FactoryItem& item) {
AddItem(container, item);
if (item->GetItemEquipped() && vaultcast_test<Actor>(container))
GameFactory::Operate<Actor, EXCEPTION_FACTORY_VALIDATED>(container->GetNetworkID(), [&item](FactoryActor& actor) {
EquipItem(actor, item);
});
});
});
}
else
{
if (IsInContext(reference->GetNetworkCell()))
NewItem_(reference);
else
{
reference->SetEnabled(false);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
sub.insert(reference->IsPersistent() ? sub.begin() : sub.end(), reference->GetNetworkID());
});
}
}
}
void Game::NewItem_(FactoryItem& reference)
{
NetworkID id = reference->GetItemContainer();
if (id)
throw VaultException("Cannot create item %llu which is bound to a Container (%llu)", reference->GetNetworkID(), id).stacktrace();
NewObject_(reference);
SetRefCount(reference);
}
void Game::NewContainer(FactoryContainer& reference)
{
if (IsInContext(reference->GetNetworkCell()))
NewContainer_(reference);
else
{
reference->SetEnabled(false);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
sub.insert(reference->IsPersistent() ? sub.begin() : sub.end(), reference->GetNetworkID());
});
}
}
void Game::NewContainer_(FactoryContainer& reference)
{
NewObject_(reference);
auto items = GameFactory::Get<Item>(reference->GetItemList());
for (auto& item : items)
{
AddItem(reference, item.get());
if (item->GetItemEquipped() && vaultcast_test<Actor>(reference))
EquipItem(vaultcast<Actor>(reference).get(), item.get());
}
}
void Game::NewActor(FactoryActor& reference)
{
if (IsInContext(reference->GetNetworkCell()))
NewActor_(reference);
else
{
reference->SetEnabled(false);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
sub.insert(reference->IsPersistent() ? sub.begin() : sub.end(), reference->GetNetworkID());
});
}
}
void Game::NewActor_(FactoryActor& reference)
{
NewContainer_(reference);
for (const auto& value : API::values)
{
SetActorValue(reference, true, value.second);
SetActorValue(reference, false, value.second);
}
SetActorRace(reference, reference->GetActorAge()); // FIXME - AgeRace is a delta, do only once per base (redo on respawn). sucks a bit
SetActorFemale(reference);
if (reference->GetReference() != PLAYER_REFERENCE)
{
SetRestrained(reference, true);
if (!reference->GetActorDead())
{
if (reference->GetActorAlerted())
SetActorAlerted(reference);
if (reference->GetActorSneaking())
SetActorSneaking(reference);
if (reference->GetActorMovingAnimation() != AnimGroup_Idle)
SetActorMovingAnimation(reference);
if (reference->GetActorWeaponAnimation() != AnimGroup_Idle)
SetActorWeaponAnimation(reference);
}
else
KillActor(reference);
}
}
void Game::NewPlayer(FactoryPlayer& reference)
{
if (IsInContext(reference->GetNetworkCell()) || reference->GetReference() == PLAYER_REFERENCE)
NewPlayer_(reference);
else
{
reference->SetEnabled(false);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
sub.insert(reference->IsPersistent() ? sub.begin() : sub.end(), reference->GetNetworkID());
});
}
}
void Game::NewPlayer_(FactoryPlayer& reference)
{
NewActor_(reference);
// ...
}
void Game::RemoveObject(const FactoryObject& reference)
{
if (!reference->GetReference())
return;
if (IsInContext(reference->GetGameCell()))
{
if (reference->SetEnabled(false))
ToggleEnabled(reference);
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::MarkForDelete, {reference->GetReferenceParam()});
});
}
else
deletedObj.Operate([&reference](DeletedObjects& deletedObj) {
deletedObj[reference->GetGameCell()].emplace_back(reference->GetReference());
});
cellRefs.Operate([&reference](CellRefs& cellRefs) {
cellRefs[reference->GetNetworkCell()][reference.GetType()].erase(reference->GetReference());
});
}
void Game::RemoveObject(unsigned int refID)
{
ToggleEnabled(refID, false);
Interface::Dynamic([refID]() {
Interface::ExecuteCommand(Func::MarkForDelete, {RawParameter(refID)});
});
}
void Game::NewWindow(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateWindow, {RawParameter(reference->GetLabel())});
}
SetWindowPos(reference);
SetWindowSize(reference);
SetWindowVisible(reference);
SetWindowLocked(reference);
SetWindowText(reference);
});
}
void Game::NewButton(const FactoryButton& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateButton, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel())});
}
NewWindow(reference);
});
}
void Game::NewText(const FactoryText& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateText, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel())});
}
NewWindow(reference);
});
}
void Game::NewEdit(const FactoryEdit& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateEdit, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel())});
}
NewWindow(reference);
SetEditMaxLength(reference);
SetEditValidation(reference);
});
}
void Game::NewCheckbox(const FactoryCheckbox& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateCheckbox, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel())});
}
NewWindow(reference);
SetCheckboxSelected(reference);
});
}
void Game::NewRadioButton(const FactoryRadioButton& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateRadio, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel()), RawParameter(reference->GetGroup())});
}
NewWindow(reference);
SetRadioButtonSelected(reference);
});
}
void Game::NewListItem(FactoryListItem& reference)
{
NetworkID item = reference->GetNetworkID();
NetworkID list = reference->GetItemContainer();
GameFactory::Free(reference);
GameFactory::Operate<List>(list, [item](List* list) {
list->AddItem(item);
GameFactory::Operate<ListItem>(item, [list](ListItem* listitem) {
Interface::Dynamic([listitem, list]() {
Interface::ExecuteCommand(Func::GUICreateItem, {RawParameter(list->GetLabel()), RawParameter(listitem->GetNetworkID()), RawParameter(listitem->GetText())});
});
});
});
}
void Game::NewList(const FactoryList& reference)
{
if (!reference->GetParentWindow())
throw VaultException("Window %llu requires a parent", reference->GetNetworkID());
Interface::Dynamic([&reference]() {
if (reference->GetLabel().empty())
{
reference->SetLabel(Utils::toString(reference->GetNetworkID()));
Interface::ExecuteCommand(Func::GUICreateListbox, {RawParameter(reference->GetParentWindow()), RawParameter(reference->GetLabel())});
}
NewWindow(reference);
SetListMultiSelect(reference);
});
GameFactory::Operate<ListItem>(reference->GetItemList(), [&reference](ListItems& listitems) {
Interface::Dynamic([&listitems, &reference]() {
for (auto listitem : listitems)
Interface::ExecuteCommand(Func::GUICreateItem, {RawParameter(reference->GetLabel()), RawParameter(listitem->GetNetworkID()), RawParameter(listitem->GetText())});
});
});
}
void Game::PlaceAtMe(const FactoryObject& reference, unsigned int baseID, float condition, unsigned int count, unsigned int key)
{
PlaceAtMe(reference->GetReference(), baseID, condition, count, key);
}
void Game::PlaceAtMe(unsigned int refID, unsigned int baseID, float condition, unsigned int count, unsigned int key)
{
Interface::Dynamic([refID, baseID, condition, count, key]() {
Interface::ExecuteCommand(Func::PlaceAtMeHealthPercent, {RawParameter(refID), RawParameter(baseID), RawParameter(condition), RawParameter(count)}, key);
});
}
void Game::ToggleEnabled(const FactoryObject& reference)
{
ToggleEnabled(reference->GetReference(), reference->GetEnabled());
}
void Game::ToggleEnabled(unsigned int refID, bool enabled)
{
Interface::Dynamic([refID, enabled]() {
if (enabled)
Interface::ExecuteCommand(Func::Enable, {RawParameter(refID), RawParameter(true)});
else
Interface::ExecuteCommand(Func::Disable, {RawParameter(refID), RawParameter(false)});
});
}
void Game::DestroyObject(FactoryObject& reference, bool silent)
{
NetworkID id = reference->GetNetworkID();
NetworkID container = GameFactory::Operate<Item, RETURN_VALIDATED>(id, [](Item* item) {
return item->GetItemContainer();
});
if (container)
{
GameFactory::Free(reference);
GameFactory::Operate<Container, EXCEPTION_FACTORY_VALIDATED>(container, [id, silent](FactoryContainer& container) {
container->RemoveItem(id);
GameFactory::Operate<Item>(id, [&container, silent](Item* item) {
RemoveItem(container, item->GetBase(), item->GetItemCount(), silent);
// Game always removes equipped item first - workaround (is this really always the case?)
NetworkID equipped = container->IsEquipped(item->GetBase());
if (equipped && vaultcast_test<Actor>(container))
GameFactory::Operate<Actor, EXCEPTION_FACTORY_VALIDATED>(container->GetNetworkID(), [equipped](FactoryActor& actor) {
GameFactory::Operate<Item>(equipped, [&actor](Item* item) {
EquipItem(actor, item->GetBase(), item->GetItemCondition(), false, item->GetItemStick());
});
});
});
GameFactory::Destroy(id);
});
}
else
{
RemoveObject(reference);
uninitObj.Operate([&reference](UninitializedObjects& uninitObj) {
auto& sub = uninitObj[reference->GetNetworkCell()];
auto it = find(sub.begin(), sub.end(), reference->GetNetworkID());
if (it != sub.end())
sub.erase(it);
});
if (reference->IsPersistent())
deletedStatic.Operate([&reference](DeletedObjects& deletedStatic) {
deletedStatic[reference->GetNetworkCell()].emplace_back(reference->GetReference());
});
GameFactory::Destroy(reference);
}
}
void Game::DestroyWindow(FactoryWindow& reference)
{
GameFactory::Operate<List, RETURN_VALIDATED>(reference->GetNetworkID(), [](List* list) {
GameFactory::Operate<ListItem>(list->GetItemList(), [list](ListItems& items) {
Interface::Dynamic([&items, list]() {
for (auto item : items)
{
list->RemoveItem(item->GetNetworkID());
Interface::ExecuteCommand(Func::GUIRemoveItem, {RawParameter(list->GetLabel()), RawParameter(item->GetNetworkID())});
}
});
});
});
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIRemoveWindow, {RawParameter(reference->GetLabel())});
});
GameFactory::Destroy(reference);
}
void Game::DestroyListItem(FactoryListItem& reference)
{
NetworkID item = reference->GetNetworkID();
NetworkID list = reference->GetItemContainer();
GameFactory::Free(reference);
GameFactory::Operate<List>(list, [item](List* list) {
list->RemoveItem(item);
GameFactory::Operate<ListItem>(item, [list](ListItem* listitem) {
Interface::Dynamic([listitem, list]() {
Interface::ExecuteCommand(Func::GUIRemoveItem, {RawParameter(list->GetLabel()), RawParameter(listitem->GetNetworkID())});
});
});
GameFactory::Destroy(item);
});
}
unsigned int Game::GetBase(unsigned int refID)
{
auto store = make_shared<Shared<unsigned int>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([refID, key]() {
Interface::ExecuteCommand(Func::GetBaseObject, {RawParameter(refID)}, key);
});
unsigned int baseID;
try
{
baseID = store->get_future(chrono::seconds(5));
}
catch (exception& e)
{
throw VaultException("Obtaining of baseID of refID %08X (%s)", refID, e.what()).stacktrace();
}
return baseID;
}
void Game::SetName(const FactoryObject& reference)
{
const string& name = reference->GetName();
auto* object = reference.operator->();
DelayOrExecute(reference, [object, name](unsigned int) {
Interface::Dynamic([object, &name]() {
Interface::ExecuteCommand(Func::SetName, {object->GetReferenceParam(), RawParameter(name)});
});
}, 0);
}
void Game::SetRestrained(const FactoryActor& reference, bool restrained)
{
Interface::Dynamic([&reference, restrained]() {
Interface::ExecuteCommand(Func::SetRestrained, {reference->GetReferenceParam(), RawParameter(restrained)});
});
}
void Game::Activate(const FactoryReference& reference, const FactoryReference& actor)
{
Interface::Dynamic([&reference, &actor]() {
Interface::ExecuteCommand(Func::Activate, {reference->GetReferenceParam(), actor->GetReferenceParam()});
});
}
void Game::SetPos(const FactoryObject& reference)
{
if (!reference->HasValidCoordinates())
return;
Interface::Dynamic([&reference]() {
const auto& pos = reference->GetNetworkPos();
Lockable* key = reference->SetGamePos(pos);
Interface::ExecuteCommand(Func::SetPosFast, {reference->GetReferenceParam(), RawParameter(get<0>(pos)), RawParameter(get<1>(pos)), RawParameter(get<2>(pos))}, key ? key->Lock() : 0);
});
}
void Game::SetAngle(const FactoryObject& reference)
{
Interface::Dynamic([&reference]() {
const auto& angle = reference->GetAngle();
Interface::ExecuteCommand(Func::SetAngle, {reference->GetReferenceParam(), RawParameter(Axis_X), RawParameter(get<0>(angle))});
float value = get<2>(angle);
auto actor = vaultcast<Actor>(reference);
if (actor)
{
if (actor->GetActorMovingXY() == 0x01)
AdjustZAngle(value, -45.0f);
else if (actor->GetActorMovingXY() == 0x02)
AdjustZAngle(value, 45.0f);
}
Interface::ExecuteCommand(Func::SetAngle, {reference->GetReferenceParam(), RawParameter(Axis_Z), RawParameter(value)});
});
}
void Game::MoveTo(const FactoryObject& reference, const FactoryObject& object, bool cell, unsigned int key)
{
Interface::Dynamic([&reference, &object, cell, key]() {
ParamContainer param_MoveTo{reference->GetReferenceParam(), object->GetReferenceParam()};
if (cell)
{
const auto& pos_1 = reference->GetNetworkPos();
const auto& pos_2 = object->GetNetworkPos();
param_MoveTo.emplace_back(get<0>(pos_1) - get<0>(pos_2));
param_MoveTo.emplace_back(get<1>(pos_1) - get<1>(pos_2));
param_MoveTo.emplace_back(get<2>(pos_1) - get<2>(pos_2));
}
Interface::ExecuteCommand(Func::MoveTo, move(param_MoveTo), key);
});
}
void Game::SetLock(const FactoryObject& reference, unsigned int key)
{
auto* object = reference.operator->();
unsigned int lock = object->GetLockLevel();
if (lock == Lock_Broken) // workaround: can't set lock to broken, so set it to impossible
lock = Lock_Impossible;
DelayOrExecute(reference, [object, lock](unsigned int key) {
Interface::Dynamic([object, lock, key]() {
if (lock != Lock_Unlocked)
Interface::ExecuteCommand(Func::Lock, {object->GetReferenceParam(), RawParameter(lock)}, key);
else
Interface::ExecuteCommand(Func::Unlock, {object->GetReferenceParam()}, key);
});
}, key);
}
void Game::SetOwner(const FactoryObject& reference, unsigned int key)
{
auto* object = reference.operator->();
unsigned int owner = object->GetOwner();
if (owner == playerBase)
owner = PLAYER_BASE;
DelayOrExecute(reference, [object, owner](unsigned int key) {
Interface::Dynamic([object, owner, key]() {
Interface::ExecuteCommand(Func::SetOwnership, {object->GetReferenceParam(), RawParameter(owner)}, key);
});
}, key);
}
void Game::SetActorValue(const FactoryActor& reference, bool base, unsigned char index, unsigned int key)
{
auto* actor = reference.operator->();
float value = base ? actor->GetActorBaseValue(index) : actor->GetActorValue(index);
DelayOrExecute(reference, [actor, base, index, value](unsigned int key) {
Interface::Dynamic([actor, base, index, value, key]() {
if (base)
Interface::ExecuteCommand(Func::SetActorValue, {actor->GetReferenceParam(), RawParameter(index), RawParameter(value)}, key);
else
Interface::ExecuteCommand(Func::ForceActorValue, {actor->GetReferenceParam(), RawParameter(index), RawParameter(value)}, key);
});
}, key);
}
void Game::DamageActorValue(const FactoryActor& reference, unsigned char index, float value, unsigned int key)
{
auto* actor = reference.operator->();
DelayOrExecute(reference, [actor, index, value](unsigned int key) {
Interface::Dynamic([actor, index, value, key]() {
Interface::ExecuteCommand(Func::DamageActorValue, {actor->GetReferenceParam(), RawParameter(index), RawParameter(value)}, key);
});
}, key);
}
void Game::RestoreActorValue(const FactoryActor& reference, unsigned char index, float value, unsigned int key)
{
auto* actor = reference.operator->();
DelayOrExecute(reference, [actor, index, value](unsigned int key) {
Interface::Dynamic([actor, index, value, key]() {
Interface::ExecuteCommand(Func::RestoreActorValue, {actor->GetReferenceParam(), RawParameter(index), RawParameter(value)}, key);
});
}, key);
}
void Game::SetActorSneaking(const FactoryActor& reference, unsigned int key)
{
auto* actor = reference.operator->();
bool sneaking = actor->GetActorSneaking();
DelayOrExecute(reference, [actor, sneaking](unsigned int key) {
Interface::Dynamic([actor, sneaking, key]() {
Interface::ExecuteCommand(Func::SetForceSneak, {actor->GetReferenceParam(), RawParameter(sneaking)}, key);
});
}, key);
}
void Game::SetActorAlerted(const FactoryActor& reference, unsigned int key)
{
auto* actor = reference.operator->();
bool alerted = actor->GetActorAlerted();
DelayOrExecute(reference, [actor, alerted](unsigned int key) {
Interface::Dynamic([actor, alerted, key]() {
Interface::ExecuteCommand(Func::SetAlert, {actor->GetReferenceParam(), RawParameter(alerted)}, key);
});
}, key);
}
void Game::SetActorAnimation(const FactoryActor& reference, unsigned char anim, unsigned int key)
{
Interface::Dynamic([&reference, anim, key]() {
Interface::ExecuteCommand(Func::PlayGroup, {reference->GetReferenceParam(), RawParameter(anim), RawParameter(true)}, key);
});
}
void Game::SetActorMovingAnimation(const FactoryActor& reference, unsigned int key)
{
SetActorAnimation(reference, reference->GetActorMovingAnimation(), key);
}
void Game::SetActorWeaponAnimation(const FactoryActor& reference, unsigned int key)
{
SetActorAnimation(reference, reference->GetActorWeaponAnimation(), key);
}
void Game::SetActorIdleAnimation(const FactoryActor& reference, const string& anim, unsigned int key)
{
Interface::Dynamic([&reference, &anim, key]() {
Interface::ExecuteCommand(Func::PlayIdle, {reference->GetReferenceParam(), RawParameter(anim)}, key);
});
}
void Game::SetActorRace(const FactoryActor& reference, signed int delta_age, unsigned int key)
{
auto* actor = reference.operator->();
unsigned int race = actor->GetActorRace();
DelayOrExecute(reference, [actor, race, delta_age](unsigned int key) {
unsigned int baseID = actor->GetBase();
// set only once per base
if (baseRaces[baseID] == race || race == UINT_MAX) // creature test
{
if (key)
Lockable::Retrieve(key);
return;
}
baseRaces[baseID] = race;
Interface::Dynamic([actor, race, delta_age, key]() {
Interface::ExecuteCommand(Func::MatchRace, {actor->GetReferenceParam(), RawParameter(race)}, delta_age ? 0 : key);
if (delta_age)
Interface::ExecuteCommand(Func::AgeRace, {actor->GetReferenceParam(), RawParameter(delta_age)}, key);
});
}, key);
}
void Game::SetActorFemale(const FactoryActor& reference, unsigned int key)
{
auto* actor = reference.operator->();
bool female = actor->GetActorFemale();
DelayOrExecute(reference, [actor, female](unsigned int key) {
if (actor->GetActorRace() == UINT_MAX) // creature test
{
if (key)
Lockable::Retrieve(key);
return;
}
Interface::Dynamic([actor, female, key]() {
Interface::ExecuteCommand(Func::SexChange, {actor->GetReferenceParam(), RawParameter(female)}, key);
});
}, key);
}
void Game::KillActor(const FactoryActor& reference, unsigned int key)
{
auto* actor = reference.operator->();
unsigned short limbs = reference->GetActorLimbs();
signed char cause = reference->GetActorDeathCause();
DelayOrExecute(reference, [actor, limbs, cause](unsigned int key) {
Interface::Dynamic([actor, limbs, cause, key]() {
// maybe add valid killer later
if (limbs)
{
unsigned int j = 0;
for (unsigned int i = 1; i <= limbs; i <<= 1, ++j)
if (limbs & i)
Interface::ExecuteCommand(Func::Kill, {actor->GetReferenceParam(), actor->GetReferenceParam(), RawParameter(j), RawParameter(cause)}, ((i << 1) > limbs) ? key : 0x00);
}
else
Interface::ExecuteCommand(Func::Kill, {actor->GetReferenceParam(), actor->GetReferenceParam(), RawParameter(Limb_None), RawParameter(cause)}, key);
});
}, key);
}
void Game::FireWeapon(const FactoryActor& reference, unsigned int weapon, unsigned int key)
{
Interface::Dynamic([&reference, weapon, key]() {
Interface::ExecuteCommand(Func::FireWeapon, {reference->GetReferenceParam(), RawParameter(weapon)}, key);
});
}
void Game::AddItem(const FactoryContainer& reference, const FactoryItem& item, unsigned int key)
{
AddItem(reference, item->GetBase(), item->GetItemCount(), item->GetItemCondition(), item->GetItemSilent(), key);
}
void Game::AddItem(const FactoryContainer& reference, unsigned int baseID, unsigned int count, float condition, bool silent, unsigned int key)
{
auto* container = reference.operator->();
DelayOrExecute(reference, [container, baseID, count, condition, silent](unsigned int key) {
Interface::Dynamic([container, baseID, count, condition, silent, key]() {
Interface::ExecuteCommand(Func::AddItemHealthPercent, {container->GetReferenceParam(), RawParameter(baseID), RawParameter(count), RawParameter(condition / 100), RawParameter(silent)}, key);
});
}, key);
}
void Game::RemoveItem(const FactoryContainer& reference, const FactoryItem& item, unsigned int key)
{
RemoveItem(reference, item->GetBase(), item->GetItemCount(), item->GetItemSilent(), key);
}
void Game::RemoveItem(const FactoryContainer& reference, unsigned int baseID, unsigned int count, bool silent, unsigned int key)
{
auto* container = reference.operator->();
DelayOrExecute(reference, [container, baseID, count, silent](unsigned int key) {
Interface::Dynamic([container, baseID, count, silent, key]() {
Interface::ExecuteCommand(Func::RemoveItem, {container->GetReferenceParam(), RawParameter(baseID), RawParameter(count), RawParameter(silent)}, key);
});
}, key);
}
void Game::SetRefCount(const FactoryItem& reference, unsigned int key)
{
auto* item = reference.operator->();
unsigned int count = item->GetItemCount();
DelayOrExecute(reference, [item, count](unsigned int key) {
Interface::Dynamic([item, count, key]() {
Interface::ExecuteCommand(Func::SetRefCount, {item->GetReferenceParam(), RawParameter(count)}, key);
});
}, key);
}
void Game::SetCurrentHealth(const FactoryItem& reference, unsigned int health, unsigned int key)
{
auto* item = reference.operator->();
DelayOrExecute(reference, [item, health](unsigned int key) {
Interface::Dynamic([item, health, key]() {
Interface::ExecuteCommand(Func::SetCurrentHealth, {item->GetReferenceParam(), RawParameter(health)}, key);
});
}, key);
}
void Game::EquipItem(const FactoryActor& reference, const FactoryItem& item, unsigned int key)
{
EquipItem(reference, item->GetBase(), item->GetItemCondition(), item->GetItemSilent(), item->GetItemStick(), key);
}
void Game::EquipItem(const FactoryActor& reference, unsigned int baseID, float condition, bool silent, bool stick, unsigned int key)
{
auto* actor = reference.operator->();
DelayOrExecute(reference, [actor, baseID, condition, silent, stick](unsigned int key) {
Interface::Dynamic([actor, baseID, condition, silent, stick, key]() {
Interface::ExecuteCommand(Func::EquipItem, {actor->GetReferenceParam(), RawParameter(baseID), RawParameter(stick), RawParameter(silent)}, key);
});
// Add: adjust condition
}, key);
}
void Game::UnequipItem(const FactoryActor& reference, const FactoryItem& item, unsigned int key)
{
UnequipItem(reference, item->GetBase(), item->GetItemSilent(), item->GetItemStick(), key);
}
void Game::UnequipItem(const FactoryActor& reference, unsigned int baseID, bool silent, bool stick, unsigned int key)
{
auto* actor = reference.operator->();
DelayOrExecute(reference, [actor, baseID, silent, stick](unsigned int key) {
Interface::Dynamic([actor, baseID, silent, stick, key]() {
Interface::ExecuteCommand(Func::UnequipItem, {actor->GetReferenceParam(), RawParameter(baseID), RawParameter(stick), RawParameter(silent)}, key);
});
}, key);
}
void Game::SetWindowPos(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIPos, {RawParameter(reference->GetLabel()), RawParameter(get<0>(reference->GetPos())), RawParameter(get<1>(reference->GetPos())), RawParameter(get<2>(reference->GetPos())), RawParameter(get<3>(reference->GetPos()))});
});
}
void Game::SetWindowSize(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUISize, {RawParameter(reference->GetLabel()), RawParameter(get<0>(reference->GetSize())), RawParameter(get<1>(reference->GetSize())), RawParameter(get<2>(reference->GetSize())), RawParameter(get<3>(reference->GetSize()))});
});
}
void Game::SetWindowVisible(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIVisible, {RawParameter(reference->GetLabel()), RawParameter(reference->GetVisible())});
});
}
void Game::SetWindowLocked(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUILocked, {RawParameter(reference->GetLabel()), RawParameter(reference->GetLocked())});
});
}
void Game::SetWindowText(const FactoryWindow& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIText, {RawParameter(reference->GetLabel()), RawParameter(reference->GetText())});
});
}
void Game::SetEditMaxLength(const FactoryEdit& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIMaxLen, {RawParameter(reference->GetLabel()), RawParameter(reference->GetMaxLength())});
});
}
void Game::SetEditValidation(const FactoryEdit& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIValid, {RawParameter(reference->GetLabel()), RawParameter(reference->GetValidation())});
});
}
void Game::SetCheckboxSelected(const FactoryCheckbox& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUICheckbox, {RawParameter(reference->GetLabel()), RawParameter(reference->GetSelected())});
});
}
void Game::SetRadioButtonSelected(const FactoryRadioButton& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUICheckbox, {RawParameter(reference->GetLabel()), RawParameter(reference->GetSelected())});
});
}
void Game::SetRadioButtonGroup(const FactoryRadioButton& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUIRadioGroup, {RawParameter(reference->GetLabel()), RawParameter(reference->GetGroup())});
});
}
void Game::SetListItemSelected(const FactoryListItem& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUISelectChange, {RawParameter(reference->GetItemContainer()), RawParameter(reference->GetNetworkID()), RawParameter(reference->GetSelected())});
});
}
void Game::SetListItemText(const FactoryListItem& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUISelectText, {RawParameter(reference->GetItemContainer()), RawParameter(reference->GetNetworkID()), RawParameter(reference->GetText())});
});
}
void Game::SetListMultiSelect(const FactoryList& reference)
{
Interface::Dynamic([&reference]() {
Interface::ExecuteCommand(Func::GUISelectMulti, {RawParameter(reference->GetLabel()), RawParameter(reference->GetMultiSelect())});
});
}
void Game::SetWindowMode()
{
Interface::Dynamic([]() {
if (GUIMode)
{
DisablePlayerControls(true, true, true, false);
ToggleControl(false, ControlCode_TogglePOV);
ToggleControl(false, ControlCode_Crouch);
}
else
{
EnablePlayerControls();
ToggleControl(true, ControlCode_TogglePOV);
ToggleControl(true, ControlCode_Crouch);
}
Interface::ExecuteCommand(Func::GUIMode, {RawParameter(GUIMode)});
});
}
void Game::EnablePlayerControls(bool movement, bool pipboy, bool fighting, bool pov, bool looking, bool rollover, bool sneaking)
{
Interface::Dynamic([movement, pipboy, fighting, pov, looking, rollover, sneaking]() {
Interface::ExecuteCommand(Func::EnablePlayerControls, {RawParameter(movement), RawParameter(pipboy), RawParameter(fighting), RawParameter(pov), RawParameter(looking), RawParameter(rollover), RawParameter(sneaking)});
});
}
void Game::DisablePlayerControls(bool movement, bool pipboy, bool fighting, bool pov, bool looking, bool rollover, bool sneaking)
{
Interface::Dynamic([movement, pipboy, fighting, pov, looking, rollover, sneaking]() {
Interface::ExecuteCommand(Func::DisablePlayerControls, {RawParameter(movement), RawParameter(pipboy), RawParameter(fighting), RawParameter(pov), RawParameter(looking), RawParameter(rollover), RawParameter(sneaking)});
});
}
void Game::ToggleKey(bool enabled, unsigned int scancode)
{
Interface::Dynamic([enabled, scancode]() {
if (enabled)
Interface::ExecuteCommand(Func::EnableKey, {RawParameter(scancode)});
else
Interface::ExecuteCommand(Func::DisableKey, {RawParameter(scancode)});
});
}
void Game::ToggleControl(bool enabled, unsigned int control)
{
Interface::Dynamic([enabled, control]() {
if (enabled)
Interface::ExecuteCommand(Func::EnableControl, {RawParameter(control)});
else
Interface::ExecuteCommand(Func::DisableControl, {RawParameter(control)});
});
}
void Game::SetWeather(unsigned int weather)
{
Interface::Dynamic([weather]() {
Interface::ExecuteCommand(Func::ForceWeather, {RawParameter(weather), RawParameter(1)});
});
}
void Game::ForceRespawn()
{
auto store = make_shared<Shared<bool>>();
unsigned int key = Lockable::Share(store);
Interface::Dynamic([key]() {
Interface::ExecuteCommand(Func::ForceRespawn, {}, key);
});
try
{
store->get_future(chrono::seconds(5));
}
catch (exception& e)
{
throw VaultException("Respawning failed (%s)", e.what()).stacktrace();
}
}
bool Game::IsInContext(unsigned int cell)
{
if (!cell)
return false;
return cellContext.Operate([cell](Player::CellContext& cellContext) {
return find(cellContext.begin(), cellContext.end(), cell) != cellContext.end();
});
}
vector<unsigned int> Game::GetContext(unsigned int type)
{
return cellRefs.Operate([type](CellRefs& cellRefs) {
return cellContext.Operate([&cellRefs, type](Player::CellContext& cellContext) {
vector<unsigned int> result;
for (unsigned int cell : cellContext)
if (cell)
for (const auto& refs : cellRefs[cell])
if (refs.first & type)
result.insert(result.end(), refs.second.begin(), refs.second.end());
return result;
});
});
}
unsigned int Game::GetAnchor(unsigned int cell)
{
return cellRefs.Operate([cell](CellRefs& cellRefs) {
const auto& refs = cellRefs[cell];
unsigned int anchorID = [&refs]() {
for (const auto& subrefs : refs)
if (!subrefs.second.empty())
return *subrefs.second.begin();
return 0x00000000u;
}();
if (!anchorID)
throw VaultException("No anchor reference in cell %08X", cell).stacktrace();
return anchorID;
});
}
void Game::net_SetName(const FactoryObject& reference, const string& name)
{
bool result = static_cast<bool>(reference->SetName(name));
if (result)
SetName(reference);
}
void Game::net_SetPos(const FactoryObject& reference, float X, float Y, float Z)
{
bool result = static_cast<bool>(reference->SetNetworkPos(tuple<float, float, float>{X, Y, Z}));
if (result && reference->GetEnabled())
{
auto actor = vaultcast<Actor>(reference); // maybe we should consider items, too (they have physics)
//if (!actor || (!reference->IsNearPoint(reference->GetNetworkPos(Axis_X), reference->GetNetworkPos(Axis_Y), reference->GetNetworkPos(Axis_Z), 50.0)) || actor->IsActorJumping() || actor->GetReference() == PLAYER_REFERENCE)
SetPos(reference);
}
}
void Game::net_SetAngle(const FactoryObject& reference, float X, float Y, float Z)
{
bool result = static_cast<bool>(reference->SetAngle(tuple<float, float, float>{X, Y, Z}));
if (result && reference->GetEnabled())
{
SetAngle(reference);
auto actor = vaultcast<Actor>(reference);
if (actor)
{
static map<AnimationGroups, array<AnimationGroups, 2>> reactions = {
{AnimGroup_AimIS, {{AnimGroup_AimISDown, AnimGroup_AimISUp}}},
{AnimGroup_AttackSpin2, {{AnimGroup_AimUp, AnimGroup_AimDown}}},
};
auto anim = static_cast<AnimationGroups>(actor->GetActorWeaponAnimation());
if (reactions.count(anim))
{
SetActorAnimation(actor.get(), reactions[anim][0]);
SetActorAnimation(actor.get(), reactions[anim][1]);
}
}
}
}
void Game::net_SetCell(FactoryObject& reference, FactoryPlayer& player, unsigned int cell, float X, float Y, float Z)
{
unsigned int old_cell = reference->GetNetworkCell();
reference->SetNetworkCell(cell);
bool result = false;
if (X || Y || Z)
result = static_cast<bool>(reference->SetNetworkPos(tuple<float, float, float>{X, Y, Z}));
if (reference->GetReference())
{
if (reference != player)
{
if (IsInContext(cell))
{
if (IsInContext(old_cell))
{
cellRefs.Operate([&reference, old_cell, cell](CellRefs& cellRefs) {
cellRefs[old_cell][reference.GetType()].erase(reference->GetReference());
cellRefs[cell][reference.GetType()].insert(reference->GetReference());
});
if (reference->SetEnabled(true))
ToggleEnabled(reference);
if (reference->SetGameCell(cell))
MoveTo(reference, player, true);
}
else
{
cellRefs.Operate([&reference, old_cell](CellRefs& cellRefs) {
cellRefs[old_cell][reference.GetType()].erase(reference->GetReference());
});
RemoveObject(reference);
reference->SetReference(0x00000000);
reference->SetEnabled(false);
GameFactory::Free(player);
NewDispatch(reference);
}
}
else
{
cellRefs.Operate([&reference, old_cell](CellRefs& cellRefs) {
cellRefs[old_cell][reference.GetType()].erase(reference->GetReference());
});
uninitObj.Operate([&reference, cell](UninitializedObjects& uninitObj) {
uninitObj[cell].push_back(reference->GetNetworkID());
});
RemoveObject(reference);
reference->SetReference(0x00000000);
reference->SetEnabled(false);
}
}
else if (result)
SetPos(player);
}
else
{
bool context = IsInContext(cell);
uninitObj.Operate([&reference, old_cell, cell, context](UninitializedObjects& uninitObj) {
NetworkID id = reference->GetNetworkID();
auto& sub = uninitObj[old_cell];
sub.erase(find(sub.begin(), sub.end(), id));
if (!context)
uninitObj[cell].push_back(id);
});
if (context)
{
GameFactory::Free(player);
NewDispatch(reference);
}
}
}
void Game::net_SetLock(const FactoryObject& reference, unsigned int lock)
{
Lockable* result;
if ((result = reference->SetLockLevel(lock)))
SetLock(reference);
}
void Game::net_SetOwner(const FactoryObject& reference, unsigned int owner)
{
if (reference->SetOwner(owner))
SetOwner(reference);
}
void Game::net_GetActivate(const FactoryReference& reference, const FactoryReference& actor)
{
Activate(reference, actor);
}
void Game::net_SetItemCount(FactoryItem& reference, unsigned int count, bool silent)
{
unsigned int old_count = reference->GetItemCount();
if (reference->SetItemCount(count))
{
NetworkID container = reference->GetItemContainer();
if (!container)
SetRefCount(reference);
else
{
reference->SetItemSilent(silent);
unsigned int baseID = reference->GetBase();
float condition = reference->GetItemCondition();
GameFactory::Free(reference);
GameFactory::Operate<Container, EXCEPTION_FACTORY_VALIDATED>(container, [count, old_count, baseID, condition, silent](FactoryContainer& container) {
signed int diff = count - old_count;
if (diff > 0)
AddItem(container, baseID, diff, condition, silent);
else
{
RemoveItem(container, baseID, abs(diff), silent);
// Game always removes equipped item first - workaround (is this really always the case?)
NetworkID equipped = container->IsEquipped(baseID);
if (equipped && vaultcast_test<Actor>(container))
GameFactory::Operate<Actor, EXCEPTION_FACTORY_VALIDATED>(container->GetNetworkID(), [equipped](FactoryActor& actor) {
GameFactory::Operate<Item>(equipped, [&actor](Item* item) {
EquipItem(actor, item->GetBase(), item->GetItemCondition(), false, item->GetItemStick());
});
});
}
});
}
}
}
void Game::net_SetItemCondition(FactoryItem& reference, float condition, unsigned int health)
{
if (reference->SetItemCondition(condition))
{
NetworkID container = reference->GetItemContainer();
if (!container)
SetCurrentHealth(reference, health);
else if (reference->GetItemEquipped())
{
GameFactory::Free(reference);
// SetEquippedCurrentHealth
}
}
}
void Game::net_SetItemEquipped(FactoryItem& reference, bool equipped, bool silent, bool stick)
{
if (reference->SetItemEquipped(equipped))
{
reference->SetItemSilent(silent);
reference->SetItemStick(stick);
NetworkID item = reference->GetNetworkID();
NetworkID container = reference->GetItemContainer();
GameFactory::Free(reference);
GameFactory::Operate<Actor, EXCEPTION_FACTORY_VALIDATED>(container, [equipped, item](FactoryActor& actor) {
GameFactory::Operate<Item, EXCEPTION_FACTORY_VALIDATED>(item, [&actor, equipped](FactoryItem& item) {
if (equipped)
EquipItem(actor, item);
else
UnequipItem(actor, item);
});
});
}
}
void Game::net_SetActorValue(const FactoryActor& reference, bool base, unsigned char index, float value)
{
Lockable* result;
float prev_value = reference->GetActorValue(index);
if (base)
result = reference->SetActorBaseValue(index, value);
else
result = reference->SetActorValue(index, value);
if (result)
{
if (!base && (index == ActorVal_Health || (index >= ActorVal_Head && index <= ActorVal_Brain)))
{
float diff = value - prev_value;
if (diff < 0.00f)
DamageActorValue(reference, index, diff);
else if (diff > 0.00f)
RestoreActorValue(reference, index, diff);
}
else
SetActorValue(reference, base, index);
}
}
void Game::net_SetActorState(const FactoryActor& reference, unsigned int, unsigned char moving, unsigned char movingxy, unsigned char weapon, bool alerted, bool sneaking, bool firing)
{
Lockable* result;
bool enabled = reference->GetEnabled();
result = reference->SetActorMovingXY(movingxy);
if (result && enabled)
SetAngle(reference);
result = reference->SetActorAlerted(alerted);
if (result && enabled)
SetActorAlerted(reference, result->Lock());
result = reference->SetActorSneaking(sneaking);
if (result && enabled)
SetActorSneaking(reference, result->Lock());
result = reference->SetActorMovingAnimation(moving);
if (result && enabled)
{
SetActorMovingAnimation(reference, result->Lock());
if (moving == AnimGroup_Idle)
SetPos(reference);
}
unsigned char prev_weapon = reference->GetActorWeaponAnimation();
result = reference->SetActorWeaponAnimation(weapon);
if (result && enabled && !firing && reference->GetActorAlerted() && weapon != AnimGroup_Idle && weapon != AnimGroup_Equip && weapon != AnimGroup_Unequip && weapon != AnimGroup_Holster &&
//(game == FALLOUT3 ? (weapon == AnimGroup_BlockHit) : (weapon == FalloutNV::AnimGroup_BlockHit)) &&
(weapon != AnimGroup_Aim || prev_weapon == AnimGroup_AimIS))
{
if (weapon == AnimGroup_Aim && prev_weapon == AnimGroup_AimIS)
{
SetActorAnimation(reference, AnimGroup_AimDown);
SetActorAnimation(reference, AnimGroup_AimUp);
}
SetActorWeaponAnimation(reference, result->Lock());
if (weapon == AnimGroup_AimIS)
{
SetActorAnimation(reference, AnimGroup_AimISDown);
SetActorAnimation(reference, AnimGroup_AimISUp);
}
}
}
void Game::net_SetActorRace(const FactoryActor& reference, unsigned int race, signed int age, signed int delta_age)
{
reference->SetActorRace(race);
reference->SetActorAge(age); // delta from original race to new race
SetActorRace(reference, delta_age); // using delta from current race to new race
}
void Game::net_SetActorFemale(const FactoryActor& reference, bool female)
{
reference->SetActorFemale(female);
SetActorFemale(reference);
}
void Game::net_SetActorDead(FactoryActor& reference, bool dead, unsigned short limbs, signed char cause)
{
Lockable* result;
result = reference->SetActorDead(dead, limbs, cause);
if (result && reference->GetReference())
{
if (dead)
KillActor(reference);
else if (reference->GetReference() != PLAYER_REFERENCE)
{
RemoveObject(reference);
reference->SetReference(0x00000000);
NewActor(reference);
}
else
{
NetworkID id = reference->GetNetworkID();
reference->SetEnabled(false);
GameFactory::Free(reference);
ForceRespawn();
this_thread::sleep_for(chrono::seconds(3));
// remove all base effects so they get re-applied in LoadEnvironment
baseRaces.clear();
spawnFunc();
cellContext.Operate([](Player::CellContext& cellContext) {
cellContext = spawnContext;
});
LoadEnvironment();
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_DEAD>(id, false, 0, 0),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
}
}
void Game::net_FireWeapon(const FactoryActor& reference, unsigned int weapon)
{
if (reference->GetEnabled())
FireWeapon(reference, weapon);
}
void Game::net_SetActorIdle(const FactoryActor& reference, unsigned int idle, const string& name)
{
Lockable* result;
bool enabled = reference->GetEnabled();
result = reference->SetActorIdleAnimation(idle);
if (result && enabled && idle)
SetActorIdleAnimation(reference, name, result->Lock());
}
void Game::net_UpdateInterior(const string& cell, bool spawn)
{
CenterOnCell(cell, spawn);
}
void Game::net_UpdateExterior(unsigned int baseID, signed int x, signed int y, bool spawn)
{
CenterOnWorld(baseID, x, y, spawn);
}
void Game::net_UpdateContext(Player::CellContext& context, bool spawn)
{
if (spawn)
spawnContext = context;
CellRefs copy;
pair<vector<unsigned int>, vector<unsigned int>> diff;
GameFactory::Operate<Player>(PLAYER_REFERENCE, [&context, ©, &diff](Player* player) {
unsigned int old_cell = player->GetNetworkCell();
player->SetNetworkCell(context[0]);
player->SetGameCell(context[0]);
cellRefs.Operate([&context, ©, &diff, old_cell](CellRefs& cellRefs) {
cellContext.Operate([&context, ©, &diff, old_cell, &cellRefs](Player::CellContext& cellContext) {
cellRefs[old_cell][ID_PLAYER].erase(PLAYER_REFERENCE);
cellRefs[context[0]][ID_PLAYER].insert(PLAYER_REFERENCE);
sort(context.begin(), context.end());
sort(cellContext.begin(), cellContext.end());
set_difference(context.begin(), context.end(), cellContext.begin(), cellContext.end(), back_inserter(diff.first));
set_difference(cellContext.begin(), cellContext.end(), context.begin(), context.end(), back_inserter(diff.second));
cellContext = context;
for (auto cell : diff.second)
if (cell)
copy[cell] = cellRefs[cell];
for (auto cell : diff.first)
if (cell)
copy[cell] = cellRefs[cell];
});
});
});
for (unsigned int cell : diff.second)
if (cell)
for (const auto& refs : copy[cell])
for (unsigned int refID : refs.second)
if (refID != PLAYER_REFERENCE)
GameFactory::Operate<Object, EXCEPTION_FACTORY_VALIDATED>(refID, [](FactoryObject& object) {
if (!object->IsPersistent() && object->SetEnabled(false))
ToggleEnabled(object);
});
for (unsigned int cell : diff.first)
if (cell)
{
vector<unsigned int> refIDs;
deletedObj.Operate([&refIDs, cell](DeletedObjects& deletedObj) {
refIDs = move(deletedObj[cell]);
});
for (auto id : refIDs)
RemoveObject(id);
for (const auto& refs : copy[cell])
for (unsigned int refID : refs.second)
if (refID != PLAYER_REFERENCE)
GameFactory::Operate<Object, EXCEPTION_FACTORY_VALIDATED>({refID, PLAYER_REFERENCE}, [cell](FactoryObjects& objects) {
if (objects[0]->SetEnabled(true))
ToggleEnabled(objects[0]);
if (objects[0]->SetGameCell(cell))
MoveTo(objects[0], objects[1], true);
objects[0]->Work();
});
UninitializedObjects::mapped_type ids;
uninitObj.Operate([&ids, cell](UninitializedObjects& uninitObj) {
ids = move(uninitObj[cell]);
});
for (auto id : ids)
GameFactory::Operate<Object, EXCEPTION_FACTORY_VALIDATED>(id, [](FactoryObject& object) {
NewDispatch(object);
});
}
}
void Game::net_UpdateConsole(bool enabled)
{
ToggleKey(enabled, ScanCode_Console);
}
void Game::net_UpdateWindowPos(const FactoryWindow& reference, const tuple<float, float, float, float>& pos)
{
reference->SetPos(get<0>(pos), get<1>(pos), get<2>(pos), get<3>(pos));
SetWindowPos(reference);
}
void Game::net_UpdateWindowSize(const FactoryWindow& reference, const tuple<float, float, float, float>& size)
{
reference->SetSize(get<0>(size), get<1>(size), get<2>(size), get<3>(size));
SetWindowSize(reference);
}
void Game::net_UpdateWindowVisible(const FactoryWindow& reference, bool visible)
{
reference->SetVisible(visible);
SetWindowVisible(reference);
}
void Game::net_UpdateWindowLocked(const FactoryWindow& reference, bool locked)
{
reference->SetLocked(locked);
SetWindowLocked(reference);
}
void Game::net_UpdateWindowText(const FactoryWindow& reference, const string& text)
{
reference->SetText(text);
SetWindowText(reference);
}
void Game::net_UpdateEditMaxLength(const FactoryEdit& reference, unsigned int length)
{
reference->SetMaxLength(length);
SetEditMaxLength(reference);
}
void Game::net_UpdateEditValidation(const FactoryEdit& reference, const std::string& validation)
{
reference->SetValidation(validation);
SetEditValidation(reference);
}
void Game::net_UpdateCheckboxSelected(const FactoryCheckbox& reference, bool selected)
{
reference->SetSelected(selected);
SetCheckboxSelected(reference);
}
void Game::net_UpdateRadioButtonSelected(const FactoryRadioButton& reference, ExpectedRadioButton& previous, bool selected)
{
if (previous)
previous->SetSelected(false);
reference->SetSelected(selected);
SetRadioButtonSelected(reference);
}
void Game::net_UpdateRadioButtonGroup(const FactoryRadioButton& reference, unsigned int group)
{
reference->SetGroup(group);
SetRadioButtonGroup(reference);
}
void Game::net_UpdateListItemSelected(const FactoryListItem& reference, bool selected)
{
reference->SetSelected(selected);
SetListItemSelected(reference);
}
void Game::net_UpdateListItemText(const FactoryListItem& reference, const string& text)
{
reference->SetText(text);
SetListItemText(reference);
}
void Game::net_UpdateListMultiSelect(const FactoryList& reference, bool multiselect)
{
reference->SetMultiSelect(multiselect);
SetListMultiSelect(reference);
}
void Game::net_UpdateWindowMode(bool enabled)
{
GUIMode = enabled;
SetWindowMode();
}
void Game::net_UIMessage(const string& message, unsigned char emoticon)
{
UIMessage(message, emoticon);
}
void Game::net_ChatMessage(const string& message)
{
ChatMessage(message);
}
void Game::net_SetGlobalValue(unsigned int global, signed int value)
{
globals[global] = value;
SetGlobalValue(global, value);
}
void Game::net_SetWeather(unsigned int weather)
{
Game::weather = weather;
SetWeather(weather);
}
void Game::net_SetBase(unsigned int playerBase)
{
Game::playerBase = playerBase;
}
void Game::net_SetDeletedStatic(DeletedObjects&& deletedStatic)
{
// move into lambda not possible
Game::deletedStatic.Operate([&deletedStatic](DeletedObjects& deletedStatic_) {
deletedStatic_ = move(deletedStatic);
});
}
void Game::GetPos(const FactoryObject& reference, float X, float Y, float Z)
{
bool result = static_cast<bool>(reference->SetGamePos(tuple<float, float, float>{X, Y, Z}));
if (result && reference->GetReference() == PLAYER_REFERENCE)
{
reference->SetNetworkPos(tuple<float, float, float>{X, Y, Z});
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_POS>(reference->GetNetworkID(), X, Y, Z),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
}
void Game::GetAngle(const FactoryObject& reference, float X, float Y, float Z)
{
if (reference->GetReference() != PLAYER_REFERENCE)
return;
bool result = static_cast<bool>(reference->SetAngle(tuple<float, float, float>{X, Y, Z}));
if (result)
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_ANGLE>(reference->GetNetworkID(), X, Z),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetParentCell(const FactoryPlayer& player, unsigned int cell)
{
bool result = static_cast<bool>(player->SetGameCell(cell));
if (result)
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_CELL>(player->GetNetworkID(), cell, 0.0f, 0.0f, 0.0f),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetActorState(const FactoryActor& reference, unsigned int idle, unsigned char moving, unsigned char weapon, unsigned char flags, bool sneaking)
{
static pair<unsigned char, unsigned char> buf_weapon{AnimGroup_Idle, AnimGroup_Idle};
unsigned char movingxy = flags & 0x03;
bool result;
if (moving == 0xFF)
moving = AnimGroup_Idle;
if (weapon == 0xFF)
weapon = AnimGroup_Idle;
result = (static_cast<bool>(reference->SetActorIdleAnimation(idle)) | static_cast<bool>(reference->SetActorMovingAnimation(moving)) | static_cast<bool>(reference->SetActorMovingXY(movingxy)) | static_cast<bool>(reference->SetActorSneaking(sneaking)));
// workaround for occurences of wrong animation (case: 2HA weapons in AimIS mode, spuriously falls back to Aim for a frame)
buf_weapon.first = buf_weapon.second;
buf_weapon.second = weapon;
if (buf_weapon.first == buf_weapon.second && static_cast<bool>(reference->SetActorWeaponAnimation(weapon)))
{
result = true;
if (weapon == AnimGroup_Equip)
reference->SetActorAlerted(true);
else if (weapon == AnimGroup_Unequip)
reference->SetActorAlerted(false);
}
if (result)
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_STATE>(reference->GetNetworkID(), idle, moving, movingxy, reference->GetActorWeaponAnimation(), reference->GetActorAlerted(), sneaking, false),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetControl(const FactoryPlayer& reference, unsigned char control, unsigned char key)
{
bool result = static_cast<bool>(reference->SetPlayerControl(control, key));
if (result)
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_CONTROL>(reference->GetNetworkID(), control, key),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetActivate(const FactoryReference& reference, const FactoryReference& actor)
{
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_ACTIVATE>(reference->GetNetworkID(), actor->GetNetworkID()),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetFireWeapon(const FactoryPlayer& reference)
{
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_FIREWEAPON>(reference->GetNetworkID(), 0),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetMessage(string message)
{
if (message.empty())
return;
if (message.length() > MAX_CHAT_LENGTH)
message.resize(MAX_CHAT_LENGTH);
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_GAME_CHAT>(message),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetWindowMode(bool enabled)
{
GUIMode = enabled;
Interface::Dynamic([]() {
if (GUIMode)
{
DisablePlayerControls(true, true, true, false);
ToggleControl(false, ControlCode_TogglePOV);
ToggleControl(false, ControlCode_Crouch);
}
else
{
EnablePlayerControls();
ToggleControl(true, ControlCode_TogglePOV);
ToggleControl(true, ControlCode_Crouch);
}
});
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WMODE>(enabled),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
void Game::GetWindowClick(const string& name)
{
if (!name.compare(Button::CLOSE_BUTTON))
Interface::SignalEnd();
else
{
NetworkID window = strtoull(name.c_str(), nullptr, 10);
GameFactory::Operate<Window>(window, [](Window* window) {
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WCLICK>(window->GetNetworkID()),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
});
}
}
void Game::GetWindowReturn(const string& name)
{
NetworkID window = strtoull(name.c_str(), nullptr, 10);
if (!window)
return;
GameFactory::Operate<Window>(window, [](Window* window) {
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WRETURN>(window->GetNetworkID()),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
});
}
void Game::GetWindowText(const string& name, const string& text)
{
NetworkID window = strtoull(name.c_str(), nullptr, 10);
GameFactory::Operate<Window>(window, [&text](Window* window) {
window->SetText(text);
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WTEXT>(window->GetNetworkID(), text),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
});
}
void Game::GetCheckboxSelected(const string& name, bool selected)
{
NetworkID checkbox = strtoull(name.c_str(), nullptr, 10);
if (!GameFactory::Operate<Checkbox, BOOL_VALIDATED>(checkbox, [selected](Checkbox* checkbox) {
checkbox->SetSelected(selected);
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WSELECTED>(checkbox->GetNetworkID(), selected),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}))
{
if (!selected)
throw VaultException("Radio button event should only fire on selection");
unsigned int group = GameFactory::Operate<RadioButton>(checkbox, [](RadioButton* radiobutton) {
radiobutton->SetSelected(true);
return radiobutton->GetGroup();
});
NetworkID previous = GameFactory::Operate<RadioButton>(GameFactory::GetByType(ID_RADIOBUTTON), [checkbox, group](RadioButtons& radiobuttons) {
for (auto radiobutton : radiobuttons)
if (radiobutton->GetGroup() == group && radiobutton->GetSelected() && radiobutton->GetNetworkID() != checkbox)
{
radiobutton->SetSelected(false);
return radiobutton->GetNetworkID();
}
return 0ull;
});
Network::Queue({Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WRSELECTED>(checkbox, previous, true),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server)
});
}
}
void Game::GetListboxSelections(const string& name, const vector<const char*>& selections)
{
NetworkID list = strtoull(name.c_str(), nullptr, 10);
set<NetworkID> selected_ids;
transform(selections.begin(), selections.end(), inserter(selected_ids, selected_ids.begin()), [](const char* selection) { return strtoull(selection, nullptr, 10); });
NetworkResponse r_deselected, r_selected;
GameFactory::Operate<List>(list, [&selected_ids, &r_deselected, &r_selected](List* list) {
GameFactory::Operate<ListItem>(list->GetItemList(), [&selected_ids, &r_deselected, &r_selected](ListItems& listitems) {
for (auto listitem : listitems)
{
NetworkID id = listitem->GetNetworkID();
bool old_selected = listitem->GetSelected();
bool selected = selected_ids.count(id);
if (selected == old_selected)
continue;
if (selected && !old_selected)
r_selected.emplace_back(Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WLSELECTED>(id, true),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server));
else
r_deselected.emplace_back(Network::CreateResponse(
PacketFactory::Create<pTypes::ID_UPDATE_WLSELECTED>(id, false),
HIGH_PRIORITY, RELIABLE_ORDERED, CHANNEL_GAME, server));
listitem->SetSelected(selected);
}
});
});
if (!r_deselected.empty())
Network::Queue(move(r_deselected));
if (!r_selected.empty())
Network::Queue(move(r_selected));
}
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
namespace GeneralizedHarmonic::BoundaryCorrections {
void register_derived_with_charm() noexcept;
} // namespace GeneralizedHarmonic::BoundaryCorrections
|
//**********************************
// OpenGL Framebuffer Multisample
// 27/01/2012 - 27/01/2012
//**********************************
// Christophe Riccio
// ogl-samples@g-truc.net
//**********************************
// G-Truc Creation
// www.g-truc.net
//**********************************
#include <glf/glf.hpp>
namespace
{
char const * SAMPLE_NAME = "OpenGL Framebuffer Explicit Multisample";
char const * TEXTURE_DIFFUSE("kueken3-bgr8.dds");
glm::ivec2 const FRAMEBUFFER_SIZE(320, 240);
int const SAMPLE_SIZE_WIDTH(640);
int const SAMPLE_SIZE_HEIGHT(480);
int const SAMPLE_MAJOR_VERSION(3);
int const SAMPLE_MINOR_VERSION(3);
glf::window Window(glm::ivec2(SAMPLE_SIZE_WIDTH, SAMPLE_SIZE_HEIGHT));
// With DDS textures, v texture coordinate are reversed, from top to bottom
GLsizei const VertexCount(6);
GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v2fv2f);
glf::vertex_v2fv2f const VertexData[VertexCount] =
{
glf::vertex_v2fv2f(glm::vec2(-4.0f,-3.0f), glm::vec2(0.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 4.0f,-3.0f), glm::vec2(1.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 4.0f, 3.0f), glm::vec2(1.0f, 0.0f)),
glf::vertex_v2fv2f(glm::vec2( 4.0f, 3.0f), glm::vec2(1.0f, 0.0f)),
glf::vertex_v2fv2f(glm::vec2(-4.0f, 3.0f), glm::vec2(0.0f, 0.0f)),
glf::vertex_v2fv2f(glm::vec2(-4.0f,-3.0f), glm::vec2(0.0f, 1.0f))
};
namespace program
{
enum type
{
THROUGH,
RESOLVE_BOX,
RESOLVE_NEAR,
MAX
};
}//namespace program
namespace renderbuffer
{
enum type
{
DEPTH,
COLOR,
MAX
};
}//namespace renderbuffer
namespace texture
{
enum type
{
DIFFUSE,
COLOR,
MAX
};
}//namespace texture
char const * VERT_SHADER_SOURCE("gl-330/multisample-explicit-texture-nv.vert");
char const * FRAG_SHADER_SOURCE[program::MAX] =
{
"gl-330/multisample-explicit-texture-nv.frag",
"gl-330/multisample-explicit-box-nv.frag",
"gl-330/multisample-explicit-near-nv.frag",
};
GLuint VertexArrayName(0);
GLuint ProgramName[program::MAX];
GLuint BufferName(0);
GLuint SamplerName(0);
GLuint TextureName[texture::MAX] = {0, 0};
GLuint RenderbufferName[renderbuffer::MAX] = {0, 0};
GLuint FramebufferName(0);
GLint UniformMVP[program::MAX];
GLint UniformDiffuse[program::MAX];
}//namespace
bool initDebugOutput()
{
bool Validated(true);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
glDebugMessageCallbackARB(&glf::debugOutput, NULL);
return Validated;
}
bool initSampler()
{
glGenSamplers(1, &SamplerName);
glSamplerParameteri(SamplerName, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glSamplerParameteri(SamplerName, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glSamplerParameteri(SamplerName, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glSamplerParameterfv(SamplerName, GL_TEXTURE_BORDER_COLOR, &glm::vec4(0.0f)[0]);
glSamplerParameterf(SamplerName, GL_TEXTURE_MIN_LOD, -1000.f);
glSamplerParameterf(SamplerName, GL_TEXTURE_MAX_LOD, 1000.f);
glSamplerParameterf(SamplerName, GL_TEXTURE_LOD_BIAS, 0.0f);
glSamplerParameteri(SamplerName, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glSamplerParameteri(SamplerName, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
return glf::checkError("initSampler");
}
bool initProgram()
{
bool Validated = true;
// Create program
for(int i = 0; i < program::MAX; ++i)
{
GLuint VertShaderName = glf::createShader(GL_VERTEX_SHADER, glf::DATA_DIRECTORY + VERT_SHADER_SOURCE);
GLuint FragShaderName = glf::createShader(GL_FRAGMENT_SHADER, glf::DATA_DIRECTORY + FRAG_SHADER_SOURCE[i]);
ProgramName[i] = glCreateProgram();
glAttachShader(ProgramName[i], VertShaderName);
glAttachShader(ProgramName[i], FragShaderName);
glDeleteShader(VertShaderName);
glDeleteShader(FragShaderName);
glLinkProgram(ProgramName[i]);
Validated = Validated && glf::checkProgram(ProgramName[i]);
UniformMVP[i] = glGetUniformLocation(ProgramName[i], "MVP");
UniformDiffuse[i] = glGetUniformLocation(ProgramName[i], "Diffuse");
}
return Validated && glf::checkError("initProgram");
}
bool initBuffer()
{
glGenBuffers(1, &BufferName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return glf::checkError("initBuffer");;
}
bool initTexture()
{
glGenTextures(texture::MAX, TextureName);
gli::texture2D Texture(gli::loadStorageDDS(glf::DATA_DIRECTORY + TEXTURE_DIFFUSE));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Required AMD bug
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Required AMD bug
for(std::size_t Level = 0; Level < Texture.levels(); ++Level)
{
glTexImage2D(
GL_TEXTURE_2D,
GLint(Level),
GL_RGB8,
GLsizei(Texture[Level].dimensions().x),
GLsizei(Texture[Level].dimensions().y),
0,
GL_BGR,
GL_UNSIGNED_BYTE,
Texture[Level].data());
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindTexture(GL_TEXTURE_RENDERBUFFER_NV, TextureName[texture::COLOR]);
glTexRenderbufferNV(GL_TEXTURE_RENDERBUFFER_NV, RenderbufferName[renderbuffer::COLOR]);
glBindTexture(GL_TEXTURE_RENDERBUFFER_NV, 0);
return glf::checkError("initTexture");
}
bool initRenderbuffer()
{
glGenRenderbuffers(renderbuffer::MAX, RenderbufferName);
glBindRenderbuffer(GL_RENDERBUFFER, RenderbufferName[renderbuffer::COLOR]);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glBindRenderbuffer(GL_RENDERBUFFER, RenderbufferName[renderbuffer::DEPTH]);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT24, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
return glf::checkError("initRenderbuffer");
}
bool initFramebuffer()
{
glGenFramebuffers(1, &FramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, RenderbufferName[renderbuffer::COLOR]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, RenderbufferName[renderbuffer::DEPTH]);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return false;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return glf::checkError("initFramebuffer");
}
bool initVertexArray()
{
glGenVertexArrays(1, &VertexArrayName);
glBindVertexArray(VertexArrayName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glVertexAttribPointer(glf::semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), GLF_BUFFER_OFFSET(0));
glVertexAttribPointer(glf::semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), GLF_BUFFER_OFFSET(sizeof(glm::vec2)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(glf::semantic::attr::POSITION);
glEnableVertexAttribArray(glf::semantic::attr::TEXCOORD);
glBindVertexArray(0);
return glf::checkError("initVertexArray");
}
bool begin()
{
bool Validated = true;
Validated = Validated && glf::checkGLVersion(SAMPLE_MAJOR_VERSION, SAMPLE_MINOR_VERSION);
Validated = Validated && glf::checkExtension("GL_NV_explicit_multisample");
if(Validated && glf::checkExtension("GL_ARB_debug_output"))
Validated = initDebugOutput();
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initVertexArray();
if(Validated)
Validated = initSampler();
if(Validated)
Validated = initRenderbuffer();
if(Validated)
Validated = initTexture();
if(Validated)
Validated = initFramebuffer();
return Validated && glf::checkError("begin");
}
bool end()
{
glDeleteBuffers(1, &BufferName);
for(int i = 0; i < program::MAX; ++i)
glDeleteProgram(ProgramName[i]);
glDeleteSamplers(1, &SamplerName);
glDeleteTextures(renderbuffer::MAX, RenderbufferName);
glDeleteTextures(texture::MAX, TextureName);
glDeleteFramebuffers(1, &FramebufferName);
glDeleteVertexArrays(1, &VertexArrayName);
return glf::checkError("end");
}
void renderFBO()
{
//glm::mat4 Perspective = glm::perspective(45.0f, float(FRAMEBUFFER_SIZE.x) / FRAMEBUFFER_SIZE.y, 0.1f, 100.0f);
//glm::mat4 ViewFlip = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f,-1.0f, 1.0f));
//glm::mat4 ViewTranslate = glm::translate(ViewFlip, glm::vec3(0.0f, 0.0f, -Window.TranlationCurrent.y * 2.0));
//glm::mat4 View = glm::rotate(ViewTranslate,-15.f, glm::vec3(0.f, 0.f, 1.f));
//glm::mat4 Model = glm::mat4(1.0f);
//glm::mat4 MVP = Perspective * View * Model;
glm::mat4 Perspective = glm::perspective(45.0f, float(FRAMEBUFFER_SIZE.x) / FRAMEBUFFER_SIZE.y, 0.1f, 100.0f);
glm::mat4 ViewTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -Window.TranlationCurrent.y * 2.0 - 4.0));
glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, Window.RotationCurrent.y, glm::vec3(1.f, 0.f, 0.f));
glm::mat4 View = glm::rotate(ViewRotateX, Window.RotationCurrent.x, glm::vec3(0.f, 1.f, 0.f));
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 MVP = Perspective * View * Model;
glEnable(GL_DEPTH_TEST);
glUseProgram(ProgramName[program::THROUGH]);
glUniform1i(UniformDiffuse[program::THROUGH], 0);
glUniformMatrix4fv(UniformMVP[program::THROUGH], 1, GL_FALSE, &MVP[0][0]);
glViewport(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
float Depth(1.0f);
glClearBufferfv(GL_DEPTH, 0, &Depth);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glBindSampler(0, SamplerName);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 5);
glDisable(GL_DEPTH_TEST);
glf::checkError("renderFBO");
}
void resolveMultisampling()
{
////glm::mat4 Projection(glm::ortho(-8.0f, 8.0f, -6.0f, 6.0f));
//glm::mat4 Perspective = glm::perspective(45.0f, float(Window.Size.x) / Window.Size.y, 0.1f, 100.0f);
//glm::mat4 ViewTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -Window.TranlationCurrent.y * 2.0));
//glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, Window.RotationCurrent.y, glm::vec3(1.f, 0.f, 0.f));
//glm::mat4 View = glm::rotate(ViewRotateX, Window.RotationCurrent.x, glm::vec3(0.f, 1.f, 0.f));
//glm::mat4 Model = glm::mat4(1.0f);
//glm::mat4 MVP = Perspective * View * Model;
glm::mat4 Perspective = glm::perspective(45.0f, float(Window.Size.x) / Window.Size.y, 0.1f, 100.0f);
glm::mat4 ViewFlip = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f,-1.0f, 1.0f));
glm::mat4 ViewTranslate = glm::translate(ViewFlip, glm::vec3(0.0f, 0.0f, -Window.TranlationCurrent.y * 2.0));
glm::mat4 View = glm::rotate(ViewTranslate,-15.f, glm::vec3(0.f, 0.f, 1.f));
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 MVP = Perspective * View * Model;
glViewport(0, 0, Window.Size.x, Window.Size.y);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RENDERBUFFER_NV, TextureName[texture::COLOR]);
glBindSampler(0, SamplerName);
glBindVertexArray(VertexArrayName);
glEnable(GL_SCISSOR_TEST);
// Box
{
glScissor(1, 1, Window.Size.x / 2 - 2, Window.Size.y - 2);
glUseProgram(ProgramName[program::RESOLVE_BOX]);
glUniform1i(UniformDiffuse[program::RESOLVE_BOX], 0);
glUniformMatrix4fv(UniformMVP[program::RESOLVE_BOX], 1, GL_FALSE, &MVP[0][0]);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 5);
}
// Near
{
glScissor(Window.Size.x / 2 + 1, 1, Window.Size.x / 2 - 2, Window.Size.y - 2);
glUseProgram(ProgramName[program::RESOLVE_NEAR]);
glUniform1i(UniformDiffuse[program::RESOLVE_NEAR], 0);
glUniformMatrix4fv(UniformMVP[program::RESOLVE_NEAR], 1, GL_FALSE, &MVP[0][0]);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 5);
}
glDisable(GL_SCISSOR_TEST);
glf::checkError("renderFB");
}
void display()
{
// Clear the framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);
// Pass 1
// Render the scene in a multisampled framebuffer
glEnable(GL_MULTISAMPLE);
renderFBO();
glDisable(GL_MULTISAMPLE);
// Pass 2
// Resolved and render the colorbuffer from the multisampled framebuffer
resolveMultisampling();
glf::checkError("display");
glf::swapBuffers();
}
int main(int argc, char* argv[])
{
if(glf::run(
argc, argv,
glm::ivec2(::SAMPLE_SIZE_WIDTH, ::SAMPLE_SIZE_HEIGHT),
GLF_CONTEXT_CORE_PROFILE_BIT, ::SAMPLE_MAJOR_VERSION,
::SAMPLE_MINOR_VERSION))
return 0;
return 1;
}
|
/*
* fpu.cpp
*
* This example demonstrates how one can use odeint to solve the Fermi-Pasta-Ulam system.
* Created on: July 13, 2011
*
* Copyright 2011-2012 Karsten Ahnert
* Copyright 2011 Mario Mulansky
* 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)
*/
#include <iostream>
#include <numeric>
#include <cmath>
#include <vector>
#include <boost/numeric/odeint.hpp>
#ifndef M_PI //not there on windows
#define M_PI 3.1415927 //...
#endif
using namespace std;
using namespace boost::numeric::odeint;
//[ fpu_system_function
typedef vector< double > container_type;
struct fpu
{
const double m_beta;
fpu( const double beta = 1.0 ) : m_beta( beta ) { }
// system function defining the ODE
void operator()( const container_type &q , container_type &dpdt ) const
{
size_t n = q.size();
double tmp = q[0] - 0.0;
double tmp2 = tmp + m_beta * tmp * tmp * tmp;
dpdt[0] = -tmp2;
for( size_t i=0 ; i<n-1 ; ++i )
{
tmp = q[i+1] - q[i];
tmp2 = tmp + m_beta * tmp * tmp * tmp;
dpdt[i] += tmp2;
dpdt[i+1] = -tmp2;
}
tmp = - q[n-1];
tmp2 = tmp + m_beta * tmp * tmp * tmp;
dpdt[n-1] += tmp2;
}
// calculates the energy of the system
double energy( const container_type &q , const container_type &p ) const
{
// ...
//<-
double energy = 0.0;
size_t n = q.size();
double tmp = q[0];
energy += 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;
for( size_t i=0 ; i<n-1 ; ++i )
{
tmp = q[i+1] - q[i];
energy += 0.5 * ( p[i] * p[i] + tmp * tmp ) + 0.25 * m_beta * tmp * tmp * tmp * tmp;
}
energy += 0.5 * p[n-1] * p[n-1];
tmp = q[n-1];
energy += 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;
return energy;
//->
}
// calculates the local energy of the system
void local_energy( const container_type &q , const container_type &p , container_type &e ) const
{
// ...
//<-
size_t n = q.size();
double tmp = q[0];
double tmp2 = 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;
e[0] = tmp2;
for( size_t i=0 ; i<n-1 ; ++i )
{
tmp = q[i+1] - q[i];
tmp2 = 0.25 * tmp * tmp + 0.125 * m_beta * tmp * tmp * tmp * tmp;
e[i] += 0.5 * p[i] * p[i] + tmp2 ;
e[i+1] = tmp2;
}
tmp = q[n-1];
tmp2 = 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;
e[n-1] += 0.5 * p[n-1] * p[n-1] + tmp2;
//->
}
};
//]
//[ fpu_observer
struct streaming_observer
{
std::ostream& m_out;
const fpu &m_fpu;
size_t m_write_every;
size_t m_count;
streaming_observer( std::ostream &out , const fpu &f , size_t write_every = 100 )
: m_out( out ) , m_fpu( f ) , m_write_every( write_every ) , m_count( 0 ) { }
template< class State >
void operator()( const State &x , double t )
{
if( ( m_count % m_write_every ) == 0 )
{
container_type &q = x.first;
container_type &p = x.second;
container_type energy( q.size() );
m_fpu.local_energy( q , p , energy );
for( size_t i=0 ; i<q.size() ; ++i )
{
m_out << t << "\t" << i << "\t" << q[i] << "\t" << p[i] << "\t" << energy[i] << "\n";
}
m_out << "\n";
clog << t << "\t" << accumulate( energy.begin() , energy.end() , 0.0 ) << "\n";
}
++m_count;
}
};
//]
int main( int argc , char **argv )
{
//[ fpu_integration
const size_t n = 64;
container_type q( n , 0.0 ) , p( n , 0.0 );
for( size_t i=0 ; i<n ; ++i )
{
p[i] = 0.0;
q[i] = 32.0 * sin( double( i + 1 ) / double( n + 1 ) * M_PI );
}
const double dt = 0.1;
typedef symplectic_rkn_sb3a_mclachlan< container_type > stepper_type;
fpu fpu_instance( 8.0 );
integrate_const( stepper_type() , fpu_instance ,
make_pair( boost::ref( q ) , boost::ref( p ) ) ,
0.0 , 1000.0 , dt , streaming_observer( cout , fpu_instance , 10 ) );
//]
return 0;
}
|
// ========================================================================== //
// Copyright (c) 2014-2019 The University of Texas at Austin. //
// All rights reserved. //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// A copy of the License is included with this software in the file LICENSE. //
// If your copy does not contain the License, you may obtain a copy of the //
// License at: //
// //
// https://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 "ServerRendering.h"
#include <pthread.h>
namespace gxy
{
KEYED_OBJECT_CLASS_TYPE(ServerRendering)
void
ServerRendering::initialize()
{
Rendering::initialize();
pthread_mutex_init(&lock, NULL);
max_frame = -1;
handler = NULL;
owner = 0;
}
ServerRendering::~ServerRendering()
{
handler = NULL;
pthread_mutex_destroy(&lock);
}
void
ServerRendering::AddLocalPixels(Pixel *p, int n, int f, int s)
{
pthread_mutex_lock(&lock);
// std::cerr << "n = " << n << " f = " << f << "\n";
// std::cerr << " p[0]: " << p[0].x << " " << p[0].y << "\n";
// std::cerr << " p[n-1]: " << p[n-1].x << " " << p[n-1].y << "\n";
if (f >= max_frame)
{
max_frame = f;
char* ptrs[] = {(char *)&n, (char *)&f, (char *)&s, (char *)p};
int szs[] = {sizeof(int), sizeof(int), sizeof(int), static_cast<int>(n*sizeof(Pixel)), 0};
if (handler)
handler->DSendV(ptrs, szs);
// std::cerr << "after... n = " << n << " f = " << f << "\n";
}
// else
// std::cerr << "skipped\n";
pthread_mutex_unlock(&lock);
}
} // namespace gxy
|
/*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup freestyle
*/
#include "BPy_CurvePointIterator.h"
#include "../BPy_Convert.h"
#include "BPy_Interface0DIterator.h"
#ifdef __cplusplus
extern "C" {
#endif
///////////////////////////////////////////////////////////////////////////////////////////
//------------------------INSTANCE METHODS ----------------------------------
PyDoc_STRVAR(CurvePointIterator_doc,
"Class hierarchy: :class:`Iterator` > :class:`CurvePointIterator`\n"
"\n"
"Class representing an iterator on a curve. Allows an iterating\n"
"outside initial vertices. A CurvePoint is instantiated and returned\n"
"through the .object attribute.\n"
"\n"
".. method:: __init__()\n"
" __init__(brother)\n"
" __init__(step=0.0)\n"
"\n"
" Builds a CurvePointIterator object using either the default constructor,\n"
" copy constructor, or the overloaded constructor.\n"
"\n"
" :arg brother: A CurvePointIterator object.\n"
" :type brother: :class:`CurvePointIterator`\n"
" :arg step: A resampling resolution with which the curve is resampled.\n"
" If zero, no resampling is done (i.e., the iterator iterates over\n"
" initial vertices).\n"
" :type step: float");
static int CurvePointIterator_init(BPy_CurvePointIterator *self, PyObject *args, PyObject *kwds)
{
static const char *kwlist_1[] = {"brother", nullptr};
static const char *kwlist_2[] = {"step", nullptr};
PyObject *brother = nullptr;
float step;
if (PyArg_ParseTupleAndKeywords(
args, kwds, "|O!", (char **)kwlist_1, &CurvePointIterator_Type, &brother)) {
if (!brother) {
self->cp_it = new CurveInternal::CurvePointIterator();
}
else {
self->cp_it = new CurveInternal::CurvePointIterator(
*(((BPy_CurvePointIterator *)brother)->cp_it));
}
}
else if ((void)PyErr_Clear(),
PyArg_ParseTupleAndKeywords(args, kwds, "f", (char **)kwlist_2, &step)) {
self->cp_it = new CurveInternal::CurvePointIterator(step);
}
else {
PyErr_SetString(PyExc_TypeError, "invalid argument(s)");
return -1;
}
self->py_it.it = self->cp_it;
return 0;
}
/*----------------------CurvePointIterator get/setters ----------------------------*/
PyDoc_STRVAR(CurvePointIterator_object_doc,
"The CurvePoint object currently pointed by this iterator.\n"
"\n"
":type: :class:`CurvePoint`");
static PyObject *CurvePointIterator_object_get(BPy_CurvePointIterator *self, void *UNUSED(closure))
{
if (self->cp_it->isEnd()) {
PyErr_SetString(PyExc_RuntimeError, "iteration has stopped");
return nullptr;
}
return BPy_CurvePoint_from_CurvePoint(self->cp_it->operator*());
}
PyDoc_STRVAR(CurvePointIterator_t_doc,
"The curvilinear abscissa of the current point.\n"
"\n"
":type: float");
static PyObject *CurvePointIterator_t_get(BPy_CurvePointIterator *self, void *UNUSED(closure))
{
return PyFloat_FromDouble(self->cp_it->t());
}
PyDoc_STRVAR(CurvePointIterator_u_doc,
"The point parameter at the current point in the stroke (0 <= u <= 1).\n"
"\n"
":type: float");
static PyObject *CurvePointIterator_u_get(BPy_CurvePointIterator *self, void *UNUSED(closure))
{
return PyFloat_FromDouble(self->cp_it->u());
}
static PyGetSetDef BPy_CurvePointIterator_getseters[] = {
{"object",
(getter)CurvePointIterator_object_get,
(setter) nullptr,
CurvePointIterator_object_doc,
nullptr},
{"t", (getter)CurvePointIterator_t_get, (setter) nullptr, CurvePointIterator_t_doc, nullptr},
{"u", (getter)CurvePointIterator_u_get, (setter) nullptr, CurvePointIterator_u_doc, nullptr},
{nullptr, nullptr, nullptr, nullptr, nullptr} /* Sentinel */
};
/*-----------------------BPy_CurvePointIterator type definition ------------------------------*/
PyTypeObject CurvePointIterator_Type = {
PyVarObject_HEAD_INIT(nullptr, 0) "CurvePointIterator", /* tp_name */
sizeof(BPy_CurvePointIterator), /* tp_basicsize */
0, /* tp_itemsize */
nullptr, /* tp_dealloc */
#if PY_VERSION_HEX >= 0x03080000
0, /* tp_vectorcall_offset */
#else
nullptr, /* tp_print */
#endif
nullptr, /* tp_getattr */
nullptr, /* tp_setattr */
nullptr, /* tp_reserved */
nullptr, /* tp_repr */
nullptr, /* tp_as_number */
nullptr, /* tp_as_sequence */
nullptr, /* tp_as_mapping */
nullptr, /* tp_hash */
nullptr, /* tp_call */
nullptr, /* tp_str */
nullptr, /* tp_getattro */
nullptr, /* tp_setattro */
nullptr, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
CurvePointIterator_doc, /* tp_doc */
nullptr, /* tp_traverse */
nullptr, /* tp_clear */
nullptr, /* tp_richcompare */
0, /* tp_weaklistoffset */
nullptr, /* tp_iter */
nullptr, /* tp_iternext */
nullptr, /* tp_methods */
nullptr, /* tp_members */
BPy_CurvePointIterator_getseters, /* tp_getset */
&Iterator_Type, /* tp_base */
nullptr, /* tp_dict */
nullptr, /* tp_descr_get */
nullptr, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)CurvePointIterator_init, /* tp_init */
nullptr, /* tp_alloc */
nullptr, /* tp_new */
};
///////////////////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
}
#endif
|
// Copyright (c) 2018, The AZUR Developers, The TURTLECOIN Developers
//
// Please see the included LICENSE file for more information.
//////////////////////////////////////////
#include <zedwallet++/CommandDispatcher.h>
//////////////////////////////////////////
#include <zedwallet++/AddressBook.h>
#include <zedwallet++/ColouredMsg.h>
#include <zedwallet++/CommandImplementations.h>
#include <zedwallet++/Open.h>
#include <zedwallet++/Transfer.h>
#include <zedwallet++/Fusion.h>
#include <zedwallet++/Utilities.h>
bool handleCommand(
const std::string command,
const std::shared_ptr<WalletBackend> walletBackend,
const std::shared_ptr<std::mutex> mutex)
{
/* Aquire the lock so transactions don't get printed whilst we're handling
a command */
std::scoped_lock lock(*mutex);
/* Basic commands */
if (command == "advanced")
{
advanced(walletBackend);
}
else if (command == "address")
{
std::cout << SuccessMsg(walletBackend->getPrimaryAddress()) << std::endl;
}
else if (command == "balance")
{
balance(walletBackend);
}
else if (command == "backup")
{
backup(walletBackend);
}
else if (command == "exit")
{
return false;
}
else if (command == "help")
{
help(walletBackend);
}
else if (command == "transfer")
{
const bool sendAll = false;
transfer(walletBackend, sendAll);
}
/* Advanced commands */
else if (command == "ab_add")
{
addToAddressBook();
}
else if (command == "ab_delete")
{
deleteFromAddressBook();
}
else if (command == "ab_list")
{
listAddressBook();
}
else if (command == "ab_send")
{
sendFromAddressBook(walletBackend);
}
else if (command == "change_password")
{
changePassword(walletBackend);
}
else if (command == "make_integrated_address")
{
createIntegratedAddress();
}
else if (command == "incoming_transfers")
{
const bool printIncoming = true;
const bool printOutgoing = false;
listTransfers(printIncoming, printOutgoing, walletBackend);
}
else if (command == "list_transfers")
{
const bool printIncoming = true;
const bool printOutgoing = true;
listTransfers(printIncoming, printOutgoing, walletBackend);
}
else if (command == "optimize")
{
std::cout << "Attempting to optimize your wallet to allow you to "
"send large amounts at once.\n"
<< WarningMsg("This may take a very long time!\n");
if (!ZedUtilities::confirm("Do you want to proceed?"))
{
std::cout << WarningMsg("Cancelling optimization.") << std::endl;
}
else
{
optimize(walletBackend);
}
}
else if (command == "outgoing_transfers")
{
const bool printIncoming = false;
const bool printOutgoing = true;
listTransfers(printIncoming, printOutgoing, walletBackend);
}
else if (command == "reset")
{
reset(walletBackend);
}
else if (command == "save")
{
save(walletBackend);
}
else if (command == "save_csv")
{
saveCSV(walletBackend);
}
else if (command == "send_all")
{
const bool sendAll = true;
transfer(walletBackend, sendAll);
}
else if (command == "status")
{
status(walletBackend);
}
else if (command == "swap_node")
{
swapNode(walletBackend);
}
/* This should never happen */
else
{
throw std::runtime_error("Command was defined but not hooked up!");
}
return true;
}
std::shared_ptr<WalletBackend> handleLaunchCommand(
const std::string launchCommand,
const Config &config)
{
if (launchCommand == "create")
{
return createWallet(config);
}
else if (launchCommand == "open")
{
return openWallet(config);
}
else if (launchCommand == "seed_restore")
{
return importWalletFromSeed(config);
}
else if (launchCommand == "key_restore")
{
return importWalletFromKeys(config);
}
else if (launchCommand == "view_wallet")
{
return importViewWallet(config);
}
/* This should never happen */
else
{
throw std::runtime_error("Command was defined but not hooked up!");
}
}
|
/*
* GmatSocketServer.h
*
* Created on: Mar 22, 2011
* Author: Tuan Nguyen
*/
#ifndef GmatSocketServer_hpp
#define GmatSocketServer_hpp
#include <wx/event.h>
#ifdef LINUX_MAC
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#else
#include <winsock2.h>
#include <process.h>
#endif
#define IP_ADDRESS "localhost"
//#define IP_ADDRESS "128.183.221.98"
#define TCP_PORT 3000
class GmatSocketServer
{
public:
GmatSocketServer(wxEvtHandler* handler);
virtual ~GmatSocketServer();
void Close();
void SetEventHandler(wxEvtHandler* handler) {evthandler = handler;}
#ifdef LINUX_MAC
bool RunRequest(int sock);
#else
bool RunRequest(SOCKET sock);
#endif
char* OnRequest(char* item);
bool OnPoke(char* data);
void RunServer();
#ifdef LINUX_MAC
void OnAccept(int sock);
static void* StaticOnAccept(void* objPtr)
{
GmatSocketServer* pThis = (GmatSocketServer*)objPtr;
pThis->OnAccept(pThis->client_sock);
return NULL;
}
static void* StaticRunServer(void* objPtr)
{
GmatSocketServer* pThis = (GmatSocketServer*)objPtr;
pThis->RunServer();
return NULL;
}
#else
void OnAccept(SOCKET sock);
static void StaticOnAccept(void* objPtr)
{
GmatSocketServer* pThis = (GmatSocketServer*)objPtr;
pThis->OnAccept(pThis->client_sock);
}
static void StaticRunServer(void* objPtr)
{
GmatSocketServer* pThis = (GmatSocketServer*)objPtr;
pThis->RunServer();
}
#endif
private:
int m_numClients;
int error;
bool shutdownserver;
wxEvtHandler* evthandler;
#ifdef LINUX_MAC
int Server;
int client_sock;
#else
SOCKET client_sock;
SOCKET Server;
#endif
};
enum
{
ID_SOCKET_POKE = 10000,
ID_SOCKET_REQUEST,
};
#endif /* GmatSocketServer_hpp */
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/vpc/v20170312/model/DisableFlowLogsResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Vpc::V20170312::Model;
using namespace std;
DisableFlowLogsResponse::DisableFlowLogsResponse()
{
}
CoreInternalOutcome DisableFlowLogsResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
return CoreInternalOutcome(true);
}
string DisableFlowLogsResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
|
#include "opentelemetry/sdk/trace/samplers/trace_id_ratio.h"
#include "opentelemetry/trace/span_context_kv_iterable_view.h"
#include "src/common/random.h"
#include <gtest/gtest.h>
#include <cstdlib>
#include <ctime>
using opentelemetry::sdk::common::Random;
using opentelemetry::sdk::trace::Decision;
using opentelemetry::sdk::trace::TraceIdRatioBasedSampler;
namespace trace_api = opentelemetry::trace;
namespace
{
/*
* Helper function for running TraceIdBased sampler tests.
* Given a span context, sampler, and number of iterations this function
* will return the number of RECORD_AND_SAMPLE decision based on randomly
* generated traces.
*
* @param context a required valid span context
* @param sampler a required valid sampler
* @param iterations a requried number specifying the number of times to
* generate a random trace_id and check if it should sample using the provided
* provider and context
*/
int RunShouldSampleCountDecision(trace_api::SpanContext &context,
TraceIdRatioBasedSampler &sampler,
int iterations)
{
int actual_count = 0;
opentelemetry::trace::SpanKind span_kind = opentelemetry::trace::SpanKind::kInternal;
using M = std::map<std::string, int>;
M m1 = {{}};
using L = std::vector<std::pair<trace_api::SpanContext, std::map<std::string, std::string>>>;
L l1 = {{trace_api::SpanContext(false, false), {}}, {trace_api::SpanContext(false, false), {}}};
opentelemetry::common::KeyValueIterableView<M> view{m1};
trace_api::SpanContextKeyValueIterableView<L> links{l1};
for (int i = 0; i < iterations; ++i)
{
uint8_t buf[16] = {0};
Random::GenerateRandomBuffer(buf);
opentelemetry::trace::TraceId trace_id(buf);
auto result = sampler.ShouldSample(context, trace_id, "", span_kind, view, links);
if (result.decision == Decision::RECORD_AND_SAMPLE)
{
++actual_count;
}
}
return actual_count;
}
} // namespace
TEST(TraceIdRatioBasedSampler, ShouldSampleWithoutContext)
{
opentelemetry::trace::TraceId invalid_trace_id;
opentelemetry::trace::SpanKind span_kind = opentelemetry::trace::SpanKind::kInternal;
using M = std::map<std::string, int>;
M m1 = {{}};
using L = std::vector<std::pair<trace_api::SpanContext, std::map<std::string, std::string>>>;
L l1 = {{trace_api::SpanContext(false, false), {}}, {trace_api::SpanContext(false, false), {}}};
opentelemetry::common::KeyValueIterableView<M> view{m1};
trace_api::SpanContextKeyValueIterableView<L> links{l1};
TraceIdRatioBasedSampler s1(0.01);
auto sampling_result = s1.ShouldSample(trace_api::SpanContext::GetInvalid(), invalid_trace_id, "",
span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
constexpr uint8_t buf[] = {0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0};
opentelemetry::trace::TraceId valid_trace_id(buf);
sampling_result = s1.ShouldSample(trace_api::SpanContext::GetInvalid(), valid_trace_id, "",
span_kind, view, links);
ASSERT_EQ(Decision::DROP, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
TraceIdRatioBasedSampler s2(0.50000001);
sampling_result = s2.ShouldSample(trace_api::SpanContext::GetInvalid(), valid_trace_id, "",
span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
TraceIdRatioBasedSampler s3(0.49999999);
sampling_result = s3.ShouldSample(trace_api::SpanContext::GetInvalid(), valid_trace_id, "",
span_kind, view, links);
ASSERT_EQ(Decision::DROP, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
TraceIdRatioBasedSampler s4(0.50000000);
sampling_result = s4.ShouldSample(trace_api::SpanContext::GetInvalid(), valid_trace_id, "",
span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
}
TEST(TraceIdRatioBasedSampler, ShouldSampleWithContext)
{
uint8_t trace_id_buffer[trace_api::TraceId::kSize] = {1};
trace_api::TraceId trace_id{trace_id_buffer};
uint8_t span_id_buffer[trace_api::SpanId::kSize] = {1};
trace_api::SpanId span_id{span_id_buffer};
opentelemetry::trace::SpanKind span_kind = opentelemetry::trace::SpanKind::kInternal;
trace_api::SpanContext c1(trace_id, span_id, trace_api::TraceFlags{0}, false);
trace_api::SpanContext c2(trace_id, span_id, trace_api::TraceFlags{1}, false);
trace_api::SpanContext c3(trace_id, span_id, trace_api::TraceFlags{0}, true);
trace_api::SpanContext c4(trace_id, span_id, trace_api::TraceFlags{1}, true);
using M = std::map<std::string, int>;
M m1 = {{}};
using L = std::vector<std::pair<trace_api::SpanContext, std::map<std::string, std::string>>>;
L l1 = {{trace_api::SpanContext(false, false), {}}, {trace_api::SpanContext(false, false), {}}};
opentelemetry::common::KeyValueIterableView<M> view{m1};
trace_api::SpanContextKeyValueIterableView<L> links{l1};
TraceIdRatioBasedSampler s1(0.01);
auto sampling_result = s1.ShouldSample(c1, trace_id, "", span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
sampling_result = s1.ShouldSample(c2, trace_id, "", span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
sampling_result = s1.ShouldSample(c3, trace_id, "", span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
sampling_result = s1.ShouldSample(c4, trace_id, "", span_kind, view, links);
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
ASSERT_EQ(nullptr, sampling_result.attributes);
}
TEST(TraceIdRatioBasedSampler, TraceIdRatioBasedSamplerHalf)
{
double ratio = 0.5;
int iterations = 100000;
int expected_count = static_cast<int>(iterations * ratio);
int variance = static_cast<int>(iterations * 0.01);
trace_api::SpanContext c(true, true);
TraceIdRatioBasedSampler s(ratio);
int actual_count = RunShouldSampleCountDecision(c, s, iterations);
ASSERT_TRUE(actual_count < (expected_count + variance));
ASSERT_TRUE(actual_count > (expected_count - variance));
}
TEST(TraceIdRatioBasedSampler, TraceIdRatioBasedSamplerOnePercent)
{
double ratio = 0.01;
int iterations = 100000;
int expected_count = static_cast<int>(iterations * ratio);
int variance = static_cast<int>(iterations * 0.01);
trace_api::SpanContext c(true, true);
TraceIdRatioBasedSampler s(ratio);
int actual_count = RunShouldSampleCountDecision(c, s, iterations);
ASSERT_TRUE(actual_count < (expected_count + variance));
ASSERT_TRUE(actual_count > (expected_count - variance));
}
TEST(TraceIdRatioBasedSampler, TraceIdRatioBasedSamplerAll)
{
double ratio = 1.0;
int iterations = 100000;
int expected_count = static_cast<int>(iterations * ratio);
trace_api::SpanContext c(true, true);
TraceIdRatioBasedSampler s(ratio);
int actual_count = RunShouldSampleCountDecision(c, s, iterations);
ASSERT_EQ(actual_count, expected_count);
}
TEST(TraceIdRatioBasedSampler, TraceIdRatioBasedSamplerNone)
{
double ratio = 0.0;
int iterations = 100000;
int expected_count = static_cast<int>(iterations * ratio);
trace_api::SpanContext c(true, true);
TraceIdRatioBasedSampler s(ratio);
int actual_count = RunShouldSampleCountDecision(c, s, iterations);
ASSERT_EQ(actual_count, expected_count);
}
TEST(TraceIdRatioBasedSampler, GetDescription)
{
TraceIdRatioBasedSampler s1(0.01);
ASSERT_EQ("TraceIdRatioBasedSampler{0.010000}", s1.GetDescription());
TraceIdRatioBasedSampler s2(0.00);
ASSERT_EQ("TraceIdRatioBasedSampler{0.000000}", s2.GetDescription());
TraceIdRatioBasedSampler s3(1.00);
ASSERT_EQ("TraceIdRatioBasedSampler{1.000000}", s3.GetDescription());
TraceIdRatioBasedSampler s4(0.102030405);
ASSERT_EQ("TraceIdRatioBasedSampler{0.102030}", s4.GetDescription());
TraceIdRatioBasedSampler s5(3.00);
ASSERT_EQ("TraceIdRatioBasedSampler{1.000000}", s5.GetDescription());
TraceIdRatioBasedSampler s6(-3.00);
ASSERT_EQ("TraceIdRatioBasedSampler{0.000000}", s6.GetDescription());
TraceIdRatioBasedSampler s7(1.00000000001);
ASSERT_EQ("TraceIdRatioBasedSampler{1.000000}", s7.GetDescription());
TraceIdRatioBasedSampler s8(-1.00000000001);
ASSERT_EQ("TraceIdRatioBasedSampler{0.000000}", s8.GetDescription());
TraceIdRatioBasedSampler s9(0.50);
ASSERT_EQ("TraceIdRatioBasedSampler{0.500000}", s9.GetDescription());
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/borealis/borealis_task.h"
#include <memory>
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/chromeos/borealis/borealis_context.h"
#include "chrome/browser/chromeos/borealis/borealis_context_manager.h"
#include "chrome/browser/chromeos/borealis/borealis_metrics.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/dlcservice/fake_dlcservice_client.h"
#include "chromeos/dbus/fake_cicerone_client.h"
#include "chromeos/dbus/fake_concierge_client.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
using ::testing::_;
using ::testing::StrNe;
namespace borealis {
namespace {
class CallbackForTesting {
public:
BorealisTask::CompletionResultCallback GetCallback() {
return base::BindOnce(&CallbackForTesting::Callback,
base::Unretained(this));
}
MOCK_METHOD(void, Callback, (BorealisStartupResult, std::string), ());
};
class BorealisTasksTest : public testing::Test {
public:
BorealisTasksTest() = default;
~BorealisTasksTest() override = default;
// Disallow copy and assign.
BorealisTasksTest(const BorealisTasksTest&) = delete;
BorealisTasksTest& operator=(const BorealisTasksTest&) = delete;
protected:
void SetUp() override {
chromeos::DBusThreadManager::Initialize();
fake_concierge_client_ = static_cast<chromeos::FakeConciergeClient*>(
chromeos::DBusThreadManager::Get()->GetConciergeClient());
fake_cicerone_client_ = static_cast<chromeos::FakeCiceroneClient*>(
chromeos::DBusThreadManager::Get()->GetCiceroneClient());
CreateProfile();
context_ = BorealisContext::CreateBorealisContextForTesting(profile_.get());
context_->set_vm_name("borealis");
chromeos::DlcserviceClient::InitializeFake();
fake_dlcservice_client_ = static_cast<chromeos::FakeDlcserviceClient*>(
chromeos::DlcserviceClient::Get());
}
void TearDown() override {
profile_.reset();
context_.reset(); // must destroy before DBus shutdown
chromeos::DlcserviceClient::Shutdown();
chromeos::DBusThreadManager::Shutdown();
}
std::unique_ptr<TestingProfile> profile_;
std::unique_ptr<BorealisContext> context_;
content::BrowserTaskEnvironment task_environment_;
// Owned by chromeos::DBusThreadManager
chromeos::FakeConciergeClient* fake_concierge_client_;
chromeos::FakeCiceroneClient* fake_cicerone_client_;
chromeos::FakeDlcserviceClient* fake_dlcservice_client_;
private:
void CreateProfile() {
TestingProfile::Builder profile_builder;
profile_builder.SetProfileName("defaultprofile");
profile_ = profile_builder.Build();
}
};
TEST_F(BorealisTasksTest, MountDlcSucceedsAndCallbackRanWithResults) {
fake_dlcservice_client_->set_install_error(dlcservice::kErrorNone);
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
MountDlc task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
}
TEST_F(BorealisTasksTest, CreateDiskSucceedsAndCallbackRanWithResults) {
vm_tools::concierge::CreateDiskImageResponse response;
base::FilePath path = base::FilePath("test/path");
response.set_status(vm_tools::concierge::DISK_STATUS_CREATED);
response.set_disk_path(path.AsUTF8Unsafe());
fake_concierge_client_->set_create_disk_image_response(std::move(response));
EXPECT_EQ(context_->disk_path(), base::FilePath());
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
CreateDiskImage task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->create_disk_image_called());
EXPECT_EQ(context_->disk_path(), path);
}
TEST_F(BorealisTasksTest,
CreateDiskImageAlreadyExistsAndCallbackRanWithResults) {
vm_tools::concierge::CreateDiskImageResponse response;
base::FilePath path = base::FilePath("test/path");
response.set_status(vm_tools::concierge::DISK_STATUS_EXISTS);
response.set_disk_path(path.AsUTF8Unsafe());
fake_concierge_client_->set_create_disk_image_response(std::move(response));
EXPECT_EQ(context_->disk_path(), base::FilePath());
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
CreateDiskImage task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->create_disk_image_called());
EXPECT_EQ(context_->disk_path(), path);
}
TEST_F(BorealisTasksTest, StartBorealisVmSucceedsAndCallbackRanWithResults) {
vm_tools::concierge::StartVmResponse response;
response.set_status(vm_tools::concierge::VM_STATUS_STARTING);
fake_concierge_client_->set_start_vm_response(std::move(response));
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
StartBorealisVm task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called());
}
TEST_F(BorealisTasksTest,
StartBorealisVmVmAlreadyRunningAndCallbackRanWithResults) {
vm_tools::concierge::StartVmResponse response;
response.set_status(vm_tools::concierge::VM_STATUS_RUNNING);
fake_concierge_client_->set_start_vm_response(std::move(response));
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
StartBorealisVm task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called());
}
TEST_F(BorealisTasksTest,
AwaitBorealisStartupSucceedsAndCallbackRanWithResults) {
vm_tools::cicerone::ContainerStartedSignal signal;
signal.set_owner_id(
chromeos::ProfileHelper::GetUserIdHashFromProfile(context_->profile()));
signal.set_vm_name(context_->vm_name());
signal.set_container_name("penguin");
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
AwaitBorealisStartup task(context_->profile(), context_->vm_name());
task.Run(context_.get(), callback.GetCallback());
fake_cicerone_client_->NotifyContainerStarted(std::move(signal));
task_environment_.RunUntilIdle();
}
TEST_F(BorealisTasksTest,
AwaitBorealisStartupContainerAlreadyStartedAndCallbackRanWithResults) {
vm_tools::cicerone::ContainerStartedSignal signal;
signal.set_owner_id(
chromeos::ProfileHelper::GetUserIdHashFromProfile(context_->profile()));
signal.set_vm_name(context_->vm_name());
signal.set_container_name("penguin");
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback, Callback(BorealisStartupResult::kSuccess, _));
AwaitBorealisStartup task(context_->profile(), context_->vm_name());
fake_cicerone_client_->NotifyContainerStarted(std::move(signal));
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
}
TEST_F(BorealisTasksTest,
AwaitBorealisStartupTimesOutAndCallbackRanWithResults) {
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(
callback,
Callback(BorealisStartupResult::kAwaitBorealisStartupFailed, StrNe("")));
AwaitBorealisStartup task(context_->profile(), context_->vm_name());
task.GetWatcherForTesting().SetTimeoutForTesting(
base::TimeDelta::FromMilliseconds(0));
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
}
class BorealisTasksTestDlc : public BorealisTasksTest,
public testing::WithParamInterface<std::string> {};
TEST_P(BorealisTasksTestDlc, MountDlcFailsAndCallbackRanWithResults) {
fake_dlcservice_client_->set_install_error(GetParam());
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback,
Callback(BorealisStartupResult::kMountFailed, StrNe("")));
MountDlc task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
}
INSTANTIATE_TEST_SUITE_P(BorealisTasksTestDlcErrors,
BorealisTasksTestDlc,
testing::Values(dlcservice::kErrorInternal,
dlcservice::kErrorInvalidDlc,
dlcservice::kErrorBusy,
dlcservice::kErrorNeedReboot,
dlcservice::kErrorAllocation,
"unknown"));
class BorealisTasksTestDiskImage
: public BorealisTasksTest,
public testing::WithParamInterface<vm_tools::concierge::DiskImageStatus> {
};
TEST_P(BorealisTasksTestDiskImage, CreateDiskFailsAndCallbackRanWithResults) {
vm_tools::concierge::CreateDiskImageResponse response;
response.set_status(GetParam());
fake_concierge_client_->set_create_disk_image_response(std::move(response));
EXPECT_EQ(context_->disk_path(), base::FilePath());
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback,
Callback(BorealisStartupResult::kDiskImageFailed, StrNe("")));
CreateDiskImage task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->create_disk_image_called());
EXPECT_EQ(context_->disk_path(), base::FilePath());
}
INSTANTIATE_TEST_SUITE_P(
BorealisTasksTestCreateDiskImageErrors,
BorealisTasksTestDiskImage,
testing::Values(vm_tools::concierge::DISK_STATUS_UNKNOWN,
vm_tools::concierge::DISK_STATUS_FAILED,
vm_tools::concierge::DISK_STATUS_DOES_NOT_EXIST,
vm_tools::concierge::DISK_STATUS_DESTROYED,
vm_tools::concierge::DISK_STATUS_IN_PROGRESS,
vm_tools::concierge::DISK_STATUS_RESIZED));
class BorealisTasksTestsStartBorealisVm
: public BorealisTasksTest,
public testing::WithParamInterface<vm_tools::concierge::VmStatus> {};
TEST_P(BorealisTasksTestsStartBorealisVm,
StartBorealisVmErrorsAndCallbackRanWithResults) {
vm_tools::concierge::StartVmResponse response;
response.set_status(GetParam());
fake_concierge_client_->set_start_vm_response(std::move(response));
testing::StrictMock<CallbackForTesting> callback;
EXPECT_CALL(callback,
Callback(BorealisStartupResult::kStartVmFailed, StrNe("")));
StartBorealisVm task;
task.Run(context_.get(), callback.GetCallback());
task_environment_.RunUntilIdle();
EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called());
}
INSTANTIATE_TEST_SUITE_P(
BorealisTasksTestStartBorealisVmErrors,
BorealisTasksTestsStartBorealisVm,
testing::Values(vm_tools::concierge::VM_STATUS_UNKNOWN,
vm_tools::concierge::VM_STATUS_FAILURE));
} // namespace
} // namespace borealis
|
// Copyright (c) 2014-2019, The ByteRub Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/archive/portable_binary_iarchive.hpp>
#include <boost/archive/portable_binary_oarchive.hpp>
#include "common/unordered_containers_boost_serialization.h"
#include "common/command_line.h"
#include "common/varint.h"
#include "serialization/crypto.h"
#include "cryptonote_basic/cryptonote_boost_serialization.h"
#include "cryptonote_core/tx_pool.h"
#include "cryptonote_core/cryptonote_core.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/blockchain_db.h"
#include "wallet/ringdb.h"
#include "version.h"
#undef BYTERUB_DEFAULT_LOG_CATEGORY
#define BYTERUB_DEFAULT_LOG_CATEGORY "bcutil"
namespace po = boost::program_options;
using namespace epee;
using namespace cryptonote;
static const char zerokey[8] = {0};
static const MDB_val zerokval = { sizeof(zerokey), (void *)zerokey };
static uint64_t records_per_sync = 200;
static uint64_t db_flags = 0;
static MDB_dbi dbi_relative_rings;
static MDB_dbi dbi_outputs;
static MDB_dbi dbi_processed_txidx;
static MDB_dbi dbi_spent;
static MDB_dbi dbi_per_amount;
static MDB_dbi dbi_ring_instances;
static MDB_dbi dbi_stats;
static MDB_env *env = NULL;
struct output_data
{
uint64_t amount;
uint64_t offset;
output_data(): amount(0), offset(0) {}
output_data(uint64_t a, uint64_t i): amount(a), offset(i) {}
bool operator==(const output_data &other) const { return other.amount == amount && other.offset == offset; }
};
//
// relative_rings: key_image -> vector<uint64_t>
// outputs: 128 bits -> set of key images
// processed_txidx: string -> uint64_t
// spent: amount -> offset
// ring_instances: vector<uint64_t> -> uint64_t
// stats: string -> arbitrary
//
static bool parse_db_sync_mode(std::string db_sync_mode)
{
std::vector<std::string> options;
boost::trim(db_sync_mode);
boost::split(options, db_sync_mode, boost::is_any_of(" :"));
for(const auto &option : options)
MDEBUG("option: " << option);
// default to fast:async:1
uint64_t DEFAULT_FLAGS = DBF_FAST;
if(options.size() == 0)
{
// default to fast:async:1
db_flags = DEFAULT_FLAGS;
}
bool safemode = false;
if(options.size() >= 1)
{
if(options[0] == "safe")
{
safemode = true;
db_flags = DBF_SAFE;
}
else if(options[0] == "fast")
{
db_flags = DBF_FAST;
}
else if(options[0] == "fastest")
{
db_flags = DBF_FASTEST;
records_per_sync = 1000; // default to fastest:async:1000
}
else
db_flags = DEFAULT_FLAGS;
}
if(options.size() >= 2 && !safemode)
{
char *endptr;
uint64_t bps = strtoull(options[1].c_str(), &endptr, 0);
if (*endptr == '\0')
records_per_sync = bps;
}
return true;
}
static std::string get_default_db_path()
{
boost::filesystem::path dir = tools::get_default_data_dir();
// remove .bitbyterub, replace with .shared-ringdb
dir = dir.remove_filename();
dir /= ".shared-ringdb";
return dir.string();
}
static std::string get_cache_filename(boost::filesystem::path filename)
{
if (!boost::filesystem::is_directory(filename))
filename.remove_filename();
return filename.string();
}
static int compare_hash32(const MDB_val *a, const MDB_val *b)
{
const uint32_t *va = (const uint32_t*) a->mv_data;
const uint32_t *vb = (const uint32_t*) b->mv_data;
for (int n = 7; n >= 0; n--)
{
if (va[n] == vb[n])
continue;
return va[n] < vb[n] ? -1 : 1;
}
return 0;
}
int compare_uint64(const MDB_val *a, const MDB_val *b)
{
const uint64_t va = *(const uint64_t *)a->mv_data;
const uint64_t vb = *(const uint64_t *)b->mv_data;
return (va < vb) ? -1 : va > vb;
}
static int compare_double64(const MDB_val *a, const MDB_val *b)
{
const uint64_t va = *(const uint64_t*) a->mv_data;
const uint64_t vb = *(const uint64_t*) b->mv_data;
if (va == vb)
{
const uint64_t va = ((const uint64_t*) a->mv_data)[1];
const uint64_t vb = ((const uint64_t*) b->mv_data)[1];
return va < vb ? -1 : va > vb;
}
return va < vb ? -1 : va > vb;
}
static int resize_env(const char *db_path)
{
MDB_envinfo mei;
MDB_stat mst;
int ret;
size_t needed = 1000ul * 1024 * 1024; // at least 1000 MB
ret = mdb_env_info(env, &mei);
if (ret)
return ret;
ret = mdb_env_stat(env, &mst);
if (ret)
return ret;
uint64_t size_used = mst.ms_psize * mei.me_last_pgno;
uint64_t mapsize = mei.me_mapsize;
if (size_used + needed > mei.me_mapsize)
{
try
{
boost::filesystem::path path(db_path);
boost::filesystem::space_info si = boost::filesystem::space(path);
if(si.available < needed)
{
MERROR("!! WARNING: Insufficient free space to extend database !!: " << (si.available >> 20L) << " MB available");
return ENOSPC;
}
}
catch(...)
{
// print something but proceed.
MWARNING("Unable to query free disk space.");
}
mapsize += needed;
}
return mdb_env_set_mapsize(env, mapsize);
}
static void init(std::string cache_filename)
{
MDB_txn *txn;
bool tx_active = false;
int dbr;
MINFO("Creating spent output cache in " << cache_filename);
tools::create_directories_if_necessary(cache_filename);
int flags = 0;
if (db_flags & DBF_FAST)
flags |= MDB_NOSYNC;
if (db_flags & DBF_FASTEST)
flags |= MDB_NOSYNC | MDB_WRITEMAP | MDB_MAPASYNC;
dbr = mdb_env_create(&env);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(env, 7);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = get_cache_filename(cache_filename);
dbr = mdb_env_open(env, actual_filename.c_str(), flags, 0664);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
dbr = mdb_dbi_open(txn, "relative_rings", MDB_CREATE | MDB_INTEGERKEY, &dbi_relative_rings);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
mdb_set_compare(txn, dbi_relative_rings, compare_hash32);
dbr = mdb_dbi_open(txn, "outputs", MDB_CREATE | MDB_INTEGERKEY, &dbi_outputs);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
mdb_set_compare(txn, dbi_outputs, compare_double64);
dbr = mdb_dbi_open(txn, "processed_txidx", MDB_CREATE, &dbi_processed_txidx);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_dbi_open(txn, "spent", MDB_CREATE | MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, &dbi_spent);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
mdb_set_dupsort(txn, dbi_spent, compare_uint64);
dbr = mdb_dbi_open(txn, "per_amount", MDB_CREATE | MDB_INTEGERKEY, &dbi_per_amount);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
mdb_set_compare(txn, dbi_per_amount, compare_uint64);
dbr = mdb_dbi_open(txn, "ring_instances", MDB_CREATE, &dbi_ring_instances);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_dbi_open(txn, "stats", MDB_CREATE, &dbi_stats);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
tx_active = false;
}
static void close()
{
if (env)
{
mdb_dbi_close(env, dbi_relative_rings);
mdb_dbi_close(env, dbi_outputs);
mdb_dbi_close(env, dbi_processed_txidx);
mdb_dbi_close(env, dbi_per_amount);
mdb_dbi_close(env, dbi_spent);
mdb_dbi_close(env, dbi_ring_instances);
mdb_dbi_close(env, dbi_stats);
mdb_env_close(env);
env = NULL;
}
}
static std::string compress_ring(const std::vector<uint64_t> &ring, std::string s = "")
{
const size_t sz = s.size();
s.resize(s.size() + 12 * ring.size());
char *ptr = (char*)s.data() + sz;
for (uint64_t out: ring)
tools::write_varint(ptr, out);
if (ptr > s.data() + sz + 12 * ring.size())
throw std::runtime_error("varint output overflow");
s.resize(ptr - s.data());
return s;
}
static std::string compress_ring(uint64_t amount, const std::vector<uint64_t> &ring)
{
char s[12], *ptr = s;
tools::write_varint(ptr, amount);
if (ptr > s + sizeof(s))
throw std::runtime_error("varint output overflow");
return compress_ring(ring, std::string(s, ptr-s));
}
static std::vector<uint64_t> decompress_ring(const std::string &s)
{
std::vector<uint64_t> ring;
int read = 0;
for (std::string::const_iterator i = s.begin(); i != s.cend(); std::advance(i, read))
{
uint64_t out;
std::string tmp(i, s.cend());
read = tools::read_varint(tmp.begin(), tmp.end(), out);
CHECK_AND_ASSERT_THROW_MES(read > 0 && read <= 256, "Internal error decompressing ring");
ring.push_back(out);
}
return ring;
}
static bool for_all_transactions(const std::string &filename, uint64_t &start_idx, uint64_t &n_txes, const std::function<bool(const cryptonote::transaction_prefix&)> &f)
{
MDB_env *env;
MDB_dbi dbi;
MDB_txn *txn;
MDB_cursor *cur;
int dbr;
bool tx_active = false;
MDB_val k;
MDB_val v;
dbr = mdb_env_create(&env);
if (dbr) throw std::runtime_error("Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(env, 2);
if (dbr) throw std::runtime_error("Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = filename;
dbr = mdb_env_open(env, actual_filename.c_str(), 0, 0664);
if (dbr) throw std::runtime_error("Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (dbr) throw std::runtime_error("Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
dbr = mdb_dbi_open(txn, "txs_pruned", MDB_INTEGERKEY, &dbi);
if (dbr)
dbr = mdb_dbi_open(txn, "txs", MDB_INTEGERKEY, &dbi);
if (dbr) throw std::runtime_error("Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_open(txn, dbi, &cur);
if (dbr) throw std::runtime_error("Failed to create LMDB cursor: " + std::string(mdb_strerror(dbr)));
MDB_stat stat;
dbr = mdb_stat(txn, dbi, &stat);
if (dbr) throw std::runtime_error("Failed to query m_block_info: " + std::string(mdb_strerror(dbr)));
n_txes = stat.ms_entries;
bool fret = true;
k.mv_size = sizeof(uint64_t);
k.mv_data = &start_idx;
MDB_cursor_op op = MDB_SET;
while (1)
{
int ret = mdb_cursor_get(cur, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw std::runtime_error("Failed to enumerate transactions: " + std::string(mdb_strerror(ret)));
if (k.mv_size != sizeof(uint64_t))
throw std::runtime_error("Bad key size");
const uint64_t idx = *(uint64_t*)k.mv_data;
if (idx < start_idx)
continue;
cryptonote::transaction_prefix tx;
blobdata bd;
bd.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
std::stringstream ss;
ss << bd;
binary_archive<false> ba(ss);
bool r = do_serialize(ba, tx);
CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
start_idx = *(uint64_t*)k.mv_data;
if (!f(tx)) {
fret = false;
break;
}
}
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
if (dbr) throw std::runtime_error("Failed to commit db transaction: " + std::string(mdb_strerror(dbr)));
tx_active = false;
mdb_dbi_close(env, dbi);
mdb_env_close(env);
return fret;
}
static bool for_all_transactions(const std::string &filename, const uint64_t &start_idx, uint64_t &n_txes, const std::function<bool(bool, uint64_t, const cryptonote::transaction_prefix&)> &f)
{
MDB_env *env;
MDB_dbi dbi_blocks, dbi_txs;
MDB_txn *txn;
MDB_cursor *cur_blocks, *cur_txs;
int dbr;
bool tx_active = false;
MDB_val k;
MDB_val v;
dbr = mdb_env_create(&env);
if (dbr) throw std::runtime_error("Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(env, 3);
if (dbr) throw std::runtime_error("Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = filename;
dbr = mdb_env_open(env, actual_filename.c_str(), 0, 0664);
if (dbr) throw std::runtime_error("Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (dbr) throw std::runtime_error("Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
dbr = mdb_dbi_open(txn, "blocks", MDB_INTEGERKEY, &dbi_blocks);
if (dbr) throw std::runtime_error("Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_dbi_open(txn, "txs_pruned", MDB_INTEGERKEY, &dbi_txs);
if (dbr) throw std::runtime_error("Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_open(txn, dbi_blocks, &cur_blocks);
if (dbr) throw std::runtime_error("Failed to create LMDB cursor: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_open(txn, dbi_txs, &cur_txs);
if (dbr) throw std::runtime_error("Failed to create LMDB cursor: " + std::string(mdb_strerror(dbr)));
MDB_stat stat;
dbr = mdb_stat(txn, dbi_blocks, &stat);
if (dbr) throw std::runtime_error("Failed to query txs stat: " + std::string(mdb_strerror(dbr)));
uint64_t n_blocks = stat.ms_entries;
dbr = mdb_stat(txn, dbi_txs, &stat);
if (dbr) throw std::runtime_error("Failed to query txs stat: " + std::string(mdb_strerror(dbr)));
n_txes = stat.ms_entries;
bool fret = true;
MDB_cursor_op op_blocks = MDB_FIRST;
MDB_cursor_op op_txs = MDB_FIRST;
uint64_t tx_idx = 0;
while (1)
{
int ret = mdb_cursor_get(cur_blocks, &k, &v, op_blocks);
op_blocks = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw std::runtime_error("Failed to enumerate blocks: " + std::string(mdb_strerror(ret)));
if (k.mv_size != sizeof(uint64_t))
throw std::runtime_error("Bad key size");
uint64_t height = *(const uint64_t*)k.mv_data;
blobdata bd;
bd.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
block b;
if (!parse_and_validate_block_from_blob(bd, b))
throw std::runtime_error("Failed to parse block from blob retrieved from the db");
ret = mdb_cursor_get(cur_txs, &k, &v, op_txs);
if (ret)
throw std::runtime_error("Failed to fetch transaction " + string_tools::pod_to_hex(get_transaction_hash(b.miner_tx)) + ": " + std::string(mdb_strerror(ret)));
op_txs = MDB_NEXT;
bool last_block = height == n_blocks - 1;
if (start_idx <= tx_idx++ && !f(last_block && b.tx_hashes.empty(), height, b.miner_tx))
{
fret = false;
break;
}
for (size_t i = 0; i < b.tx_hashes.size(); ++i)
{
const crypto::hash& txid = b.tx_hashes[i];
ret = mdb_cursor_get(cur_txs, &k, &v, op_txs);
if (ret)
throw std::runtime_error("Failed to fetch transaction " + string_tools::pod_to_hex(txid) + ": " + std::string(mdb_strerror(ret)));
if (start_idx <= tx_idx++)
{
cryptonote::transaction_prefix tx;
bd.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
CHECK_AND_ASSERT_MES(parse_and_validate_tx_prefix_from_blob(bd, tx), false, "Failed to parse transaction from blob");
if (!f(last_block && i == b.tx_hashes.size() - 1, height, tx))
{
fret = false;
break;
}
}
}
if (!fret)
break;
}
mdb_cursor_close(cur_blocks);
mdb_cursor_close(cur_txs);
mdb_txn_commit(txn);
tx_active = false;
mdb_dbi_close(env, dbi_blocks);
mdb_dbi_close(env, dbi_txs);
mdb_env_close(env);
return fret;
}
static uint64_t find_first_diverging_transaction(const std::string &first_filename, const std::string &second_filename)
{
MDB_env *env[2];
MDB_dbi dbi[2];
MDB_txn *txn[2];
MDB_cursor *cur[2];
int dbr;
bool tx_active[2] = { false, false };
uint64_t n_txes[2];
MDB_val k;
MDB_val v[2];
epee::misc_utils::auto_scope_leave_caller txn_dtor[2];
for (int i = 0; i < 2; ++i)
{
dbr = mdb_env_create(&env[i]);
if (dbr) throw std::runtime_error("Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(env[i], 2);
if (dbr) throw std::runtime_error("Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = i ? second_filename : first_filename;
dbr = mdb_env_open(env[i], actual_filename.c_str(), 0, 0664);
if (dbr) throw std::runtime_error("Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env[i], NULL, MDB_RDONLY, &txn[i]);
if (dbr) throw std::runtime_error("Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
txn_dtor[i] = epee::misc_utils::create_scope_leave_handler([&, i](){if (tx_active[i]) mdb_txn_abort(txn[i]);});
tx_active[i] = true;
dbr = mdb_dbi_open(txn[i], "txs_pruned", MDB_INTEGERKEY, &dbi[i]);
if (dbr)
dbr = mdb_dbi_open(txn[i], "txs", MDB_INTEGERKEY, &dbi[i]);
if (dbr) throw std::runtime_error("Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_open(txn[i], dbi[i], &cur[i]);
if (dbr) throw std::runtime_error("Failed to create LMDB cursor: " + std::string(mdb_strerror(dbr)));
MDB_stat stat;
dbr = mdb_stat(txn[i], dbi[i], &stat);
if (dbr) throw std::runtime_error("Failed to query m_block_info: " + std::string(mdb_strerror(dbr)));
n_txes[i] = stat.ms_entries;
}
if (n_txes[0] == 0 || n_txes[1] == 0)
throw std::runtime_error("No transaction in the database");
uint64_t lo = 0, hi = std::min(n_txes[0], n_txes[1]) - 1;
while (lo <= hi)
{
uint64_t mid = (lo + hi) / 2;
k.mv_size = sizeof(uint64_t);
k.mv_data = (void*)∣
dbr = mdb_cursor_get(cur[0], &k, &v[0], MDB_SET);
if (dbr) throw std::runtime_error("Failed to query transaction: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_get(cur[1], &k, &v[1], MDB_SET);
if (dbr) throw std::runtime_error("Failed to query transaction: " + std::string(mdb_strerror(dbr)));
if (v[0].mv_size == v[1].mv_size && !memcmp(v[0].mv_data, v[1].mv_data, v[0].mv_size))
lo = mid + 1;
else
hi = mid - 1;
}
for (int i = 0; i < 2; ++i)
{
mdb_cursor_close(cur[i]);
dbr = mdb_txn_commit(txn[i]);
if (dbr) throw std::runtime_error("Failed to query transaction: " + std::string(mdb_strerror(dbr)));
tx_active[i] = false;
mdb_dbi_close(env[i], dbi[i]);
mdb_env_close(env[i]);
}
return hi;
}
static std::vector<uint64_t> canonicalize(const std::vector<uint64_t> &v)
{
std::vector<uint64_t> c;
c.reserve(v.size());
c.push_back(v[0]);
for (size_t n = 1; n < v.size(); ++n)
{
if (v[n] != 0)
c.push_back(v[n]);
}
if (c.size() < v.size())
{
MINFO("Ring has duplicate member(s): " <<
boost::join(v | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " "));
}
return c;
}
static uint64_t get_num_spent_outputs()
{
MDB_txn *txn;
bool tx_active = false;
int dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open cursor for spent outputs: " + std::string(mdb_strerror(dbr)));
MDB_val k, v;
mdb_size_t count = 0, tmp;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
dbr = mdb_cursor_get(cur, &k, &v, op);
op = MDB_NEXT_NODUP;
if (dbr == MDB_NOTFOUND)
break;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get first/next spent output: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_count(cur, &tmp);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to count entries: " + std::string(mdb_strerror(dbr)));
count += tmp;
}
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn: " + std::string(mdb_strerror(dbr)));
tx_active = false;
return count;
}
static bool add_spent_output(MDB_cursor *cur, const output_data &od)
{
MDB_val k = {sizeof(od.amount), (void*)&od.amount};
MDB_val v = {sizeof(od.offset), (void*)&od.offset};
int dbr = mdb_cursor_put(cur, &k, &v, MDB_NODUPDATA);
if (dbr == MDB_KEYEXIST)
return false;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to add spent output: " + std::string(mdb_strerror(dbr)));
return true;
}
static bool is_output_spent(MDB_cursor *cur, const output_data &od)
{
MDB_val k = {sizeof(od.amount), (void*)&od.amount};
MDB_val v = {sizeof(od.offset), (void*)&od.offset};
int dbr = mdb_cursor_get(cur, &k, &v, MDB_GET_BOTH);
CHECK_AND_ASSERT_THROW_MES(!dbr || dbr == MDB_NOTFOUND, "Failed to get spent output: " + std::string(mdb_strerror(dbr)));
bool spent = dbr == 0;
return spent;
}
static std::vector<output_data> get_spent_outputs(MDB_txn *txn)
{
MDB_cursor *cur;
int dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open cursor for spent outputs: " + std::string(mdb_strerror(dbr)));
MDB_val k, v;
mdb_size_t count = 0;
dbr = mdb_cursor_get(cur, &k, &v, MDB_FIRST);
if (dbr != MDB_NOTFOUND)
{
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get first spent output: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_count(cur, &count);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to count entries: " + std::string(mdb_strerror(dbr)));
}
std::vector<output_data> outs;
outs.reserve(count);
while (1)
{
outs.push_back({*(const uint64_t*)k.mv_data, *(const uint64_t*)v.mv_data});
dbr = mdb_cursor_get(cur, &k, &v, MDB_NEXT);
if (dbr == MDB_NOTFOUND)
break;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get next spent output: " + std::string(mdb_strerror(dbr)));
}
mdb_cursor_close(cur);
return outs;
}
static void get_per_amount_outputs(MDB_txn *txn, uint64_t amount, uint64_t &total, uint64_t &spent)
{
MDB_cursor *cur;
int dbr = mdb_cursor_open(txn, dbi_per_amount, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open cursor for per amount outputs: " + std::string(mdb_strerror(dbr)));
MDB_val k, v;
mdb_size_t count = 0;
k.mv_size = sizeof(uint64_t);
k.mv_data = (void*)&amount;
dbr = mdb_cursor_get(cur, &k, &v, MDB_SET);
if (dbr == MDB_NOTFOUND)
{
total = spent = 0;
}
else
{
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get per amount outputs: " + std::string(mdb_strerror(dbr)));
total = ((const uint64_t*)v.mv_data)[0];
spent = ((const uint64_t*)v.mv_data)[1];
}
mdb_cursor_close(cur);
}
static void inc_per_amount_outputs(MDB_txn *txn, uint64_t amount, uint64_t total, uint64_t spent)
{
MDB_cursor *cur;
int dbr = mdb_cursor_open(txn, dbi_per_amount, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open cursor for per amount outputs: " + std::string(mdb_strerror(dbr)));
MDB_val k, v;
mdb_size_t count = 0;
k.mv_size = sizeof(uint64_t);
k.mv_data = (void*)&amount;
dbr = mdb_cursor_get(cur, &k, &v, MDB_SET);
if (dbr == 0)
{
total += ((const uint64_t*)v.mv_data)[0];
spent += ((const uint64_t*)v.mv_data)[1];
}
else
{
CHECK_AND_ASSERT_THROW_MES(dbr == MDB_NOTFOUND, "Failed to get per amount outputs: " + std::string(mdb_strerror(dbr)));
}
uint64_t data[2] = {total, spent};
v.mv_size = 2 * sizeof(uint64_t);
v.mv_data = (void*)data;
dbr = mdb_cursor_put(cur, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to write record for per amount outputs: " + std::string(mdb_strerror(dbr)));
mdb_cursor_close(cur);
}
static uint64_t get_processed_txidx(const std::string &name)
{
MDB_txn *txn;
bool tx_active = false;
int dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
uint64_t height = 0;
MDB_val k, v;
k.mv_data = (void*)name.c_str();
k.mv_size = name.size();
dbr = mdb_get(txn, dbi_processed_txidx, &k, &v);
if (dbr != MDB_NOTFOUND)
{
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get processed height: " + std::string(mdb_strerror(dbr)));
height = *(const uint64_t*)v.mv_data;
}
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn: " + std::string(mdb_strerror(dbr)));
tx_active = false;
return height;
}
static void set_processed_txidx(MDB_txn *txn, const std::string &name, uint64_t height)
{
MDB_val k, v;
k.mv_data = (void*)name.c_str();
k.mv_size = name.size();
v.mv_data = (void*)&height;
v.mv_size = sizeof(height);
int dbr = mdb_put(txn, dbi_processed_txidx, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set processed height: " + std::string(mdb_strerror(dbr)));
}
static bool get_relative_ring(MDB_txn *txn, const crypto::key_image &ki, std::vector<uint64_t> &ring)
{
MDB_val k, v;
k.mv_data = (void*)&ki;
k.mv_size = sizeof(ki);
int dbr = mdb_get(txn, dbi_relative_rings, &k, &v);
if (dbr == MDB_NOTFOUND)
return false;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get relative ring: " + std::string(mdb_strerror(dbr)));
ring = decompress_ring(std::string((const char*)v.mv_data, v.mv_size));
return true;
}
static void set_relative_ring(MDB_txn *txn, const crypto::key_image &ki, const std::vector<uint64_t> &ring)
{
const std::string sring = compress_ring(ring);
MDB_val k, v;
k.mv_data = (void*)&ki;
k.mv_size = sizeof(ki);
v.mv_data = (void*)sring.c_str();
v.mv_size = sring.size();
int dbr = mdb_put(txn, dbi_relative_rings, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set relative ring: " + std::string(mdb_strerror(dbr)));
}
static std::string keep_under_511(const std::string &s)
{
if (s.size() <= 511)
return s;
crypto::hash hash;
crypto::cn_fast_hash(s.data(), s.size(), hash);
return std::string((const char*)&hash, 32);
}
static uint64_t get_ring_instances(MDB_txn *txn, uint64_t amount, const std::vector<uint64_t> &ring)
{
const std::string sring = keep_under_511(compress_ring(amount, ring));
MDB_val k, v;
k.mv_data = (void*)sring.data();
k.mv_size = sring.size();
int dbr = mdb_get(txn, dbi_ring_instances, &k, &v);
if (dbr == MDB_NOTFOUND)
return 0;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get ring instances: " + std::string(mdb_strerror(dbr)));
return *(const uint64_t*)v.mv_data;
}
static uint64_t get_ring_subset_instances(MDB_txn *txn, uint64_t amount, const std::vector<uint64_t> &ring)
{
uint64_t instances = get_ring_instances(txn, amount, ring);
if (ring.size() > 11)
return instances;
uint64_t extra = 0;
std::vector<uint64_t> subset;
subset.reserve(ring.size());
for (uint64_t mask = 1; mask < (((uint64_t)1) << ring.size()) - 1; ++mask)
{
subset.resize(0);
for (size_t i = 0; i < ring.size(); ++i)
if ((mask >> i) & 1)
subset.push_back(ring[i]);
extra += get_ring_instances(txn, amount, subset);
}
return instances + extra;
}
static uint64_t inc_ring_instances(MDB_txn *txn, uint64_t amount, const std::vector<uint64_t> &ring)
{
const std::string sring = keep_under_511(compress_ring(amount, ring));
MDB_val k, v;
k.mv_data = (void*)sring.data();
k.mv_size = sring.size();
int dbr = mdb_get(txn, dbi_ring_instances, &k, &v);
CHECK_AND_ASSERT_THROW_MES(!dbr || dbr == MDB_NOTFOUND, "Failed to get ring instances: " + std::string(mdb_strerror(dbr)));
uint64_t count;
if (dbr == MDB_NOTFOUND)
count = 1;
else
count = 1 + *(const uint64_t*)v.mv_data;
v.mv_data = &count;
v.mv_size = sizeof(count);
dbr = mdb_put(txn, dbi_ring_instances, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set ring instances: " + std::string(mdb_strerror(dbr)));
return count;
}
static std::vector<crypto::key_image> get_key_images(MDB_txn *txn, const output_data &od)
{
MDB_val k, v;
k.mv_data = (void*)&od;
k.mv_size = sizeof(od);
int dbr = mdb_get(txn, dbi_outputs, &k, &v);
CHECK_AND_ASSERT_THROW_MES(!dbr || dbr == MDB_NOTFOUND, "Failed to get output: " + std::string(mdb_strerror(dbr)));
if (dbr == MDB_NOTFOUND)
return {};
CHECK_AND_ASSERT_THROW_MES(v.mv_size % 32 == 0, "Unexpected record size");
std::vector<crypto::key_image> key_images;
key_images.reserve(v.mv_size / 32);
const crypto::key_image *ki = (const crypto::key_image*)v.mv_data;
for (size_t n = 0; n < v.mv_size / 32; ++n)
key_images.push_back(*ki++);
return key_images;
}
static void add_key_image(MDB_txn *txn, const output_data &od, const crypto::key_image &ki)
{
MDB_val k, v;
k.mv_data = (void*)&od;
k.mv_size = sizeof(od);
int dbr = mdb_get(txn, dbi_outputs, &k, &v);
CHECK_AND_ASSERT_THROW_MES(!dbr || dbr == MDB_NOTFOUND, "Failed to get output");
std::string data;
if (!dbr)
{
CHECK_AND_ASSERT_THROW_MES(v.mv_size % 32 == 0, "Unexpected record size");
data = std::string((const char*)v.mv_data, v.mv_size);
}
data += std::string((const char*)&ki, sizeof(ki));
v.mv_data = (void*)data.data();
v.mv_size = data.size();
dbr = mdb_put(txn, dbi_outputs, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set outputs: " + std::string(mdb_strerror(dbr)));
}
static bool get_stat(MDB_txn *txn, const char *key, uint64_t &data)
{
MDB_val k, v;
k.mv_data = (void*)key;
k.mv_size = strlen(key);
int dbr = mdb_get(txn, dbi_stats, &k, &v);
if (dbr == MDB_NOTFOUND)
return false;
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to get stat record");
CHECK_AND_ASSERT_THROW_MES(v.mv_size == sizeof(uint64_t), "Unexpected record size");
data = *(const uint64_t*)v.mv_data;
return true;
}
static void set_stat(MDB_txn *txn, const char *key, uint64_t data)
{
MDB_val k, v;
k.mv_data = (void*)key;
k.mv_size = strlen(key);
v.mv_data = (void*)&data;
v.mv_size = sizeof(uint64_t);
int dbr = mdb_put(txn, dbi_stats, &k, &v, 0);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set stat record");
}
static void inc_stat(MDB_txn *txn, const char *key)
{
uint64_t data;
if (!get_stat(txn, key, data))
data = 0;
++data;
set_stat(txn, key, data);
}
static void open_db(const std::string &filename, MDB_env **env, MDB_txn **txn, MDB_cursor **cur, MDB_dbi *dbi)
{
tools::create_directories_if_necessary(filename);
int flags = MDB_RDONLY;
if (db_flags & DBF_FAST)
flags |= MDB_NOSYNC;
if (db_flags & DBF_FASTEST)
flags |= MDB_NOSYNC | MDB_WRITEMAP | MDB_MAPASYNC;
int dbr = mdb_env_create(env);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(*env, 1);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = filename;
MINFO("Opening byterub blockchain at " << actual_filename);
dbr = mdb_env_open(*env, actual_filename.c_str(), flags, 0664);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(*env, NULL, MDB_RDONLY, txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
dbr = mdb_dbi_open(*txn, "output_amounts", MDB_CREATE | MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, dbi);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
mdb_set_dupsort(*txn, *dbi, compare_uint64);
dbr = mdb_cursor_open(*txn, *dbi, cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB cursor: " + std::string(mdb_strerror(dbr)));
}
static void close_db(MDB_env *env, MDB_txn *txn, MDB_cursor *cur, MDB_dbi dbi)
{
mdb_txn_abort(txn);
mdb_cursor_close(cur);
mdb_dbi_close(env, dbi);
mdb_env_close(env);
}
static void get_num_outputs(MDB_txn *txn, MDB_cursor *cur, MDB_dbi dbi, uint64_t &pre_rct, uint64_t &rct)
{
uint64_t amount = 0;
MDB_val k = { sizeof(amount), (void*)&amount }, v;
int dbr = mdb_cursor_get(cur, &k, &v, MDB_SET);
if (dbr == MDB_NOTFOUND)
{
rct = 0;
}
else
{
if (dbr) throw std::runtime_error("Record 0 not found: " + std::string(mdb_strerror(dbr)));
mdb_size_t count = 0;
dbr = mdb_cursor_count(cur, &count);
if (dbr) throw std::runtime_error("Failed to count records: " + std::string(mdb_strerror(dbr)));
rct = count;
}
MDB_stat s;
dbr = mdb_stat(txn, dbi, &s);
if (dbr) throw std::runtime_error("Failed to count records: " + std::string(mdb_strerror(dbr)));
if (s.ms_entries < rct) throw std::runtime_error("Inconsistent records: " + std::string(mdb_strerror(dbr)));
pre_rct = s.ms_entries - rct;
}
static crypto::hash get_genesis_block_hash(const std::string &filename)
{
MDB_env *env;
MDB_dbi dbi;
MDB_txn *txn;
int dbr;
bool tx_active = false;
dbr = mdb_env_create(&env);
if (dbr) throw std::runtime_error("Failed to create LDMB environment: " + std::string(mdb_strerror(dbr)));
dbr = mdb_env_set_maxdbs(env, 1);
if (dbr) throw std::runtime_error("Failed to set max env dbs: " + std::string(mdb_strerror(dbr)));
const std::string actual_filename = filename;
dbr = mdb_env_open(env, actual_filename.c_str(), 0, 0664);
if (dbr) throw std::runtime_error("Failed to open rings database file '"
+ actual_filename + "': " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (dbr) throw std::runtime_error("Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);});
tx_active = true;
dbr = mdb_dbi_open(txn, "block_info", MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, &dbi);
mdb_set_dupsort(txn, dbi, compare_uint64);
if (dbr) throw std::runtime_error("Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr)));
uint64_t zero = 0;
MDB_val k = { sizeof(uint64_t), (void*)&zero}, v;
dbr = mdb_get(txn, dbi, &k, &v);
if (dbr) throw std::runtime_error("Failed to retrieve genesis block: " + std::string(mdb_strerror(dbr)));
crypto::hash genesis_block_hash = *(const crypto::hash*)(((const uint64_t*)v.mv_data) + 5);
mdb_dbi_close(env, dbi);
mdb_txn_abort(txn);
mdb_env_close(env);
tx_active = false;
return genesis_block_hash;
}
static std::vector<std::pair<uint64_t, uint64_t>> load_outputs(const std::string &filename)
{
std::vector<std::pair<uint64_t, uint64_t>> outputs;
uint64_t amount = std::numeric_limits<uint64_t>::max();
FILE *f;
f = fopen(filename.c_str(), "r");
if (!f)
{
MERROR("Failed to load outputs from " << filename << ": " << strerror(errno));
return {};
}
while (1)
{
char s[256];
if (!fgets(s, sizeof(s), f))
{
MERROR("Error reading from " << filename << ": " << strerror(errno));
break;
}
if (feof(f))
break;
const size_t len = strlen(s);
if (len > 0 && s[len - 1] == '\n')
s[len - 1] = 0;
if (!s[0])
continue;
std::pair<uint64_t, uint64_t> output;
uint64_t offset, num_offsets;
if (sscanf(s, "@%" PRIu64, &amount) == 1)
{
continue;
}
if (amount == std::numeric_limits<uint64_t>::max())
{
MERROR("Bad format in " << filename);
continue;
}
if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits<uint64_t>::max() - offset)
{
while (num_offsets-- > 0)
outputs.push_back(std::make_pair(amount, offset++));
}
else if (sscanf(s, "%" PRIu64, &offset) == 1)
{
outputs.push_back(std::make_pair(amount, offset));
}
else
{
MERROR("Bad format in " << filename);
continue;
}
}
fclose(f);
return outputs;
}
static bool export_spent_outputs(MDB_cursor *cur, const std::string &filename)
{
FILE *f = fopen(filename.c_str(), "w");
if (!f)
{
MERROR("Failed to open " << filename << ": " << strerror(errno));
return false;
}
uint64_t pending_amount = std::numeric_limits<uint64_t>::max();
std::vector<uint64_t> pending_offsets;
MDB_val k, v;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int dbr = mdb_cursor_get(cur, &k, &v, op);
if (dbr == MDB_NOTFOUND)
break;
op = MDB_NEXT;
if (dbr)
{
fclose(f);
MERROR("Failed to enumerate spent outputs: " << mdb_strerror(dbr));
return false;
}
const uint64_t amount = *(const uint64_t*)k.mv_data;
const uint64_t offset = *(const uint64_t*)v.mv_data;
if (!pending_offsets.empty() && (amount != pending_amount || pending_offsets.back()+1 != offset))
{
if (pending_offsets.size() == 1)
fprintf(f, "%" PRIu64 "\n", pending_offsets.front());
else
fprintf(f, "%" PRIu64 "*%zu\n", pending_offsets.front(), pending_offsets.size());
pending_offsets.clear();
}
if (pending_amount != amount)
{
fprintf(f, "@%" PRIu64 "\n", amount);
pending_amount = amount;
}
pending_offsets.push_back(offset);
}
if (!pending_offsets.empty())
{
if (pending_offsets.size() == 1)
fprintf(f, "%" PRIu64 "\n", pending_offsets.front());
else
fprintf(f, "%" PRIu64 "*%zu\n", pending_offsets.front(), pending_offsets.size());
pending_offsets.clear();
}
fclose(f);
return true;
}
int main(int argc, char* argv[])
{
TRY_ENTRY();
epee::string_tools::set_module_name_and_folder(argv[0]);
uint32_t log_level = 0;
tools::on_startup();
boost::filesystem::path output_file_path;
po::options_description desc_cmd_only("Command line options");
po::options_description desc_cmd_sett("Command line options and settings options");
const command_line::arg_descriptor<std::string> arg_blackball_db_dir = {
"spent-output-db-dir", "Specify spent output database directory",
get_default_db_path(),
};
const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
const command_line::arg_descriptor<bool> arg_rct_only = {"rct-only", "Only work on ringCT outputs", false};
const command_line::arg_descriptor<bool> arg_check_subsets = {"check-subsets", "Check ring subsets (very expensive)", false};
const command_line::arg_descriptor<bool> arg_verbose = {"verbose", "Verbose output)", false};
const command_line::arg_descriptor<std::vector<std::string> > arg_inputs = {"inputs", "Path to ByteRub DB, and path to any fork DBs"};
const command_line::arg_descriptor<std::string> arg_db_sync_mode = {
"db-sync-mode"
, "Specify sync option, using format [safe|fast|fastest]:[nrecords_per_sync]."
, "fast:1000"
};
const command_line::arg_descriptor<std::string> arg_extra_spent_list = {"extra-spent-list", "Optional list of known spent outputs",""};
const command_line::arg_descriptor<std::string> arg_export = {"export", "Filename to export the backball list to"};
const command_line::arg_descriptor<bool> arg_force_chain_reaction_pass = {"force-chain-reaction-pass", "Run the chain reaction pass even if no new blockchain data was processed"};
const command_line::arg_descriptor<bool> arg_historical_stat = {"historical-stat", "Report historical stat of spent outputs for every 10000 blocks window"};
command_line::add_arg(desc_cmd_sett, arg_blackball_db_dir);
command_line::add_arg(desc_cmd_sett, arg_log_level);
command_line::add_arg(desc_cmd_sett, arg_rct_only);
command_line::add_arg(desc_cmd_sett, arg_check_subsets);
command_line::add_arg(desc_cmd_sett, arg_verbose);
command_line::add_arg(desc_cmd_sett, arg_db_sync_mode);
command_line::add_arg(desc_cmd_sett, arg_extra_spent_list);
command_line::add_arg(desc_cmd_sett, arg_export);
command_line::add_arg(desc_cmd_sett, arg_force_chain_reaction_pass);
command_line::add_arg(desc_cmd_sett, arg_historical_stat);
command_line::add_arg(desc_cmd_sett, arg_inputs);
command_line::add_arg(desc_cmd_only, command_line::arg_help);
po::options_description desc_options("Allowed options");
desc_options.add(desc_cmd_only).add(desc_cmd_sett);
po::positional_options_description positional_options;
positional_options.add(arg_inputs.name, -1);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_options, [&]()
{
auto parser = po::command_line_parser(argc, argv).options(desc_options).positional(positional_options);
po::store(parser.run(), vm);
po::notify(vm);
return true;
});
if (! r)
return 1;
if (command_line::get_arg(vm, command_line::arg_help))
{
std::cout << "ByteRub '" << BYTERUB_RELEASE_NAME << "' (v" << BYTERUB_VERSION_FULL << ")" << ENDL << ENDL;
std::cout << desc_options << std::endl;
return 1;
}
mlog_configure(mlog_get_default_log_path("byterub-blockchain-mark-spent-outputs.log"), true);
if (!command_line::is_arg_defaulted(vm, arg_log_level))
mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
else
mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
LOG_PRINT_L0("Starting...");
output_file_path = command_line::get_arg(vm, arg_blackball_db_dir);
bool opt_rct_only = command_line::get_arg(vm, arg_rct_only);
bool opt_check_subsets = command_line::get_arg(vm, arg_check_subsets);
bool opt_verbose = command_line::get_arg(vm, arg_verbose);
bool opt_force_chain_reaction_pass = command_line::get_arg(vm, arg_force_chain_reaction_pass);
bool opt_historical_stat = command_line::get_arg(vm, arg_historical_stat);
std::string opt_export = command_line::get_arg(vm, arg_export);
std::string extra_spent_list = command_line::get_arg(vm, arg_extra_spent_list);
std::vector<std::pair<uint64_t, uint64_t>> extra_spent_outputs = extra_spent_list.empty() ? std::vector<std::pair<uint64_t, uint64_t>>() : load_outputs(extra_spent_list);
std::string db_sync_mode = command_line::get_arg(vm, arg_db_sync_mode);
if (!parse_db_sync_mode(db_sync_mode))
{
MERROR("Invalid db sync mode: " << db_sync_mode);
return 1;
}
const std::vector<std::string> inputs = command_line::get_arg(vm, arg_inputs);
if (inputs.empty())
{
LOG_PRINT_L0("No inputs given");
return 1;
}
const std::string cache_dir = (output_file_path / "spent-outputs-cache").string();
init(cache_dir);
LOG_PRINT_L0("Scanning for spent outputs...");
size_t done = 0;
const uint64_t start_blackballed_outputs = get_num_spent_outputs();
tools::ringdb ringdb(output_file_path.string(), epee::string_tools::pod_to_hex(get_genesis_block_hash(inputs[0])));
bool stop_requested = false;
tools::signal_handler::install([&stop_requested](int type) {
stop_requested = true;
});
int dbr = resize_env(cache_dir.c_str());
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to resize LMDB database: " + std::string(mdb_strerror(dbr)));
// open first db
MDB_env *env0;
MDB_txn *txn0;
MDB_dbi dbi0;
MDB_cursor *cur0;
open_db(inputs[0], &env0, &txn0, &cur0, &dbi0);
std::vector<output_data> work_spent;
if (opt_historical_stat)
{
if (!start_blackballed_outputs)
{
MINFO("Spent outputs database is empty. Either you haven't run the analysis mode yet, or there is really no output marked as spent.");
goto skip_secondary_passes;
}
MDB_txn *txn;
int dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
const uint64_t STAT_WINDOW = 10000;
uint64_t outs_total = 0;
uint64_t outs_spent = 0;
std::unordered_map<uint64_t, uint64_t> outs_per_amount;
uint64_t start_idx = 0, n_txes;
uint64_t prev_height = 0;
for_all_transactions(inputs[0], start_idx, n_txes, [&](bool last_tx, uint64_t height, const cryptonote::transaction_prefix &tx)->bool
{
if (height != prev_height)
{
if (height % 100 == 0) std::cout << "\r" << height << ": " << (100.0f * outs_spent / outs_total) << "% ( " << outs_spent << " / " << outs_total << " ) \r" << std::flush;
if (height % STAT_WINDOW == 0)
{
uint64_t window_front = (height / STAT_WINDOW - 1) * STAT_WINDOW;
uint64_t window_back = window_front + STAT_WINDOW - 1;
LOG_PRINT_L0(window_front << "-" << window_back << ": " << (100.0f * outs_spent / outs_total) << "% ( " << outs_spent << " / " << outs_total << " )");
outs_total = outs_spent = 0;
}
}
prev_height = height;
for (const auto &out: tx.vout)
{
++outs_total;
CHECK_AND_ASSERT_THROW_MES(out.target.type() == typeid(txout_to_key), "Out target type is not txout_to_key: height=" + std::to_string(height));
uint64_t out_global_index = outs_per_amount[out.amount]++;
if (is_output_spent(cur, output_data(out.amount, out_global_index)))
++outs_spent;
}
if (last_tx)
{
uint64_t window_front = (height / STAT_WINDOW) * STAT_WINDOW;
uint64_t window_back = height;
LOG_PRINT_L0(window_front << "-" << window_back << ": " << (100.0f * outs_spent / outs_total) << "% ( " << outs_spent << " / " << outs_total << " )");
}
if (stop_requested)
{
MINFO("Stopping scan...");
return false;
}
return true;
});
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
goto skip_secondary_passes;
}
if (!extra_spent_outputs.empty())
{
MINFO("Adding " << extra_spent_outputs.size() << " extra spent outputs");
MDB_txn *txn;
int dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
std::vector<std::pair<uint64_t, uint64_t>> blackballs;
for (const std::pair<uint64_t, uint64_t> &output: extra_spent_outputs)
{
if (!is_output_spent(cur, output_data(output.first, output.second)))
{
blackballs.push_back(output);
if (add_spent_output(cur, output_data(output.first, output.second)))
inc_stat(txn, output.first ? "pre-rct-extra" : "rct-ring-extra");
}
}
if (!blackballs.empty())
{
ringdb.blackball(blackballs);
blackballs.clear();
}
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
}
for (size_t n = 0; n < inputs.size(); ++n)
{
const std::string canonical = boost::filesystem::canonical(inputs[n]).string();
uint64_t start_idx = get_processed_txidx(canonical);
if (n > 0 && start_idx == 0)
{
start_idx = find_first_diverging_transaction(inputs[0], inputs[n]);
LOG_PRINT_L0("First diverging transaction at " << start_idx);
}
LOG_PRINT_L0("Reading blockchain from " << inputs[n] << " from " << start_idx);
MDB_txn *txn;
int dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
size_t records = 0;
const std::string filename = inputs[n];
std::vector<std::pair<uint64_t, uint64_t>> blackballs;
uint64_t n_txes;
for_all_transactions(filename, start_idx, n_txes, [&](const cryptonote::transaction_prefix &tx)->bool
{
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
const bool miner_tx = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
for (const auto &in: tx.vin)
{
if (in.type() != typeid(txin_to_key))
continue;
const auto &txin = boost::get<txin_to_key>(in);
if (opt_rct_only && txin.amount != 0)
continue;
const std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
if (n == 0)
for (uint64_t out: absolute)
add_key_image(txn, output_data(txin.amount, out), txin.k_image);
std::vector<uint64_t> relative_ring;
std::vector<uint64_t> new_ring = canonicalize(txin.key_offsets);
const uint32_t ring_size = txin.key_offsets.size();
const uint64_t instances = inc_ring_instances(txn, txin.amount, new_ring);
uint64_t pa_total = 0, pa_spent = 0;
if (!opt_rct_only)
get_per_amount_outputs(txn, txin.amount, pa_total, pa_spent);
if (n == 0 && ring_size == 1)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(txin.amount, absolute[0]);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in a 1-ring");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(txin.amount, absolute[0])))
inc_stat(txn, txin.amount ? "pre-rct-ring-size-1" : "rct-ring-size-1");
}
else if (n == 0 && instances == new_ring.size())
{
for (size_t o = 0; o < new_ring.size(); ++o)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(txin.amount, absolute[o]);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in " << new_ring.size() << " identical " << new_ring.size() << "-rings");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(txin.amount, absolute[o])))
inc_stat(txn, txin.amount ? "pre-rct-duplicate-rings" : "rct-duplicate-rings");
}
}
else if (n == 0 && !opt_rct_only && pa_spent + 1 == pa_total)
{
for (size_t o = 0; o < pa_total; ++o)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(txin.amount, o);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to as many outputs of that amount being spent as exist so far");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(txin.amount, o)))
inc_stat(txn, txin.amount ? "pre-rct-full-count" : "rct-full-count");
}
}
else if (n == 0 && opt_check_subsets && get_ring_subset_instances(txn, txin.amount, new_ring) >= new_ring.size())
{
for (size_t o = 0; o < new_ring.size(); ++o)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(txin.amount, absolute[o]);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in " << new_ring.size() << " subsets of " << new_ring.size() << "-rings");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(txin.amount, absolute[o])))
inc_stat(txn, txin.amount ? "pre-rct-subset-rings" : "rct-subset-rings");
}
}
else if (n > 0 && get_relative_ring(txn, txin.k_image, relative_ring))
{
MDEBUG("Key image " << txin.k_image << " already seen: rings " <<
boost::join(relative_ring | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " ") <<
", " << boost::join(txin.key_offsets | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " "));
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
if (relative_ring != txin.key_offsets)
{
MDEBUG("Rings are different");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
const std::vector<uint64_t> r0 = cryptonote::relative_output_offsets_to_absolute(relative_ring);
const std::vector<uint64_t> r1 = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
std::vector<uint64_t> common;
for (uint64_t out: r0)
{
if (std::find(r1.begin(), r1.end(), out) != r1.end())
common.push_back(out);
}
if (common.empty())
{
MERROR("Rings for the same key image are disjoint");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
else if (common.size() == 1)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(txin.amount, common[0]);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in rings with a single common element");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(txin.amount, common[0])))
inc_stat(txn, txin.amount ? "pre-rct-key-image-attack" : "rct-key-image-attack");
}
else
{
MDEBUG("The intersection has more than one element, it's still ok");
std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush;
for (const auto &out: r0)
if (std::find(common.begin(), common.end(), out) != common.end())
new_ring.push_back(out);
new_ring = cryptonote::absolute_output_offsets_to_relative(new_ring);
}
}
}
if (n == 0)
{
set_relative_ring(txn, txin.k_image, new_ring);
if (!opt_rct_only)
inc_per_amount_outputs(txn, txin.amount, 0, 1);
}
}
set_processed_txidx(txn, canonical, start_idx+1);
if (!opt_rct_only)
{
for (const auto &out: tx.vout)
{
uint64_t amount = out.amount;
if (miner_tx && tx.version >= 2)
amount = 0;
if (opt_rct_only && amount != 0)
continue;
if (out.target.type() != typeid(txout_to_key))
continue;
inc_per_amount_outputs(txn, amount, 1, 0);
}
}
++records;
if (records >= records_per_sync)
{
if (!blackballs.empty())
{
ringdb.blackball(blackballs);
blackballs.clear();
}
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
int dbr = resize_env(cache_dir.c_str());
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to resize LMDB database: " + std::string(mdb_strerror(dbr)));
dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
records = 0;
}
if (stop_requested)
{
MINFO("Stopping scan...");
return false;
}
return true;
});
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
LOG_PRINT_L0("blockchain from " << inputs[n] << " processed till tx idx " << start_idx);
if (stop_requested)
break;
}
if (stop_requested)
goto skip_secondary_passes;
if (opt_force_chain_reaction_pass || get_num_spent_outputs() > start_blackballed_outputs)
{
MDB_txn *txn;
dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
work_spent = get_spent_outputs(txn);
mdb_txn_abort(txn);
}
while (!work_spent.empty())
{
LOG_PRINT_L0("Secondary pass on " << work_spent.size() << " spent outputs");
int dbr = resize_env(cache_dir.c_str());
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to resize LMDB database: " + std::string(mdb_strerror(dbr)));
MDB_txn *txn;
dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
std::vector<std::pair<uint64_t, uint64_t>> blackballs;
std::vector<output_data> scan_spent = std::move(work_spent);
work_spent.clear();
for (const output_data &od: scan_spent)
{
std::vector<crypto::key_image> key_images = get_key_images(txn, od);
for (const crypto::key_image &ki: key_images)
{
std::vector<uint64_t> relative_ring;
CHECK_AND_ASSERT_THROW_MES(get_relative_ring(txn, ki, relative_ring), "Relative ring not found");
std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(relative_ring);
size_t known = 0;
uint64_t last_unknown = 0;
for (uint64_t out: absolute)
{
output_data new_od(od.amount, out);
if (is_output_spent(cur, new_od))
++known;
else
last_unknown = out;
}
if (known == absolute.size() - 1)
{
const std::pair<uint64_t, uint64_t> output = std::make_pair(od.amount, last_unknown);
if (opt_verbose)
{
MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in a " <<
absolute.size() << "-ring where all other outputs are known to be spent");
}
blackballs.push_back(output);
if (add_spent_output(cur, output_data(od.amount, last_unknown)))
inc_stat(txn, od.amount ? "pre-rct-chain-reaction" : "rct-chain-reaction");
work_spent.push_back(output_data(od.amount, last_unknown));
}
}
if (stop_requested)
{
MINFO("Stopping secondary passes. Secondary passes are not incremental, they will re-run fully.");
return 0;
}
}
if (!blackballs.empty())
{
ringdb.blackball(blackballs);
blackballs.clear();
}
mdb_cursor_close(cur);
dbr = mdb_txn_commit(txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr)));
}
skip_secondary_passes:
uint64_t diff = get_num_spent_outputs() - start_blackballed_outputs;
LOG_PRINT_L0(std::to_string(diff) << " new outputs marked as spent, " << get_num_spent_outputs() << " total outputs marked as spent");
MDB_txn *txn;
dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
uint64_t pre_rct = 0, rct = 0;
get_num_outputs(txn0, cur0, dbi0, pre_rct, rct);
MINFO("Total pre-rct outputs: " << pre_rct);
MINFO("Total rct outputs: " << rct);
static const struct { const char *key; uint64_t base; } stat_keys[] = {
{ "pre-rct-ring-size-1", pre_rct }, { "rct-ring-size-1", rct },
{ "pre-rct-duplicate-rings", pre_rct }, { "rct-duplicate-rings", rct },
{ "pre-rct-subset-rings", pre_rct }, { "rct-subset-rings", rct },
{ "pre-rct-full-count", pre_rct }, { "rct-full-count", rct },
{ "pre-rct-key-image-attack", pre_rct }, { "rct-key-image-attack", rct },
{ "pre-rct-extra", pre_rct }, { "rct-ring-extra", rct },
{ "pre-rct-chain-reaction", pre_rct }, { "rct-chain-reaction", rct },
};
for (const auto &key: stat_keys)
{
uint64_t data;
if (!get_stat(txn, key.key, data))
data = 0;
float percent = key.base ? 100.0f * data / key.base : 0.0f;
MINFO(key.key << ": " << data << " (" << percent << "%)");
}
mdb_txn_abort(txn);
if (!opt_export.empty())
{
MDB_txn *txn;
int dbr = mdb_txn_begin(env, NULL, 0, &txn);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr)));
MDB_cursor *cur;
dbr = mdb_cursor_open(txn, dbi_spent, &cur);
CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open LMDB cursor: " + std::string(mdb_strerror(dbr)));
export_spent_outputs(cur, opt_export);
mdb_cursor_close(cur);
mdb_txn_abort(txn);
}
LOG_PRINT_L0("Blockchain spent output data exported OK");
close_db(env0, txn0, cur0, dbi0);
close();
return 0;
CATCH_ENTRY("Error", 1);
}
|
#include "LockstepDemo.h"
#include "Cubes.h"
#ifdef CLIENT
#include "Global.h"
#include "Render.h"
#include "Console.h"
#include "core/Queue.h"
#include "protocol/Stream.h"
#include "protocol/SlidingWindow.h"
#include "protocol/PacketFactory.h"
#include "network/Simulator.h"
static const int MaxInputs = 256;
static const int PlayoutDelayBufferSize = 1024;
static const int LeftPort = 1000;
static const int RightPort = 1001;
enum LockstepModes
{
LOCKSTEP_MODE_DETERMINISTIC,
LOCKSTEP_MODE_NON_DETERMINISTIC,
LOCKSTEP_MODE_TCP_100MS_1PC,
LOCKSTEP_MODE_TCP_200MS_2PC,
LOCKSTEP_MODE_TCP_250MS_5PC,
LOCKSTEP_MODE_UDP_250MS_25PC,
LOCKSTEP_MODE_UDP_250MS_50PC,
LOCKSTEP_NUM_MODES
};
static const char * lockstep_mode_descriptions[] =
{
"Deterministic Mode",
"Non-Determistic Mode",
"TCP at 100ms latency and 1%% packet loss (100ms playout delay buffer)",
"TCP at 200ms latency and 2%% packet loss (100ms playout delay buffer)",
"TCP at 250ms latency and 5%% packet loss (100ms playout delay buffer)",
"UDP at 2 seconds latency and 25%% packet loss (100ms playout delay buffer)",
"UDP at 2 seconds latency and 50%% packet loss (250ms playout delay buffer)",
};
struct LockstepModeData
{
bool tcp = true;
bool deterministic = true;
float playout_delay = 0.1f;
float latency = 0.0f;
float packet_loss = 0.0f;
float jitter = 0.0f;
};
static LockstepModeData lockstep_mode_data[LOCKSTEP_NUM_MODES];
static void InitLockstepModes()
{
lockstep_mode_data[LOCKSTEP_MODE_NON_DETERMINISTIC].tcp = true;
lockstep_mode_data[LOCKSTEP_MODE_NON_DETERMINISTIC].deterministic = false;
lockstep_mode_data[LOCKSTEP_MODE_NON_DETERMINISTIC].latency = 0.0f;
lockstep_mode_data[LOCKSTEP_MODE_DETERMINISTIC].tcp = true;
lockstep_mode_data[LOCKSTEP_MODE_DETERMINISTIC].playout_delay = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_DETERMINISTIC].latency = 0.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_100MS_1PC].playout_delay = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_100MS_1PC].latency = 0.05f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_100MS_1PC].packet_loss = 1.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_100MS_1PC].jitter = 1.0f / 60.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_200MS_2PC].playout_delay = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_200MS_2PC].latency = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_200MS_2PC].packet_loss = 2.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_200MS_2PC].jitter = 1.0f / 60.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_250MS_5PC].playout_delay = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_250MS_5PC].latency = 0.125f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_250MS_5PC].packet_loss = 5.0f;
lockstep_mode_data[LOCKSTEP_MODE_TCP_250MS_5PC].jitter = 1.0f / 60.0f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_25PC].tcp = false;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_25PC].playout_delay = 0.1f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_25PC].latency = 0.125f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_25PC].packet_loss = 25.0f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_25PC].jitter = 1.0f / 60.0f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_50PC].tcp = false;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_50PC].playout_delay = 0.25f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_50PC].latency = 0.125f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_50PC].packet_loss = 50.0f;
lockstep_mode_data[LOCKSTEP_MODE_UDP_250MS_50PC].jitter = 1.0f / 60.0f;
}
typedef protocol::SlidingWindow<game::Input> LockstepInputSlidingWindow;
enum LockstepPackets
{
LOCKSTEP_PACKET_INPUT,
LOCKSTEP_PACKET_ACK,
LOCKSTEP_NUM_PACKETS
};
struct LockstepInputPacket : public protocol::Packet
{
uint16_t sequence;
int num_inputs;
game::Input inputs[MaxInputs];
LockstepInputPacket() : Packet( LOCKSTEP_PACKET_INPUT )
{
sequence = 0;
num_inputs = 0;
}
PROTOCOL_SERIALIZE_OBJECT( stream )
{
serialize_uint16( stream, sequence );
serialize_int( stream, num_inputs, 0, MaxInputs );
if ( num_inputs >= 1 )
{
serialize_bool( stream, inputs[0].left );
serialize_bool( stream, inputs[0].right );
serialize_bool( stream, inputs[0].up );
serialize_bool( stream, inputs[0].down );
serialize_bool( stream, inputs[0].push );
serialize_bool( stream, inputs[0].pull );
for ( int i = 1; i < num_inputs; ++i )
{
bool input_changed = Stream::IsWriting ? inputs[i] != inputs[i-1] : false;
serialize_bool( stream, input_changed );
if ( input_changed )
{
serialize_bool( stream, inputs[i].left );
serialize_bool( stream, inputs[i].right );
serialize_bool( stream, inputs[i].up );
serialize_bool( stream, inputs[i].down );
serialize_bool( stream, inputs[i].push );
serialize_bool( stream, inputs[i].pull );
}
else if ( Stream::IsReading )
{
inputs[i] = inputs[i-1];
}
}
}
}
};
struct LockstepAckPacket : public protocol::Packet
{
uint16_t ack;
LockstepAckPacket() : Packet( LOCKSTEP_PACKET_ACK )
{
ack = 0;
}
PROTOCOL_SERIALIZE_OBJECT( stream )
{
serialize_uint16( stream, ack );
}
};
class LockstepPacketFactory : public protocol::PacketFactory
{
core::Allocator * m_allocator;
public:
LockstepPacketFactory( core::Allocator & allocator )
: PacketFactory( allocator, LOCKSTEP_NUM_PACKETS )
{
m_allocator = &allocator;
}
protected:
protocol::Packet * CreateInternal( int type )
{
switch ( type )
{
case LOCKSTEP_PACKET_INPUT: return CORE_NEW( *m_allocator, LockstepInputPacket );
case LOCKSTEP_PACKET_ACK: return CORE_NEW( *m_allocator, LockstepAckPacket );
default:
return nullptr;
}
}
};
struct LockstepPlayoutDelayBuffer
{
LockstepPlayoutDelayBuffer( core::Allocator & allocator, const LockstepModeData & mode_data )
: input_queue( allocator )
{
stopped = true;
start_time = 0.0;
most_recent_input = 0;
frame = 0;
playout_delay = mode_data.playout_delay;
core::queue::reserve( input_queue, PlayoutDelayBufferSize );
}
void AddInputs( double time, uint16_t sequence, int num_inputs, game::Input * inputs )
{
CORE_ASSERT( num_inputs > 0 );
if ( stopped )
{
start_time = time;
stopped = false;
}
const uint16_t first_input_sequence = sequence - num_inputs;
for ( int i = 0; i < num_inputs; ++i )
{
const uint16_t sequence = first_input_sequence + i;
if ( sequence == most_recent_input )
{
most_recent_input = sequence + 1;
core::queue::push_back( input_queue, inputs[i] );
}
}
}
void GetFrames( double time, int & num_frames, game::Input * frame_input )
{
num_frames = 0;
if ( stopped )
return;
for ( int i = 0; i < MaxSimFrames; ++i )
{
if ( time < ( start_time + ( frame + 0.5 ) * ( 1.0f / 60.0f ) + playout_delay ) )
break;
if ( !core::queue::size( input_queue ) )
break;
frame_input[i] = input_queue[0];
core::queue::pop_front( input_queue );
num_frames++;
frame++;
}
}
void Reset()
{
stopped = true;
start_time = 0.0;
most_recent_input = 0;
frame = 0;
core::queue::clear( input_queue );
}
bool stopped;
double start_time;
uint16_t most_recent_input;
uint64_t frame;
float playout_delay;
core::Queue<game::Input> input_queue;
};
struct LockstepInternal
{
LockstepInternal( core::Allocator & allocator, const LockstepModeData & mode_data )
: packet_factory( allocator ), input_sliding_window( allocator, MaxInputs ), playout_delay_buffer( allocator, mode_data )
{
this->allocator = &allocator;
network::SimulatorConfig networkSimulatorConfig;
networkSimulatorConfig.packetFactory = &packet_factory;
network_simulator = CORE_NEW( allocator, network::Simulator, networkSimulatorConfig );
Reset( mode_data );
}
~LockstepInternal()
{
CORE_ASSERT( network_simulator );
typedef network::Simulator NetworkSimulator;
CORE_DELETE( *allocator, NetworkSimulator, network_simulator );
network_simulator = nullptr;
}
void Reset( const LockstepModeData & mode_data )
{
input_sliding_window.Reset();
playout_delay_buffer.Reset();
network_simulator->Reset();
network_simulator->ClearStates();
network_simulator->AddState( { mode_data.latency, mode_data.jitter, mode_data.packet_loss } );
network_simulator->SetTCPMode( mode_data.tcp );
}
core::Allocator * allocator;
LockstepPacketFactory packet_factory;
LockstepInputSlidingWindow input_sliding_window;
LockstepPlayoutDelayBuffer playout_delay_buffer;
network::Simulator * network_simulator;
};
LockstepDemo::LockstepDemo( core::Allocator & allocator )
{
InitLockstepModes();
m_allocator = &allocator;
m_internal = nullptr;
m_settings = CORE_NEW( *m_allocator, CubesSettings );
m_lockstep = CORE_NEW( *m_allocator, LockstepInternal, *m_allocator, lockstep_mode_data[GetMode()] );
}
LockstepDemo::~LockstepDemo()
{
Shutdown();
CORE_DELETE( *m_allocator, LockstepInternal, m_lockstep );
CORE_DELETE( *m_allocator, CubesSettings, m_settings );
m_settings = nullptr;
m_lockstep = nullptr;
m_allocator = nullptr;
}
bool LockstepDemo::Initialize()
{
if ( m_internal )
Shutdown();
m_internal = CORE_NEW( *m_allocator, CubesInternal );
CubesConfig config;
config.num_simulations = 2;
config.num_views = 2;
config.soften_simulation = true;
m_internal->Initialize( *m_allocator, config, m_settings );
m_settings->deterministic = lockstep_mode_data[GetMode()].deterministic;
return true;
}
void LockstepDemo::Shutdown()
{
CORE_ASSERT( m_allocator );
CORE_ASSERT( m_lockstep );
m_lockstep->Reset( lockstep_mode_data[GetMode()] );
if ( m_internal )
{
m_internal->Free( *m_allocator );
CORE_DELETE( *m_allocator, CubesInternal, m_internal );
m_internal = nullptr;
}
}
void LockstepDemo::Update()
{
CubesUpdateConfig update_config;
auto local_input = m_internal->GetLocalInput();
// setup left simulation to update one frame with local input
update_config.sim[0].num_frames = 1;
update_config.sim[0].frame_input[0] = local_input;
// insert local input for this frame in the input sliding window
auto & inputs = m_lockstep->input_sliding_window;
CORE_ASSERT( !inputs.IsFull() );
inputs.Insert( local_input );
// send an input packet to the right simulation (all inputs since last ack)
auto input_packet = (LockstepInputPacket*) m_lockstep->packet_factory.Create( LOCKSTEP_PACKET_INPUT );
input_packet->sequence = inputs.GetSequence();
inputs.GetArray( input_packet->inputs, input_packet->num_inputs );
m_lockstep->network_simulator->SendPacket( network::Address( "::1", RightPort ), input_packet );
// if we are in TCP mode, ack right away because the simulator ensures reliable-ordered delivery
if ( m_lockstep->network_simulator->GetTCPMode() )
inputs.Ack( inputs.GetSequence() );
// update the network simulator
m_lockstep->network_simulator->Update( global.timeBase );
// receive packets from the simulator (with latency, packet loss and jitter applied...)
bool received_input_this_frame = false;
uint16_t ack_sequence = 0;
while ( true )
{
auto packet = m_lockstep->network_simulator->ReceivePacket();
if ( !packet )
break;
auto port = packet->GetAddress().GetPort();
auto type = packet->GetType();
if ( type == LOCKSTEP_PACKET_INPUT && port == RightPort )
{
// input packet for right simulation
auto input_packet = (LockstepInputPacket*) packet;
if ( !m_lockstep->network_simulator->GetTCPMode() )
{
if ( !received_input_this_frame )
{
received_input_this_frame = true;
ack_sequence = input_packet->sequence - 1;
}
else
{
if ( core::sequence_greater_than( input_packet->sequence - 1, ack_sequence ) )
ack_sequence = input_packet->sequence - 1;
}
}
m_lockstep->playout_delay_buffer.AddInputs( global.timeBase.time, input_packet->sequence, input_packet->num_inputs, input_packet->inputs );
}
else if ( type == LOCKSTEP_PACKET_ACK && port == LeftPort && !m_lockstep->network_simulator->GetTCPMode() )
{
// ack packet for left simulation
auto ack_packet = (LockstepAckPacket*) packet;
inputs.Ack( ack_packet->ack );
}
m_lockstep->packet_factory.Destroy( packet );
}
// if any input packets were received this frame, send an ack packet back to the left simulation
if ( received_input_this_frame )
{
auto ack_packet = (LockstepAckPacket*) m_lockstep->packet_factory.Create( LOCKSTEP_PACKET_ACK );
ack_packet->ack = ack_sequence;
m_lockstep->network_simulator->SendPacket( network::Address( "::1", LeftPort ), ack_packet );
}
// if we have frames available from playout delay buffer set them up to simulate
m_lockstep->playout_delay_buffer.GetFrames( global.timeBase.time, update_config.sim[1].num_frames, update_config.sim[1].frame_input );
// run the simulation(s)
m_internal->Update( update_config );
}
bool LockstepDemo::Clear()
{
return m_internal->Clear();
}
void LockstepDemo::Render()
{
CubesRenderConfig render_config;
render_config.render_mode = CUBES_RENDER_SPLITSCREEN;
m_internal->Render( render_config );
}
bool LockstepDemo::KeyEvent( int key, int scancode, int action, int mods )
{
return m_internal->KeyEvent( key, scancode, action, mods );
}
bool LockstepDemo::CharEvent( unsigned int /*code*/ )
{
return false;
}
int LockstepDemo::GetNumModes() const
{
return LOCKSTEP_NUM_MODES;
}
const char * LockstepDemo::GetModeDescription( int mode ) const
{
return lockstep_mode_descriptions[mode];
}
#endif // #ifdef CLIENT
|
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <deque>
#include <string>
#include <map>
#include <cstring>
#include "include/dart_api.h"
#include "include/dart_native_api.h"
#include "leveldb/db.h"
#include "leveldb/filter_policy.h"
const int BLOOM_BITS_PER_KEY = 10;
Dart_NativeFunction ResolveName(Dart_Handle name,
int argc,
bool* auto_setup_scope);
DART_EXPORT Dart_Handle leveldb_Init(Dart_Handle parent_library) {
if (Dart_IsError(parent_library)) {
return parent_library;
}
Dart_Handle result_code =
Dart_SetNativeResolver(parent_library, ResolveName, NULL);
if (Dart_IsError(result_code)) {
return result_code;
}
return Dart_Null();
}
int64_t statusToError(leveldb::Status status) {
if (status.IsNotFound()) {
return -5;
}
if (status.IsIOError()) {
return -2;
}
if (status.IsCorruption()) {
return -3;
}
// LevelDB does not provide Status::IsInvalidArgument so we just assume all other errors are invalid argument.
if (!status.ok()) {
return -4;
}
return 0;
}
struct DB {
leveldb::DB *db;
int64_t refcount;
bool is_shared;
char* path;
int64_t block_size;
bool create_if_missing;
bool error_if_exists;
pthread_t thread;
std::deque<Dart_Port> notify_list;
int64_t open_status;
pthread_mutex_t mutex;
};
struct cmp_str {
bool operator()(char const *a, char const *b) const {
return std::strcmp(a, b) < 0;
}
};
typedef std::map<char const*, DB*, cmp_str> DBMap;
pthread_mutex_t shared_mutex = PTHREAD_MUTEX_INITIALIZER;
DBMap sharedDBs;
void* runOpen(void* ptr) {
// This function may not take the shared mutex because we take it when joining to this thread.
DB *native_db = (DB*) ptr;
leveldb::Options options;
options.create_if_missing = native_db->create_if_missing;
options.error_if_exists = native_db->error_if_exists;
options.block_size = native_db->block_size;
options.filter_policy = leveldb::NewBloomFilterPolicy(BLOOM_BITS_PER_KEY);
leveldb::Status status = leveldb::DB::Open(options, native_db->path, &native_db->db);
// Notify all ports the new status.
pthread_mutex_lock(&native_db->mutex);
native_db->open_status = statusToError(status);
while (!native_db->notify_list.empty()) {
Dart_Port port = native_db->notify_list.front();
native_db->notify_list.pop_front();
Dart_PostInteger(port, native_db->open_status);
}
pthread_mutex_unlock(&native_db->mutex);
return NULL;
}
/// Open a db and take a reference to it.
/// open_port_id will be notified when the db is ready or an error occurs.
DB* referenceDB(const char *path, bool is_shared, Dart_Port open_port_id, bool create_if_missing, bool error_if_exists, int64_t block_size) {
DB* db = NULL;
bool is_new = false;
pthread_mutex_lock(&shared_mutex);
// Look for the db by path
if (is_shared) {
DBMap::iterator it = sharedDBs.find(path);
if (it != sharedDBs.end()) {
db = it->second;
assert(db->refcount > 0);
}
}
// Create db if not found
if (db == NULL) {
is_new = true;
db = new DB();
db->is_shared = is_shared;
db->path = strdup(path);
db->refcount = 0;
db->open_status = 1;
db->create_if_missing = create_if_missing;
db->error_if_exists = error_if_exists;
db->block_size = block_size;
pthread_mutex_init(&db->mutex, NULL);
}
// If the db is shared add it to the map
if (is_shared) {
sharedDBs[db->path] = db;
}
// If the db is open then just post a reply now. Otherwise add the port to the notify list.
pthread_mutex_lock(&db->mutex);
db->refcount += 1;
if (db->open_status <= 0) {
// The open thread has finished.
Dart_PostInteger(open_port_id, db->open_status);
} else {
db->notify_list.push_back(open_port_id);
}
pthread_mutex_unlock(&db->mutex);
pthread_mutex_unlock(&shared_mutex);
// Spawn a thread to open the DB
if (is_new) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc = pthread_create(&db->thread, &attr, runOpen, (void*)db);
assert(rc == 0);
pthread_attr_destroy(&attr);
}
return db;
}
/// Drop a reference to a db.
/// May result in the db being closed.
void unreferenceDB(DB* db) {
bool is_finished;
// Take the shared mutex and the db mutex. This is so that if the refcount drops to 0 we can safely remove it
// from the shared map.
pthread_mutex_lock(&shared_mutex);
pthread_mutex_lock(&db->mutex);
db->refcount -= 1;
is_finished = db->refcount == 0;
// If the db is shared then remove it from the map.
if (is_finished && db->is_shared) {
sharedDBs.erase(db->path);
}
pthread_mutex_unlock(&db->mutex);
if (is_finished) {
// It is possible that unreferenceDB is called before db->thread is initialized if a 2nd thread quickly takes a reference to a
// shared db and then drops it. However the initializing thread still has a reference so it is safe to call pthread_join()
// if the refcount was 0
pthread_join(db->thread, NULL);
// The actual closing of the db and its file descriptors must be run whilst
// the shared lock is taken so that any threads attempting to open the same file will
// succeed.
delete db->path;
delete db->db;
delete db;
}
pthread_mutex_unlock(&shared_mutex);
}
struct NativeIterator;
struct NativeDB {
// Reference to the DB. NULL if closed.
DB* db;
std::list<NativeIterator*> *iterators;
};
struct NativeIterator {
NativeDB *native_db;
leveldb::Iterator *iterator;
bool is_finalized;
// Iterator params
int64_t limit;
bool is_gt_closed;
bool is_lt_closed;
uint8_t* gt;
int64_t gt_len;
uint8_t* lt;
int64_t lt_len;
bool is_fill_cache;
// Iterator state
int64_t count;
};
/**
* Finalize the iterator.
*/
static void iteratorFinalize(NativeIterator *it_ref) {
if (it_ref->is_finalized) {
return;
}
it_ref->is_finalized = true;
// This iterator will only be in the db list if the level db iterator has been created (i.e. the stream has
// started).
if (it_ref->iterator != NULL) {
// Remove the iterator from the db list
it_ref->native_db->iterators->remove(it_ref);
delete it_ref->iterator;
it_ref->iterator = NULL;
}
delete it_ref->gt;
delete it_ref->lt;
}
/**
* Finalizer called when the dart LevelDB instance is not reachable.
* */
static void NativeDBFinalizer(void* isolate_callback_data, Dart_WeakPersistentHandle handle, void* peer) {
NativeDB* native_db = (NativeDB*) peer;
// If the db reference is not NULL then the user did not call close on the db before it went out of scope.
// We unreference it now.
if (native_db->db != NULL) {
unreferenceDB(native_db->db);
native_db->db = NULL;
}
// Finalize every iterator. The iterators remove themselves from the array.
while (!native_db->iterators->empty()) {
iteratorFinalize(native_db->iterators->front());
}
delete native_db->iterators;
delete native_db;
}
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) {
Dart_PropagateError(handle);
}
return handle;
}
/**
* Finalizer called when the dart instance is not reachable.
* */
static void NativeIteratorFinalizer(void* isolate_callback_data, Dart_WeakPersistentHandle handle, void* peer) {
NativeIterator* it_ref = (NativeIterator*) peer;
iteratorFinalize(it_ref);
delete it_ref;
}
void dbOpen(Dart_NativeArguments arguments) { // (bool shared, SendPort port, String path, int blockSize, bool create_if_missing, bool error_if_exists)
Dart_EnterScope();
NativeDB* native_db = new NativeDB();
const char* path;
Dart_Handle arg2 = Dart_GetNativeArgument(arguments, 3);
Dart_StringToCString(arg2, &path);
Dart_Port port_id;
Dart_Handle arg1 = Dart_GetNativeArgument(arguments, 2);
Dart_SendPortGetId(arg1, &port_id);
bool is_shared;
bool create_if_missing;
bool error_if_exists;
int64_t block_size;
Dart_GetNativeBooleanArgument(arguments, 1, &is_shared);
Dart_GetNativeIntegerArgument(arguments, 4, &block_size);
Dart_GetNativeBooleanArgument(arguments, 5, &create_if_missing);
Dart_GetNativeBooleanArgument(arguments, 6, &error_if_exists);
native_db->db = referenceDB(path, is_shared, port_id, create_if_missing, error_if_exists, 1024);
native_db->iterators = new std::list<NativeIterator*>();
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_SetNativeInstanceField(arg0, 0, (intptr_t) native_db);
Dart_NewWeakPersistentHandle(arg0, (void*) native_db, sizeof(NativeDB) /* external_allocation_size */, NativeDBFinalizer);
Dart_SetReturnValue(arguments, Dart_Null());
Dart_ExitScope();
}
// SYNC API
// Throw a LevelClosedError. This function does not return.
void throwClosedException() {
Dart_Handle klass = Dart_GetType(Dart_LookupLibrary(Dart_NewStringFromCString("package:leveldb/leveldb.dart")), Dart_NewStringFromCString("LevelClosedError"), 0, NULL);
Dart_Handle exception = Dart_New(klass, Dart_NewStringFromCString("_internal"), 0, NULL);
Dart_ThrowException(exception);
}
// If status is not ok then throw an error. This function does not return.
void maybeThrowStatus(leveldb::Status status) {
if (status.ok()) {
return;
}
Dart_Handle library = Dart_LookupLibrary(Dart_NewStringFromCString("package:leveldb/leveldb.dart"));
Dart_Handle klass;
if (status.IsCorruption()) {
klass = Dart_GetType(library, Dart_NewStringFromCString("LevelCorruptionError"), 0, NULL);
} else {
klass = Dart_GetType(library, Dart_NewStringFromCString("LevelIOError"), 0, NULL);
}
Dart_Handle exception = Dart_New(klass, Dart_NewStringFromCString("_internal"), 0, NULL);
Dart_ThrowException(exception);
}
void syncNew(Dart_NativeArguments arguments) { // (this, db, limit, fillCache, gt, is_gt_closed, lt, is_lt_closed)
Dart_EnterScope();
NativeDB *native_db;
Dart_Handle arg1 = Dart_GetNativeArgument(arguments, 1);
Dart_GetNativeInstanceField(arg1, 0, (intptr_t*) &native_db);
if (native_db->db == NULL) {
throwClosedException();
assert(false); // Not reached
}
NativeIterator* it_ref = new NativeIterator();
it_ref->native_db = native_db;
it_ref->is_finalized = false;
it_ref->iterator = NULL;
it_ref->count = 0;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_SetNativeInstanceField(arg0, 0, (intptr_t) it_ref);
Dart_GetNativeIntegerArgument(arguments, 2, &it_ref->limit);
Dart_GetNativeBooleanArgument(arguments, 3, &it_ref->is_fill_cache);
Dart_Handle arg5 = Dart_GetNativeArgument(arguments, 4);
if (Dart_IsNull(arg5)) {
it_ref->gt = NULL;
it_ref->gt_len = 0;
} else {
Dart_TypedData_Type typed_data_type = Dart_GetTypeOfTypedData(arg5);
assert(typed_data_type == Dart_TypedData_kUint8);
char *data;
intptr_t len;
Dart_TypedDataAcquireData(arg5, &typed_data_type, (void**)&data, &len);
it_ref->gt_len = len;
it_ref->gt = (uint8_t*) malloc(len);
memcpy(it_ref->gt, data, len);
Dart_TypedDataReleaseData(arg5);
}
Dart_Handle arg6 = Dart_GetNativeArgument(arguments, 6);
if (Dart_IsNull(arg6)) {
it_ref->lt = NULL;
it_ref->lt_len = 0;
} else {
Dart_TypedData_Type typed_data_type = Dart_GetTypeOfTypedData(arg6);
assert(typed_data_type != Dart_TypedData_kInvalid);
char *data;
intptr_t len;
Dart_TypedDataAcquireData(arg6, &typed_data_type, (void**)&data, &len);
it_ref->lt_len = len;
it_ref->lt = (uint8_t*) malloc(len);
memcpy(it_ref->lt, data, len);
Dart_TypedDataReleaseData(arg6);
}
Dart_GetNativeBooleanArgument(arguments, 5, &it_ref->is_gt_closed);
Dart_GetNativeBooleanArgument(arguments, 7, &it_ref->is_lt_closed);
// We just pass the directly allocated size of the iterator here. The iterator holds a lot of other data in
// memory when it mmaps the files but I'm not sure how to account for it.
// Because the GC is not seeing all of the allocated memory it is important to manually call finalize() on the
// iterator when we are done with it (for example when the iterator reaches the end of its range).
Dart_NewWeakPersistentHandle(arg0, (void*) it_ref, /* external_allocation_size */ sizeof(NativeIterator), NativeIteratorFinalizer);
Dart_SetReturnValue(arguments, Dart_Null());
Dart_ExitScope();
}
// http://stackoverflow.com/questions/2022179/c-quick-calculation-of-next-multiple-of-4
uint32_t increaseToMultipleOf4(uint32_t v) {
return (v + 3) & ~0x03;
}
void syncNext(Dart_NativeArguments arguments) { // (this)
Dart_EnterScope();
NativeIterator *native_iterator;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_GetNativeInstanceField(arg0, 0, (intptr_t*) &native_iterator);
NativeDB *native_db = native_iterator->native_db;
leveldb::Iterator* it = native_iterator->iterator;
if (native_db->db == NULL) {
throwClosedException();
assert(false); // Not reached
}
// If it is NULL we need to create the iterator and perform the initial seek.
if (!native_iterator->is_finalized && it == NULL) {
leveldb::ReadOptions options;
options.fill_cache = native_iterator->is_fill_cache;
it = native_db->db->db->NewIterator(options);
native_iterator->iterator = it;
// Add the iterator to the db list. This is so we know to finalize it before finalizing the db.
native_db->iterators->push_back(native_iterator);
if (native_iterator->gt_len > 0) {
leveldb::Slice start_slice = leveldb::Slice((char*)native_iterator->gt, native_iterator->gt_len);
it->Seek(start_slice);
if (!native_iterator->is_gt_closed && it->Valid()) {
// If we are pointing at start_slice and not inclusive then we need to advance by 1
leveldb::Slice key = it->key();
if (key.compare(start_slice) == 0) {
it->Next();
}
}
} else {
it->SeekToFirst();
}
}
leveldb::Slice end_slice = leveldb::Slice((char*)native_iterator->lt, native_iterator->lt_len);
bool is_valid = false;
bool is_limit_reached = native_iterator->limit >= 0 && native_iterator->count >= native_iterator->limit;
bool is_query_limit_reached = false;
leveldb::Slice key;
leveldb::Slice value;
if (!native_iterator->is_finalized) {
is_valid = it->Valid();
}
if (is_valid) {
key = it->key();
value = it->value();
// Check if key is equal to end slice
if (native_iterator->lt_len > 0) {
int cmp = key.compare(end_slice);
if (cmp == 0 && !native_iterator->is_lt_closed) { // key == end_slice and not closed
is_query_limit_reached = true;
}
if (cmp > 0) { // key > end_slice
is_query_limit_reached = true;
}
}
}
Dart_Handle result = Dart_Null();
if (!is_valid || is_query_limit_reached || is_limit_reached) {
// Iteration is finished. Any subsequent calls to syncNext() will return null so we can finalize the iterator
// here.
iteratorFinalize(native_iterator);
} else {
// Copy key and value into same buffer.
// Align the value array to a multiple of 4 bytes so the offset of the view in dart is a multiple of 4.
uint32_t key_size_mult_4 = increaseToMultipleOf4(key.size());
result = Dart_NewTypedData(Dart_TypedData_kUint8, key_size_mult_4 + value.size() + 4);
uint8_t *data;
intptr_t len;
Dart_TypedData_Type t;
Dart_TypedDataAcquireData(result, &t, (void**)&data, &len);
data[0] = key.size() & 0xFF;
data[1] = (key.size() >> 8) & 0xFF;
data[2] = key_size_mult_4 & 0xFF;
data[3] = (key_size_mult_4 >> 8) & 0xFF;
memcpy(data + 4, key.data(), key.size());
memcpy(data + 4 + key_size_mult_4, value.data(), value.size());
Dart_TypedDataReleaseData(result);
native_iterator->count += 1;
it->Next();
}
Dart_SetReturnValue(arguments, result);
Dart_ExitScope();
}
void syncGet(Dart_NativeArguments arguments) { // (this, key)
Dart_EnterScope();
NativeDB *native_db;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_GetNativeInstanceField(arg0, 0, (intptr_t*) &native_db);
if (native_db->db == NULL) {
throwClosedException();
assert(false); // Not reached
}
Dart_Handle arg1 = Dart_GetNativeArgument(arguments, 1);
Dart_TypedData_Type typed_data_type = Dart_GetTypeOfTypedData(arg1);
assert(typed_data_type == Dart_TypedData_kUint8);
char *data;
intptr_t len;
Dart_TypedDataAcquireData(arg1, &typed_data_type, (void**)&data, &len);
leveldb::Slice key = leveldb::Slice(data, len);
std::string value;
leveldb::Status status = native_db->db->db->Get(leveldb::ReadOptions(), key, &value);
Dart_TypedDataReleaseData(arg1);
Dart_Handle result;
if (status.IsNotFound()) {
result = Dart_Null();
} else if (status.ok()) {
result = Dart_NewTypedData(Dart_TypedData_kUint8, value.size());
Dart_TypedData_Type t;
Dart_TypedDataAcquireData(result, &t, (void**)&data, &len);
memcpy(data, value.data(), value.size());
Dart_TypedDataReleaseData(result);
} else {
maybeThrowStatus(status);
assert(false); // Not reached
}
Dart_SetReturnValue(arguments, result);
Dart_ExitScope();
}
void syncPut(Dart_NativeArguments arguments) { // (this, key, value, sync)
Dart_EnterScope();
NativeDB *native_db;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_GetNativeInstanceField(arg0, 0, (intptr_t*) &native_db);
if (native_db->db == NULL) {
throwClosedException();
assert(false); // Not reached
}
Dart_Handle arg1 = Dart_GetNativeArgument(arguments, 1);
Dart_TypedData_Type typed_data_type1;
Dart_Handle arg2 = Dart_GetNativeArgument(arguments, 2);
Dart_TypedData_Type typed_data_type2;
bool is_sync;
Dart_GetNativeBooleanArgument(arguments, 3, &is_sync);
char *data1, *data2;
intptr_t len1, len2;
Dart_TypedDataAcquireData(arg1, &typed_data_type1, (void**)&data1, &len1);
Dart_TypedDataAcquireData(arg2, &typed_data_type2, (void**)&data2, &len2);
assert(typed_data_type1 == Dart_TypedData_kUint8);
assert(typed_data_type2 == Dart_TypedData_kUint8);
leveldb::Slice key = leveldb::Slice(data1, len1);
leveldb::Slice value = leveldb::Slice(data2, len2);
leveldb::WriteOptions options;
options.sync = is_sync;
leveldb::Status status = native_db->db->db->Put(options, key, value);
Dart_TypedDataReleaseData(arg1);
Dart_TypedDataReleaseData(arg2);
maybeThrowStatus(status);
Dart_SetReturnValue(arguments, Dart_Null());
Dart_ExitScope();
}
void syncDelete(Dart_NativeArguments arguments) { // (this, key)
Dart_EnterScope();
NativeDB *native_db;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_GetNativeInstanceField(arg0, 0, (intptr_t*) &native_db);
if (native_db->db == NULL) {
throwClosedException();
assert(false); // Not reached
}
Dart_Handle arg1 = Dart_GetNativeArgument(arguments, 1);
Dart_TypedData_Type typed_data_type = Dart_GetTypeOfTypedData(arg1);
assert(typed_data_type == Dart_TypedData_kUint8);
char *data;
intptr_t len;
Dart_TypedDataAcquireData(arg1, &typed_data_type, (void**)&data, &len);
leveldb::Slice key = leveldb::Slice(data, len);
leveldb::Status status = native_db->db->db->Delete(leveldb::WriteOptions(), key);
Dart_TypedDataReleaseData(arg1);
maybeThrowStatus(status);
Dart_SetReturnValue(arguments, Dart_Null());
Dart_ExitScope();
}
void syncClose(Dart_NativeArguments arguments) { // (this)
Dart_EnterScope();
NativeDB *native_db;
Dart_Handle arg0 = Dart_GetNativeArgument(arguments, 0);
Dart_GetNativeInstanceField(arg0, 0, (intptr_t*) &native_db);
if (native_db->db == NULL) {
// DB has already been closed
throwClosedException();
assert(false); // Not reached
}
// Finalize all iterators
while (!native_db->iterators->empty()) {
iteratorFinalize(native_db->iterators->front());
}
unreferenceDB(native_db->db);
native_db->db = NULL;
Dart_SetReturnValue(arguments, Dart_Null());
Dart_ExitScope();
}
// Plugin
struct FunctionLookup {
const char* name;
Dart_NativeFunction function;
};
FunctionLookup function_list[] = {
{"DB_Open", dbOpen},
{"SyncIterator_New", syncNew},
{"SyncIterator_Next", syncNext},
{"SyncGet", syncGet},
{"SyncPut", syncPut},
{"SyncDelete", syncDelete},
{"SyncClose", syncClose},
{NULL, NULL}};
FunctionLookup no_scope_function_list[] = {
{NULL, NULL}
};
Dart_NativeFunction ResolveName(Dart_Handle name,
int argc,
bool* auto_setup_scope) {
if (!Dart_IsString(name)) {
return NULL;
}
Dart_NativeFunction result = NULL;
if (auto_setup_scope == NULL) {
return NULL;
}
Dart_EnterScope();
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
for (int i=0; function_list[i].name != NULL; ++i) {
if (strcmp(function_list[i].name, cname) == 0) {
*auto_setup_scope = true;
result = function_list[i].function;
break;
}
}
if (result != NULL) {
Dart_ExitScope();
return result;
}
for (int i=0; no_scope_function_list[i].name != NULL; ++i) {
if (strcmp(no_scope_function_list[i].name, cname) == 0) {
*auto_setup_scope = false;
result = no_scope_function_list[i].function;
break;
}
}
Dart_ExitScope();
return result;
}
|
#include "chokoengine.hpp"
CE_BEGIN_NAMESPACE
Vec4::Vec4(float v) : x(v), y(v), z(v), w(v) {}
Vec4::Vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
Vec4::Vec4(Vec2 a, Vec2 b) : x(a.x), y(a.y), z(b.y), w(b.y) {}
Vec4::Vec4(Vec3 v, float w) : x(v.x), y(v.y), z(v.z), w(w) {}
Vec4::operator Vec2() const {
return Vec2(x, y);
}
Vec4::operator Vec3() const {
return Vec3(x, y, z);
}
float& Vec4::operator [](const int i) {
return (&x)[i];
}
Vec4 Vec4::operator -() const {
return Vec4(-x, -y, -z, -w);
}
Vec4 Vec4::operator +(const Vec4& rhs) const {
return Vec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w);
}
Vec4 Vec4::operator -(const Vec4& rhs) const {
return Vec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w);
}
Vec4 Vec4::operator *(const Vec4& rhs) const {
return Vec4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w);
}
Vec4 Vec4::operator /(const Vec4& rhs) const {
return Vec4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w);
}
bool Vec4::operator ==(const Vec4& rhs) const {
return (x == rhs.x) && (y == rhs.y) && (z == rhs.z) && (w == rhs.w);
}
bool Vec4::operator !=(const Vec4& rhs) const {
return (x != rhs.x) || (y != rhs.y) || (z != rhs.z) || (w != rhs.w);
}
Vec4& Vec4::operator +=(const Vec4& rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
return *this;
}
Vec4& Vec4::operator -=(const Vec4& rhs) {
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
w -= rhs.w;
return *this;
}
Vec4& Vec4::operator *=(const Vec4& rhs) {
x *= rhs.x;
y *= rhs.y;
z *= rhs.z;
w *= rhs.w;
return *this;
}
Vec4& Vec4::operator /=(const Vec4& rhs) {
x /= rhs.x;
y /= rhs.y;
z /= rhs.z;
w /= rhs.w;
return *this;
}
float Vec4::dot(const Vec4& v) const {
return x * v.x + y * v.y + z * v.z + w * v.w;
}
Vec4 Vec4::normalized() const {
return (*this) / length();
}
float Vec4::length() const {
return std::sqrt(x * x + y * y + z * z + w * w);
}
float Vec4::length2() const {
return x * x + y * y + z * z + w * w;
}
std::string Vec4::str() const {
return "Vector(" + std::to_string(x) + ", "
+ std::to_string(y) + ", " + std::to_string(z) + ", " + std::to_string(w) + ")";
}
Vec4 Vec4::left(float w) {
return Vec4(-1, 0, 0, w);
}
Vec4 Vec4::right(float w) {
return Vec4(1, 0, 0, w);
}
Vec4 Vec4::up(float w) {
return Vec4(0, 1, 0, w);
}
Vec4 Vec4::down(float w) {
return Vec4(0, -1, 0, w);
}
Vec4 Vec4::front(float w) {
return Vec4(0, 0, 1, w);
}
Vec4 Vec4::back(float w) {
return Vec4(0, 0, -1, w);
}
CE_END_NAMESPACE
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace json_spirit;
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static void accountingDeprecationCheck()
{
if (!GetBoolArg("-enableaccounts", false))
throw runtime_error(
"Accounting API is deprecated and will be removed in future.\n"
"It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n"
"If you still want to enable it, add to your config file enableaccounts=1\n");
if (GetBoolArg("-staking", true))
throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n");
}
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
vector<unsigned char> vchPubKey = newKey.Raw();
return HexStr(vchPubKey.begin(), vchPubKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new VPSCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current VPSCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <VPSCoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid VPSCoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <VPSCoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid VPSCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <VPSCoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid VPSCoin address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <VPSCoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <VPSCoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <VPSCoinaddress> [minconf=1]\n"
"Returns the total amount received by <VPSCoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid VPSCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
accountingDeprecationCheck();
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64_t nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal() || wtx.GetDepthInMainChain() < 0)
continue;
int64_t nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64_t GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number.
int64_t nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsTrusted())
continue;
int64_t allFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
accountingDeprecationCheck();
string strAccount = AccountFromValue(params[0]);
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
accountingDeprecationCheck();
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64_t nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toVPSCoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid VPSCoin address");
int64_t nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
int64_t totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid VPSCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a VPSCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value addredeemscript(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
string msg = "addredeemscript <redeemScript> [account]\n"
"Add a P2SH address with a specified redeemScript to the wallet.\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Construct using pay-to-script-hash:
vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript");
CScript inner(innerData.begin(), innerData.end());
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64_t nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64_t nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64_t nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
accountingDeprecationCheck();
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
bool stop = false;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
if (!wtx.IsCoinStake())
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
else
{
entry.push_back(Pair("amount", ValueFromAmount(-nFee)));
stop = true; // only one coinstake output
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
if (stop)
break;
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
accountingDeprecationCheck();
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64_t> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
entry.push_back(Pair("confirmations", 0));
else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
else
entry.push_back(Pair("confirmations", 0));
}
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size");
nSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(nSize);
if (pwalletMain->GetKeyPoolSize() < nSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("VPSCoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("VPSCoin-lock-wa");
int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64_t nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64_t*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [stakingonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"if [stakingonly] is true sending functions are disabled.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64_t* pnSleepTime = new int64_t(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
// VPSCoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockStakingOnly = params[2].get_bool();
else
fWalletUnlockStakingOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; VPSCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <VPSCoinaddress>\n"
"Return information about <VPSCoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <VPSCoinpubkey>\n"
"Return information about <VPSCoinpubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
ret.push_back(Pair("iscompressed", isCompressed));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
// VPSCoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// VPSCoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// VPSCoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// NovaCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions(true);
return Value::null;
}
// VPSCoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
return result;
}
|
#include "common/Env.hpp"
namespace chatterino {
namespace {
QString readStringEnv(const char *envName, QString defaultValue)
{
auto envString = std::getenv(envName);
if (envString != nullptr)
{
return QString(envString);
}
return defaultValue;
}
} // namespace
Env::Env()
: recentMessagesApiUrl(
readStringEnv("CHATTERINO2_RECENT_MESSAGES_URL",
"https://recent-messages.robotty.de/api/v2/"
"recent-messages/%1?clearchatToNotice=true"))
, linkResolverUrl(readStringEnv(
"CHATTERINO2_LINK_RESOLVER_URL",
"https://braize.pajlada.com/chatterino/link_resolver/%1"))
, twitchEmoteSetResolverUrl(readStringEnv(
"CHATTERINO2_TWITCH_EMOTE_SET_RESOLVER_URL",
"https://braize.pajlada.com/chatterino/twitchemotes/set/%1/"))
{
}
const Env &Env::get()
{
static Env instance;
return instance;
}
} // namespace chatterino
|
#include "LumiereFrustum.h"
#include "Common/LumiereAssert.h"
BEGIN_LUMIERE_NAMESPACE
Frustum::Frustum()
: mFOVy(45.0f)
, mAspectRatio(1.0f)
, mNearClipDistance(0.1f)
, mFarClipDistance(100.0f)
, mPosition(0.0f, 0.0f, 0.0f)
, mFrontDir(0.0f, 0.0f, -1.0f)
, mUpDir(0.0f, 1.0f, 0.0f)
, mRightDir(1.0f, 0.0f, 0.0f)
, mViewMatrix()
, mProjectionMatrix()
, mFrustumPlaneList()
, mIsFrustumValid(false)
{
invalidateFrustum();
LUMIERE_ENSURE(!mIsFrustumValid);
}
void Frustum::setFOVy(float FOVy)
{
mFOVy = FOVy;
LUMIERE_ENSURE(mFOVy > 0.0 && mFOVy < 180.0);
invalidateFrustum();
}
void Frustum::setAspectRatio(float aspectRatio)
{
mAspectRatio = aspectRatio;
LUMIERE_ENSURE(mAspectRatio > 0.0);
invalidateFrustum();
}
void Frustum::setNearClipDistance(float nearClipDistance)
{
mNearClipDistance = nearClipDistance;
LUMIERE_ENSURE(mNearClipDistance > 0.0);
invalidateFrustum();
}
void Frustum::setFarClipDistance(float farClipDistance)
{
mFarClipDistance = farClipDistance;
LUMIERE_ENSURE(mFarClipDistance > 0.0);
invalidateFrustum();
}
void Frustum::setPosition(const Point3f& position)
{
mPosition = position;
invalidateFrustum();
}
void Frustum::lookAt(const Point3f& lookAt)
{
Vector3f lookDir = Normalize(lookAt - mPosition);
setFrontDir(lookDir);
}
void Frustum::setFrontDir(const Vector3f& frontDir)
{
mFrontDir = Normalize(frontDir);
invalidateFrustum();
}
const Matrix4x4& Frustum::getViewMatrix()
{
if (!mIsFrustumValid) {
updateFrustum();
}
return mViewMatrix;
}
const Matrix4x4& Frustum::getProjectionMatrix()
{
if (!mIsFrustumValid) {
updateFrustum();
}
return mProjectionMatrix;
}
float Frustum::getFOVy() const
{
return mFOVy;
}
float Frustum::getAspectRation() const
{
return mAspectRatio;
}
float Frustum::getNearClipDistance() const
{
return mNearClipDistance;
}
float Frustum::getFarClipDistance() const
{
return mFarClipDistance;
}
const Point3f& Frustum::getPosition() const
{
return mPosition;
}
const Vector3f& Frustum::getFrontDir() const
{
return mFrontDir;
}
bool Frustum::inFrustum(const Point3f& point)
{
if (!mIsFrustumValid) {
updateFrustum();
}
for (int i = 0; i < FrustumPlane::_size(); ++ i) {
if (mFrustumPlaneList[i].distanceToPoint(point) < 0.0) {
return false;
}
}
return true;
}
bool Frustum::inFrustum(const AxisAlignedBox& axisAlignedBox)
{
if (!mIsFrustumValid) {
updateFrustum();
}
for (int i = 0; i < FrustumPlane::_size(); ++ i) {
const auto& plane = mFrustumPlaneList[i];
bool allCornerOutside = true;
for (size_t cornerIndex = 0; cornerIndex < AxisAlignedBoxCornerIndex::_size() && allCornerOutside; ++ cornerIndex) {
const Point3f corner = axisAlignedBox.getCornerVertex(AxisAlignedBoxCornerIndex::_from_index(cornerIndex));
if (plane.distanceToPoint(corner) > 0.0) {
allCornerOutside = false;
}
}
if (allCornerOutside) {
return false;
}
}
return true;
}
void Frustum::updateFrustum()
{
updateViewMatrix();
updateProjectionMatrix();
updateFrustumPlaneList();
mIsFrustumValid = true;
}
void Frustum::updateViewMatrix()
{
const Vector3f worldUp = Normalize(Vector3f{0.0, 1.0, 0.0});
mFrontDir = Normalize(mFrontDir);
mRightDir = Normalize(Cross(mFrontDir, worldUp));
mUpDir = Normalize(Cross(mRightDir, mFrontDir));
//mViewMatrix = CalculateViewMatrix(mPosition, mPosition + mFrontDir, mUpDir);
}
void Frustum::updateProjectionMatrix()
{
//mProjectionMatrix = CalculateProjectionMatrix(mFOVy, mAspectRatio, mNearClipDistance, mFarClipDistance);
}
void Frustum::updateFrustumPlaneList()
{
float nearPlaneHeight = mNearClipDistance * std::tan(ConvertDegreeToRadians(mFOVy / 2.0));
float nearPlaneWidth = nearPlaneHeight * mAspectRatio;
float farPlaneHeight = mFarClipDistance * std::tan(ConvertDegreeToRadians(mFOVy / 2.0));
float farPlaneWidth = farPlaneHeight * mAspectRatio;
const Point3f farPlaneCenter = mPosition + mFrontDir * mFarClipDistance;
Point3f farPlaneTopLeft = farPlaneCenter + (mUpDir * (farPlaneHeight / 2.0f)) - (mRightDir * (farPlaneWidth / 2.0f));
Point3f farPlaneTopRight = farPlaneCenter + (mUpDir * (farPlaneHeight / 2.0f)) + (mRightDir * (farPlaneWidth / 2.0f));
Point3f farPlaneBottomLeft = farPlaneCenter - (mUpDir * (farPlaneHeight / 2.0f)) - (mRightDir * (farPlaneWidth / 2.0f));
Point3f farPlaneBottomRight = farPlaneCenter - (mUpDir * (farPlaneHeight / 2.0f)) + (mRightDir * (farPlaneWidth / 2.0f));
const Point3f nearPlaneCenter = mPosition + mFrontDir * mNearClipDistance;
Point3f nearPlaneTopLeft = nearPlaneCenter + (mUpDir * (nearPlaneHeight / 2.0f)) - (mRightDir * (nearPlaneWidth / 2.0f));
Point3f nearPlaneTopRight = nearPlaneCenter + (mUpDir * (nearPlaneHeight / 2.0f)) + (mRightDir * (nearPlaneWidth / 2.0f));
Point3f nearPlaneBottomLeft = nearPlaneCenter - (mUpDir * (nearPlaneHeight / 2.0f)) - (mRightDir * (nearPlaneWidth / 2.0f));
Point3f nearPlaneBottomRight = nearPlaneCenter - (mUpDir * (nearPlaneHeight / 2.0f)) + (mRightDir * (nearPlaneWidth / 2.0f));
Plane planeList[FrustumPlane::_size()];
/*
planeList[FrustumPlane::NearPlane] = Plane(mFrontDir, nearPlaneCenter);
planeList[FrustumPlane::FarPlane] = Plane(-mFrontDir, farPlaneCenter);
Vector3f tmpVector;
tmpVector = (nearPlaneCenter + mRightDir * (nearPlaneWidth / 2.0f)) - mPosition;
tmpVector = Normalize(tmpVector);
Normal3f rightPlaneNormal = Normalize(Cross(mUpDir, tmpVector));
planeList[FrustumPlane::RightPlane] = Plane(rightPlaneNormal, nearPlaneTopRight);
tmpVector = (nearPlaneCenter - mRightDir * (nearPlaneWidth / 2.0f)) - mPosition;
tmpVector = Normalize(tmpVector);
Normal3f leftPlaneNormal = Normalize(Cross(tmpVector, mUpDir));
planeList[FrustumPlane::LeftPlane] = Plane(leftPlaneNormal, nearPlaneTopLeft);
tmpVector = (nearPlaneCenter + mUpDir * (nearPlaneHeight / 2.0f)) - mPosition;
tmpVector = Normalize(tmpVector);
Normal3f topPlaneNormal = Normalize(Cross(tmpVector, mRightDir));
planeList[FrustumPlane::TopPlane] = Plane(topPlaneNormal, nearPlaneTopLeft);
tmpVector = (nearPlaneCenter - mUpDir * (nearPlaneHeight / 2.0f)) - mPosition;
tmpVector = Normalize(tmpVector);
Normal3f bottomPlaneNormal = Normalize(Cross(mRightDir, tmpVector));
planeList[FrustumPlane::BottomPlane] = Plane(bottomPlaneNormal, nearPlaneBottomLeft);
*/
for (const auto& plane : planeList) {
mFrustumPlaneList.push_back(plane);
}
LUMIERE_ENSURE(mFrustumPlaneList.size() == FrustumPlane::_size());
}
void Frustum::invalidateFrustum()
{
mIsFrustumValid = false;
}
END_LUMIERE_NAMESPACE
|
#pragma once
/* Compiler */
#include <stdint.h>
namespace interrupts
{
/**
* Public functions from int.asm
*/
extern "C"
{
/* Enables hardware based interrupts */
void enable_hw_interrupts();
/* Disables hardware based interrupts */
void disable_hw_interrupts();
}
/**
* Sets up a standard 256-entry IDT
* ...with no present interrupts
*/
void setup();
/**
* The signature for an interrupt function
*/
using int_func = void(*)(void);
/**
* Registers a given interrupt or trap
*
* Interrupts disable hw interrupts while processing
* Traps do not
*
* @param vec The interrupt vector to setup
* @param func Function to call for interrupt
* @param is_int True for an interrupt gate, false for trap
*/
void add(uint8_t vec, int_func func, bool is_int);
/**
* De-registers the given interrupt vector
*/
void remove(uint8_t vec);
}
|
// link to the problem: https://leetcode.com/problems/length-of-last-word/
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <iterator>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
class Solution {
public:
int lengthOfLastWord(std::string s) {
auto word_end = s.find_first_not_of(" ");
auto word_start = s.find_last_of(" ", word_end);
if (word_end == std::string::npos) return 0;
if (word_start == std::string::npos) return s.size();
return word_end - word_start;
}
};
// another solution
class Solution {
public:
int lengthOfLastWord(std::string s) {
int word_end = s.size() - 1;
while (s[word_end] == ' ') {
word_end--;
}
// there is at least one word, so no need to check if word_end == -1
int word_start = word_end;
while(word_start >= 0 && s[word_start] != ' ') {
word_start--;
}
return word_end - word_start;
}
};
int main(int argc, char** argv) {}
|
// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2017, Christopher Durand
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_AD7928_HPP
# error "Don't include this file directly! Use 'ad7928.hpp' instead."
#endif
// ----------------------------------------------------------------------------
namespace xpcc
{
template <typename SpiMaster, typename Cs>
Ad7928<SpiMaster, Cs>::Ad7928() : currentPowerMode{PowerMode::Normal}
{
config = ControlRegister::WriteControlReg | ControlRegister::VrefRange;
config |= ControlRegister::UnsignedOutput;
SequenceMode_t::set(config, SequenceMode::NoSequence);
PowerMode_t::set(config, PowerMode::Normal);
InputChannel_t::reset(config);
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<void>
Ad7928<SpiMaster, Cs>::initialize()
{
RF_BEGIN();
Cs::setOutput(xpcc::Gpio::High);
delayMicroseconds(1);
// reset device
RF_CALL(transfer(Register_t(0xFF)));
RF_CALL(transfer(Register_t(0xFF)));
config |= ControlRegister::WriteControlReg;
config |= ControlRegister::UnsignedOutput;
SequenceMode_t::set(config, SequenceMode::NoSequence);
PowerMode_t::set(config, PowerMode::Normal);
InputChannel_t::reset(config);
// write configuration
RF_CALL(transfer(config));
currentPowerMode = PowerMode::Normal;
RF_END();
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<ad7928::Data>
Ad7928<SpiMaster, Cs>::singleConversion(ad7928::InputChannel channel)
{
RF_BEGIN();
SequenceMode_t::set(config, SequenceMode::NoSequence);
if(currentPowerMode == PowerMode::FullShutdown) {
// power up device, will be in normal mode afterwards
RF_CALL(wakeup());
} else if(currentPowerMode == PowerMode::AutoShutdown) {
// dummy conversion to power up device
// does not alter control register (write bit = 0)
RF_CALL(transfer(ControlRegister(0)));
}
InputChannel_t::set(config, channel);
RF_CALL(transfer(config));
InputChannel_t::reset(config);
currentPowerMode = PowerMode_t::get(config);
RF_END_RETURN(data);
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<void>
Ad7928<SpiMaster, Cs>::startSequence(ad7928::SequenceChannels_t channels1,
ad7928::SequenceChannels_t channels2)
{
RF_BEGIN();
if(currentPowerMode == PowerMode::FullShutdown) {
// power up device, will be in normal mode afterwards
RF_CALL(wakeup());
} else if(currentPowerMode == PowerMode::AutoShutdown) {
// dummy conversion to power up device
// does not alter control register (write bit = 0)
RF_CALL(transfer(ControlRegister_t(0)));
}
PowerMode_t::set(config, PowerMode::Normal);
SequenceMode_t::set(config, SequenceMode::ProgramShadowRegister);
RF_CALL(transfer(config));
currentPowerMode = PowerMode::Normal;
// The next transfer writes to the shadow register
Sequence1Channels_t::set(sequenceChannels, static_cast<SequenceChannels>(channels1.value));
Sequence2Channels_t::set(sequenceChannels, static_cast<SequenceChannels>(channels2.value));
RF_CALL(transfer(sequenceChannels));
RF_END();
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<ad7928::Data>
Ad7928<SpiMaster, Cs>::nextSequenceConversion()
{
RF_BEGIN();
SequenceMode_t::set(config, SequenceMode::ContinueSequence);
// invalid if device is not in normal mode
if(currentPowerMode != PowerMode::Normal) {
RF_RETURN(data);
}
RF_CALL(transfer(config));
currentPowerMode = PowerMode_t::get(config);
RF_END_RETURN(data);
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
void
Ad7928<SpiMaster, Cs>::setExtendedRange(bool enabled)
{
if(enabled) {
config &= ~ControlRegister::VrefRange;
} else {
config |= ControlRegister::VrefRange;
}
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
bool
Ad7928<SpiMaster, Cs>::isExtendedRange()
{
return !(config & ControlRegister::VrefRange);
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
void
Ad7928<SpiMaster, Cs>::setAutoShutdownEnabled(bool enabled)
{
if(enabled) {
PowerMode_t::set(config, PowerMode::AutoShutdown);
} else {
PowerMode_t::set(config, PowerMode::Normal);
}
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
bool
Ad7928<SpiMaster, Cs>::isAutoShutdownEnabled()
{
return PowerMode_t::get(config) == PowerMode::AutoShutdown;
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<void>
Ad7928<SpiMaster, Cs>::fullShutdown()
{
SequenceMode_t::set(config, SequenceMode::NoSequence);
ControlRegister_t controlRegister = config;
PowerMode_t::set(controlRegister, PowerMode::FullShutdown);
currentPowerMode = PowerMode::FullShutdown;
return transfer(controlRegister);
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<void>
Ad7928<SpiMaster, Cs>::wakeup()
{
RF_BEGIN();
SequenceMode_t::set(config, SequenceMode::NoSequence);
PowerMode_t::set(config, PowerMode::Normal);
RF_CALL(transfer(config));
// Wait for the device to power up
delayMicroseconds(1);
currentPowerMode = PowerMode::Normal;
RF_END();
}
// ----------------------------------------------------------------------------
template <typename SpiMaster, typename Cs>
ResumableResult<void>
Ad7928<SpiMaster, Cs>::transfer(Register_t reg)
{
RF_BEGIN();
RF_WAIT_UNTIL(this->acquireMaster());
SpiMaster::setDataMode(SpiMaster::DataMode::Mode1);
Cs::reset();
outBuffer[0] = (reg.value & 0xFF00) >> 8;
outBuffer[1] = reg.value & 0xFF;
RF_CALL(SpiMaster::transfer(outBuffer, data.data, 2));
if (this->releaseMaster())
Cs::set();
RF_END();
}
} // namespace xpcc
|
#include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Meta/Information/MetaInfoModelSkeleton.h>
#include <Dy/Helper/Library/HelperJson.h>
#include <Dy/Helper/System/Assertion.h>
namespace dy
{
void to_json(_MINOUT_ nlohmann::json& j, _MIN_ const PDyModelSkelInstanceMetaInfo& p)
{
MDY_NOT_IMPLEMENTED_ASSERT();
}
void from_json(_MIN_ const nlohmann::json& j, _MINOUT_ PDyModelSkelInstanceMetaInfo& p)
{
p.mSourceType = decltype(p.mSourceType)::External;
json::GetValueFromTo(j, "ExternalPath", p.mExternalPath);
json::GetValueFromTo(j, "IsCompressed", p.mIsCompressed);
}
} /// ::dy namespace
|
// Copyright (c) 2019-2021, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#include "serac/physics/thermal_conduction.hpp"
#include "serac/infrastructure/logger.hpp"
#include "serac/numerics/expr_template_ops.hpp"
#include "serac/physics/integrators/nonlinear_reaction_integrator.hpp"
#include "serac/physics/integrators/wrapper_integrator.hpp"
#include "serac/physics/utilities/state_manager.hpp"
namespace serac {
constexpr int NUM_FIELDS = 1;
ThermalConduction::ThermalConduction(int order, const SolverOptions& options, const std::string& name)
: BasePhysics(NUM_FIELDS, order),
temperature_(StateManager::newState(FiniteElementState::Options{.order = order,
.vector_dim = 1,
.ordering = mfem::Ordering::byNODES,
.name = detail::addPrefix(name, "temperature")})),
residual_(temperature_.space().TrueVSize()),
ode_(temperature_.space().TrueVSize(), {.u = u_, .dt = dt_, .du_dt = previous_, .previous_dt = previous_dt_},
nonlin_solver_, bcs_)
{
state_.push_back(temperature_);
nonlin_solver_ = mfem_ext::EquationSolver(mesh_.GetComm(), options.T_lin_options, options.T_nonlin_options);
nonlin_solver_.SetOperator(residual_);
// Check for dynamic mode
if (options.dyn_options) {
ode_.SetTimestepper(options.dyn_options->timestepper);
ode_.SetEnforcementMethod(options.dyn_options->enforcement_method);
is_quasistatic_ = false;
} else {
is_quasistatic_ = true;
}
dt_ = 0.0;
previous_dt_ = -1.0;
int true_size = temperature_.space().TrueVSize();
u_.SetSize(true_size);
previous_.SetSize(true_size);
previous_ = 0.0;
zero_.SetSize(true_size);
zero_ = 0.0;
// Default to constant value of 1.0 for density and specific heat capacity
cp_ = std::make_unique<mfem::ConstantCoefficient>(1.0);
rho_ = std::make_unique<mfem::ConstantCoefficient>(1.0);
}
ThermalConduction::ThermalConduction(const InputOptions& options, const std::string& name)
: ThermalConduction(options.order, options.solver_options, name)
{
setConductivity(std::make_unique<mfem::ConstantCoefficient>(options.kappa));
setMassDensity(std::make_unique<mfem::ConstantCoefficient>(options.rho));
setSpecificHeatCapacity(std::make_unique<mfem::ConstantCoefficient>(options.cp));
if (options.reaction_func) {
if (options.reaction_scale_coef) {
setNonlinearReaction(options.reaction_func, options.d_reaction_func,
options.reaction_scale_coef->constructScalar());
} else {
setNonlinearReaction(options.reaction_func, options.d_reaction_func,
std::make_unique<mfem::ConstantCoefficient>(1.0));
}
}
if (options.initial_temperature) {
auto temp = options.initial_temperature->constructScalar();
setTemperature(*temp);
}
if (options.source_coef) {
setSource(options.source_coef->constructScalar());
}
// Process the BCs in sorted order for correct behavior with repeated attributes
std::map<std::string, input::BoundaryConditionInputOptions> sorted_bcs(options.boundary_conditions.begin(),
options.boundary_conditions.end());
for (const auto& [bc_name, bc] : sorted_bcs) {
// FIXME: Better naming for boundary conditions?
if (bc_name.find("temperature") != std::string::npos) {
std::shared_ptr<mfem::Coefficient> temp_coef(bc.coef_opts.constructScalar());
setTemperatureBCs(bc.attrs, temp_coef);
} else if (bc_name.find("flux") != std::string::npos) {
std::shared_ptr<mfem::Coefficient> flux_coef(bc.coef_opts.constructScalar());
setFluxBCs(bc.attrs, flux_coef);
} else {
SLIC_WARNING_ROOT("Ignoring boundary condition with unknown name: " << name);
}
}
}
void ThermalConduction::setTemperature(mfem::Coefficient& temp)
{
// Project the coefficient onto the grid function
temp.SetTime(time_);
temperature_.project(temp);
gf_initialized_[0] = true;
}
void ThermalConduction::setTemperatureBCs(const std::set<int>& temp_bdr,
std::shared_ptr<mfem::Coefficient> temp_bdr_coef)
{
bcs_.addEssential(temp_bdr, temp_bdr_coef, temperature_);
}
void ThermalConduction::setFluxBCs(const std::set<int>& flux_bdr, std::shared_ptr<mfem::Coefficient> flux_bdr_coef)
{
// Set the natural (integral) boundary condition
bcs_.addNatural(flux_bdr, flux_bdr_coef, -1);
}
void ThermalConduction::setConductivity(std::unique_ptr<mfem::Coefficient>&& kappa)
{
// Set the conduction coefficient
kappa_ = std::move(kappa);
}
void ThermalConduction::setSource(std::unique_ptr<mfem::Coefficient>&& source)
{
// Set the body source integral coefficient
source_ = std::move(source);
}
void ThermalConduction::setNonlinearReaction(std::function<double(double)> reaction,
std::function<double(double)> d_reaction,
std::unique_ptr<mfem::Coefficient>&& scale)
{
reaction_ = reaction;
d_reaction_ = d_reaction;
reaction_scale_ = std::move(scale);
}
void ThermalConduction::setSpecificHeatCapacity(std::unique_ptr<mfem::Coefficient>&& cp)
{
// Set the specific heat capacity coefficient
cp_ = std::move(cp);
}
void ThermalConduction::setMassDensity(std::unique_ptr<mfem::Coefficient>&& rho)
{
// Set the density coefficient
rho_ = std::move(rho);
}
void ThermalConduction::completeSetup()
{
SLIC_ASSERT_MSG(kappa_, "Conductivity not set in ThermalSolver!");
// Add the domain diffusion integrator to the K form
K_form_ = temperature_.createOnSpace<mfem::ParNonlinearForm>();
K_form_->AddDomainIntegrator(
new mfem_ext::BilinearToNonlinearFormIntegrator(std::make_unique<mfem::DiffusionIntegrator>(*kappa_)));
// Add the body source to the RS if specified
if (source_) {
K_form_->AddDomainIntegrator(new mfem_ext::LinearToNonlinearFormIntegrator(
std::make_unique<mfem::DomainLFIntegrator>(*source_), temperature_.space()));
}
// Add a nonlinear reaction term if specified
if (reaction_) {
K_form_->AddDomainIntegrator(
new serac::mfem_ext::NonlinearReactionIntegrator(reaction_, d_reaction_, *reaction_scale_));
}
// Build the dof array lookup tables
temperature_.space().BuildDofToArrays();
// Project the essential boundary coefficients
for (auto& bc : bcs_.essentials()) {
bc.projectBdr(temperature_, time_);
}
// Initialize the true vector
temperature_.initializeTrueVec();
if (is_quasistatic_) {
residual_ = mfem_ext::StdFunctionOperator(
temperature_.space().TrueVSize(),
[this](const mfem::Vector& u, mfem::Vector& r) {
K_form_->Mult(u, r);
r.SetSubVector(bcs_.allEssentialDofs(), 0.0);
},
[this](const mfem::Vector& u) -> mfem::Operator& {
auto& J = dynamic_cast<mfem::HypreParMatrix&>(K_form_->GetGradient(u));
bcs_.eliminateAllEssentialDofsFromMatrix(J);
return J;
});
} else {
// If dynamic, assemble the mass matrix
M_form_ = temperature_.createOnSpace<mfem::ParBilinearForm>();
// Define the mass matrix coefficient as a product of the density and specific heat capacity
mass_coef_ = std::make_unique<mfem::ProductCoefficient>(*rho_, *cp_);
M_form_->AddDomainIntegrator(new mfem::MassIntegrator(*mass_coef_));
M_form_->Assemble(0); // keep sparsity pattern of M and K the same
M_form_->Finalize();
M_.reset(M_form_->ParallelAssemble());
residual_ = mfem_ext::StdFunctionOperator(
temperature_.space().TrueVSize(),
[this](const mfem::Vector& du_dt, mfem::Vector& r) {
r = (*M_) * du_dt + (*K_form_) * (u_ + dt_ * du_dt);
r.SetSubVector(bcs_.allEssentialDofs(), 0.0);
},
[this](const mfem::Vector& du_dt) -> mfem::Operator& {
// Only reassemble the stiffness if it is a new timestep or we have a nonlinear reaction
if (dt_ != previous_dt_ || reaction_) {
auto localJ = std::unique_ptr<mfem::SparseMatrix>(
mfem::Add(1.0, M_form_->SpMat(), dt_, K_form_->GetLocalGradient(u_ + dt_ * du_dt)));
J_.reset(M_form_->ParallelAssemble(localJ.get()));
bcs_.eliminateAllEssentialDofsFromMatrix(*J_);
}
return *J_;
});
}
}
void ThermalConduction::advanceTimestep(double& dt)
{
temperature_.initializeTrueVec();
if (is_quasistatic_) {
nonlin_solver_.Mult(zero_, temperature_.trueVec());
} else {
SLIC_ASSERT_MSG(gf_initialized_[0], "Thermal state not initialized!");
// Step the time integrator
ode_.Step(temperature_.trueVec(), time_, dt);
}
temperature_.distributeSharedDofs();
cycle_ += 1;
}
void ThermalConduction::InputOptions::defineInputFileSchema(axom::inlet::Container& container)
{
// Polynomial interpolation order - currently up to 8th order is allowed
container.addInt("order", "Order degree of the finite elements.").defaultValue(1).range(1, 8);
// material parameters
container.addDouble("kappa", "Thermal conductivity").defaultValue(0.5);
container.addDouble("rho", "Density").defaultValue(1.0);
container.addDouble("cp", "Specific heat capacity").defaultValue(1.0);
auto& source = container.addStruct("source", "Scalar source term (RHS of the thermal conduction PDE)");
serac::input::CoefficientInputOptions::defineInputFileSchema(source);
auto& reaction_container = container.addStruct("nonlinear_reaction", "Nonlinear reaction term parameters");
reaction_container.addFunction("reaction_function", axom::inlet::FunctionTag::Double,
{axom::inlet::FunctionTag::Double}, "Nonlinear reaction function q = q(temperature)");
reaction_container.addFunction("d_reaction_function", axom::inlet::FunctionTag::Double,
{axom::inlet::FunctionTag::Double},
"Derivative of the nonlinear reaction function dq = dq / dTemperature");
auto& scale_coef_container = reaction_container.addStruct("scale", "Spatially varying scale factor for the reaction");
serac::input::CoefficientInputOptions::defineInputFileSchema(scale_coef_container);
auto& equation_solver_container =
container.addStruct("equation_solver", "Linear and Nonlinear stiffness Solver Parameters.");
serac::mfem_ext::EquationSolver::DefineInputFileSchema(equation_solver_container);
auto& dynamics_container = container.addStruct("dynamics", "Parameters for mass matrix inversion");
dynamics_container.addString("timestepper", "Timestepper (ODE) method to use");
dynamics_container.addString("enforcement_method", "Time-varying constraint enforcement method to use");
auto& bc_container = container.addStructDictionary("boundary_conds", "Container of boundary conditions");
serac::input::BoundaryConditionInputOptions::defineInputFileSchema(bc_container);
auto& init_temp = container.addStruct("initial_temperature", "Coefficient for initial condition");
serac::input::CoefficientInputOptions::defineInputFileSchema(init_temp);
}
} // namespace serac
using serac::DirichletEnforcementMethod;
using serac::ThermalConduction;
using serac::TimestepMethod;
serac::ThermalConduction::InputOptions FromInlet<serac::ThermalConduction::InputOptions>::operator()(
const axom::inlet::Container& base)
{
ThermalConduction::InputOptions result;
result.order = base["order"];
// Solver parameters
auto equation_solver = base["equation_solver"];
result.solver_options.T_lin_options = equation_solver["linear"].get<serac::LinearSolverOptions>();
result.solver_options.T_nonlin_options = equation_solver["nonlinear"].get<serac::NonlinearSolverOptions>();
if (base.contains("dynamics")) {
ThermalConduction::TimesteppingOptions dyn_options;
auto dynamics = base["dynamics"];
// FIXME: Implement all supported methods as part of an ODE schema
const static std::map<std::string, TimestepMethod> timestep_methods = {
{"AverageAcceleration", TimestepMethod::AverageAcceleration},
{"BackwardEuler", TimestepMethod::BackwardEuler},
{"ForwardEuler", TimestepMethod::ForwardEuler}};
std::string timestep_method = dynamics["timestepper"];
SLIC_ERROR_ROOT_IF(timestep_methods.count(timestep_method) == 0,
"Unrecognized timestep method: " << timestep_method);
dyn_options.timestepper = timestep_methods.at(timestep_method);
// FIXME: Implement all supported methods as part of an ODE schema
const static std::map<std::string, DirichletEnforcementMethod> enforcement_methods = {
{"RateControl", DirichletEnforcementMethod::RateControl}};
std::string enforcement_method = dynamics["enforcement_method"];
SLIC_ERROR_ROOT_IF(enforcement_methods.count(enforcement_method) == 0,
"Unrecognized enforcement method: " << enforcement_method);
dyn_options.enforcement_method = enforcement_methods.at(enforcement_method);
result.solver_options.dyn_options = std::move(dyn_options);
}
if (base.contains("nonlinear_reaction")) {
auto reaction = base["nonlinear_reaction"];
result.reaction_func = reaction["reaction_function"].get<std::function<double(double)>>();
result.d_reaction_func = reaction["d_reaction_function"].get<std::function<double(double)>>();
if (reaction.contains("scale")) {
result.reaction_scale_coef = reaction["scale"].get<serac::input::CoefficientInputOptions>();
}
}
if (base.contains("source")) {
result.source_coef = base["source"].get<serac::input::CoefficientInputOptions>();
}
// Set the material parameters
result.kappa = base["kappa"];
result.rho = base["rho"];
result.cp = base["cp"];
result.boundary_conditions =
base["boundary_conds"].get<std::unordered_map<std::string, serac::input::BoundaryConditionInputOptions>>();
if (base.contains("initial_temperature")) {
result.initial_temperature = base["initial_temperature"].get<serac::input::CoefficientInputOptions>();
}
return result;
}
|
/**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define sf(a) scanf("%lld",&a)
#define sf2(a,b) scanf("%lld %lld",&a,&b)
#define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#ifdef redback
#define bug printf("line=%d\n",__LINE__);
#define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;}
struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg;
#else
#define bug
#define debug(args...)
#endif //debugging macros
int main()
{
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
ll t=1,tc;
//sf(tc);
ll l,m,n;
while(~sf2(n,m)) {
ll i,j,k;
printf("%lld\n",min(n,m)+1);
for(i=0,j=min(n,m);i<=min(n,m);i++,j--)
{
printf("%lld %lld\n",i,j);
}
}
return 0;
}
|
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdlib>
#include <random>
#include <string>
// clang-format off
#ifdef ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#define DEFAULT_FLOAT_TOLERANCE_BITS ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#endif
#ifdef ${BACKEND_NAME}_DOUBLE_TOLERANCE_BITS
#define DEFAULT_DOUBLE_TOLERANCE_BITS ${BACKEND_NAME}_DOUBLE_TOLERANCE_BITS
#endif
// clang-format on
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/ndarray.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
template <typename optype, typename itype, typename otype>
void check_auto_bcast(
const std::vector<std::vector<itype>>& inputs,
const std::vector<otype> output,
const op::AutoBroadcastSpec& autob = op::AutoBroadcastSpec(op::AutoBroadcastType::NUMPY))
{
auto iet = element::from<itype>();
auto oet = element::from<otype>();
if (std::is_same<itype, char>::value)
{
iet = element::boolean;
}
if (std::is_same<otype, char>::value)
{
oet = element::boolean;
}
auto A = make_shared<op::Parameter>(iet, Shape{2, 3});
auto B = make_shared<op::Parameter>(iet, Shape{3});
auto f = make_shared<Function>(make_shared<optype>(A, B, autob), ParameterVector{A, B});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
shared_ptr<runtime::Tensor> a = backend->create_tensor(iet, Shape{2, 3});
shared_ptr<runtime::Tensor> b = backend->create_tensor(iet, Shape{3});
shared_ptr<runtime::Tensor> result = backend->create_tensor(oet, Shape{2, 3});
copy_data(a, inputs[0]);
copy_data(b, inputs[1]);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, b});
EXPECT_TRUE(test::all_close(read_vector<otype>(result), output));
}
NGRAPH_TEST(${BACKEND_NAME}, auto_bcast_binary_elementwise)
{
check_auto_bcast<op::Add, float, float>({{1, 2, 3, 4, 5, 6}, {5, 6, 7}}, {6, 8, 10, 9, 11, 13});
check_auto_bcast<op::Subtract, float, float>({{1, 2, 3, 4, 5, 6}, {5, 6, 7}},
{-4.f, -4.f, -4.f, -1.f, -1.f, -1.f});
check_auto_bcast<op::Multiply, float, float>({{1, 2, 3, 4, 5, 6}, {5, 6, 7}},
{5, 12, 21, 20, 30, 42});
check_auto_bcast<op::Divide, float, float>({{4, 5, 6, 7, 8, 9}, {1, 2, 3}},
{4, 2.5f, 2, 7, 4, 3});
check_auto_bcast<op::Maximum, float, float>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}},
{1, 5, 8, 4, 5, 8});
check_auto_bcast<op::Minimum, float, float>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}},
{1, 2, 3, 1, 5, 6});
check_auto_bcast<op::Power, float, float>({{1, 2, 3, 4, 5, 6}, {1, 2, 3}},
{1, 4, 27, 4, 25, 216});
check_auto_bcast<op::And, char, char>({{1, 0, 1, 0, 0, 1}, {1, 0, 1}}, {1, 0, 1, 0, 0, 1});
check_auto_bcast<op::Or, char, char>({{1, 0, 1, 0, 1, 1}, {1, 0, 0}}, {1, 0, 1, 1, 1, 1});
check_auto_bcast<op::Equal, uint8_t, char>({{1, 0, 1, 0, 1, 1}, {1, 0, 0}}, {1, 1, 0, 0, 0, 0});
check_auto_bcast<op::Greater, float, char>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {0, 0, 0, 1, 0, 0});
check_auto_bcast<op::GreaterEq, float, char>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}},
{1, 0, 0, 1, 1, 0});
check_auto_bcast<op::Less, uint8_t, char>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {0, 1, 1, 0, 0, 1});
check_auto_bcast<op::LessEq, uint8_t, char>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}},
{1, 1, 1, 0, 1, 1});
check_auto_bcast<op::NotEqual, uint8_t, char>({{1, 2, 3, 4, 5, 6}, {1, 5, 8}},
{0, 1, 1, 1, 0, 1});
}
NGRAPH_TEST(${BACKEND_NAME}, auto_bcast_binary_elementwise_pdpd)
{
const op::AutoBroadcastSpec& autob = op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, 1);
check_auto_bcast<op::Add, float, float>(
{{1, 2, 3, 4, 5, 6}, {5, 6, 7}}, {6, 8, 10, 9, 11, 13}, autob);
check_auto_bcast<op::Subtract, float, float>(
{{1, 2, 3, 4, 5, 6}, {5, 6, 7}}, {-4.f, -4.f, -4.f, -1.f, -1.f, -1.f}, autob);
check_auto_bcast<op::Multiply, float, float>(
{{1, 2, 3, 4, 5, 6}, {5, 6, 7}}, {5, 12, 21, 20, 30, 42}, autob);
check_auto_bcast<op::Divide, float, float>(
{{4, 5, 6, 7, 8, 9}, {1, 2, 3}}, {4, 2.5f, 2, 7, 4, 3}, autob);
check_auto_bcast<op::Maximum, float, float>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {1, 5, 8, 4, 5, 8}, autob);
check_auto_bcast<op::Minimum, float, float>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {1, 2, 3, 1, 5, 6}, autob);
check_auto_bcast<op::Power, float, float>(
{{1, 2, 3, 4, 5, 6}, {1, 2, 3}}, {1, 4, 27, 4, 25, 216}, autob);
check_auto_bcast<op::And, char, char>(
{{1, 0, 1, 0, 0, 1}, {1, 0, 1}}, {1, 0, 1, 0, 0, 1}, autob);
check_auto_bcast<op::Or, char, char>(
{{1, 0, 1, 0, 1, 1}, {1, 0, 0}}, {1, 0, 1, 1, 1, 1}, autob);
check_auto_bcast<op::Equal, uint8_t, char>(
{{1, 0, 1, 0, 1, 1}, {1, 0, 0}}, {1, 1, 0, 0, 0, 0}, autob);
check_auto_bcast<op::Greater, float, char>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {0, 0, 0, 1, 0, 0}, autob);
check_auto_bcast<op::GreaterEq, float, char>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {1, 0, 0, 1, 1, 0}, autob);
check_auto_bcast<op::Less, uint8_t, char>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {0, 1, 1, 0, 0, 1}, autob);
check_auto_bcast<op::LessEq, uint8_t, char>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {1, 1, 1, 0, 1, 1}, autob);
check_auto_bcast<op::NotEqual, uint8_t, char>(
{{1, 2, 3, 4, 5, 6}, {1, 5, 8}}, {0, 1, 1, 1, 0, 1}, autob);
}
NGRAPH_TEST(${BACKEND_NAME}, auto_bcast_binary_elementwise_pdpd_dynamic)
{
auto pshape_a = PartialShape::dynamic();
auto pshape_b = PartialShape::dynamic();
auto a = make_shared<op::Parameter>(element::f32, pshape_a);
auto b = make_shared<op::Parameter>(element::f32, pshape_b);
op::AutoBroadcastSpec autob = op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, -1);
auto f = make_shared<Function>(make_shared<op::Add>(a, b, autob), ParameterVector{a, b});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
auto t_a = backend->create_tensor(element::f32, Shape{2, 3});
auto t_b = backend->create_tensor(element::f32, Shape{3});
copy_data(t_a, vector<float>{1, 2, 3, 4, 5, 6});
copy_data(t_b, vector<float>{5, 6, 7});
ex->call_with_validate({t_r}, {t_a, t_b});
ASSERT_EQ(t_r->get_shape(), (Shape{2, 3}));
auto results = read_vector<float>(t_r);
vector<float> expected_values{6, 8, 10, 9, 11, 13};
EXPECT_TRUE(test::all_close_f(results, expected_values));
// a shape {2, 3, 4, 5}, b shape {3, 4} axis = 1
autob = op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, 1);
f = make_shared<Function>(make_shared<op::Add>(a, b, autob), ParameterVector{a, b});
ex = backend->compile(f);
t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
t_a = backend->create_tensor(element::f32, Shape{2, 3, 4, 5});
t_b = backend->create_tensor(element::f32, Shape{3, 4});
copy_data(t_a, vector<float>(2 * 3 * 4 * 5, 1));
copy_data(t_b, vector<float>(3 * 4, 1));
ex->call_with_validate({t_r}, {t_a, t_b});
ASSERT_EQ(t_r->get_shape(), (Shape{2, 3, 4, 5}));
// a shape {2, 3, 4, 5}, b shape {3, 1} axis = 1
t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
t_a = backend->create_tensor(element::f32, Shape{2, 3, 4, 5});
t_b = backend->create_tensor(element::f32, Shape{3, 1});
copy_data(t_a, vector<float>(2 * 3 * 4 * 5, 1));
copy_data(t_b, vector<float>(3, 1));
ex->call_with_validate({t_r}, {t_a, t_b});
ASSERT_EQ(t_r->get_shape(), (Shape{2, 3, 4, 5}));
}
|
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int get_digits(int n)
{
int count = 0;
while(n / 10 != 0)
{
count++;
n = n / 10;
}
return count;
}
int get_max(int a, int b)
{
int count_a = get_digits(a);
int count_b = get_digits(b);
int temp_a = (a * (int)pow(10, count_b + 1)) + b;
int temp_b = (b * (int)pow(10, count_a + 1)) + a;
if(temp_a >= temp_b)
return a;
else
return b;
}
void get_max_salary(int n, vector<int> numbers)
{
int temp_n = n;
int max_digit = -1;
int temp_index = 0;
while(temp_n != 0)
{
max_digit = numbers[0];
temp_index = 0;
for(int i = 1; i < n; i++)
{
max_digit = get_max(max_digit, numbers[i]);
if(max_digit == numbers[i])
{
temp_index = i;
}
}
numbers[temp_index] = 0;
cout<<max_digit;
temp_n--;
}
}
int main()
{
int n = 0;
cin>>n;
vector<int> numbers(n);
for(int i = 0; i < n; i++)
cin>>numbers[i];
get_max_salary(n, numbers);
//cout<<'\n';
return 0;
}
|
#include "source/common/grpc/async_client_manager_impl.h"
#include "envoy/config/core/v3/grpc_service.pb.h"
#include "envoy/stats/scope.h"
#include "source/common/common/base64.h"
#include "source/common/grpc/async_client_impl.h"
#include "absl/strings/match.h"
#ifdef ENVOY_GOOGLE_GRPC
#include "source/common/grpc/google_async_client_impl.h"
#endif
namespace Envoy {
namespace Grpc {
namespace {
// Validates a string for gRPC header key compliance. This is a subset of legal HTTP characters.
// See https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
bool validateGrpcHeaderChars(absl::string_view key) {
for (auto ch : key) {
if (!(absl::ascii_isalnum(ch) || ch == '_' || ch == '.' || ch == '-')) {
return false;
}
}
return true;
}
bool validateGrpcCompatibleAsciiHeaderValue(absl::string_view h_value) {
for (auto ch : h_value) {
if (ch < 0x20 || ch > 0x7e) {
return false;
}
}
return true;
}
} // namespace
AsyncClientFactoryImpl::AsyncClientFactoryImpl(Upstream::ClusterManager& cm,
const envoy::config::core::v3::GrpcService& config,
bool skip_cluster_check, TimeSource& time_source)
: cm_(cm), config_(config), time_source_(time_source) {
if (skip_cluster_check) {
return;
}
cm_.checkActiveStaticCluster(config.envoy_grpc().cluster_name());
}
AsyncClientManagerImpl::AsyncClientManagerImpl(Upstream::ClusterManager& cm,
ThreadLocal::Instance& tls, TimeSource& time_source,
Api::Api& api, const StatNames& stat_names)
: cm_(cm), tls_(tls), time_source_(time_source), api_(api), stat_names_(stat_names),
raw_async_client_cache_(tls_) {
raw_async_client_cache_.set(
[](Event::Dispatcher&) { return std::make_shared<RawAsyncClientCache>(); });
#ifdef ENVOY_GOOGLE_GRPC
google_tls_slot_ = tls.allocateSlot();
google_tls_slot_->set(
[&api](Event::Dispatcher&) { return std::make_shared<GoogleAsyncClientThreadLocal>(api); });
#else
UNREFERENCED_PARAMETER(api_);
#endif
}
RawAsyncClientPtr AsyncClientFactoryImpl::createUncachedRawAsyncClient() {
return std::make_unique<AsyncClientImpl>(cm_, config_, time_source_);
}
GoogleAsyncClientFactoryImpl::GoogleAsyncClientFactoryImpl(
ThreadLocal::Instance& tls, ThreadLocal::Slot* google_tls_slot, Stats::Scope& scope,
const envoy::config::core::v3::GrpcService& config, Api::Api& api, const StatNames& stat_names)
: tls_(tls), google_tls_slot_(google_tls_slot),
scope_(scope.createScope(fmt::format("grpc.{}.", config.google_grpc().stat_prefix()))),
config_(config), api_(api), stat_names_(stat_names) {
#ifndef ENVOY_GOOGLE_GRPC
UNREFERENCED_PARAMETER(tls_);
UNREFERENCED_PARAMETER(google_tls_slot_);
UNREFERENCED_PARAMETER(scope_);
UNREFERENCED_PARAMETER(config_);
UNREFERENCED_PARAMETER(api_);
UNREFERENCED_PARAMETER(stat_names_);
throw EnvoyException("Google C++ gRPC client is not linked");
#else
ASSERT(google_tls_slot_ != nullptr);
#endif
// Check metadata for gRPC API compliance. Uppercase characters are lowered in the HeaderParser.
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
for (const auto& header : config.initial_metadata()) {
// Validate key
if (!validateGrpcHeaderChars(header.key())) {
throw EnvoyException(
fmt::format("Illegal characters in gRPC initial metadata header key: {}.", header.key()));
}
// Validate value
// Binary base64 encoded - handled by the GRPC library
if (!::absl::EndsWith(header.key(), "-bin") &&
!validateGrpcCompatibleAsciiHeaderValue(header.value())) {
throw EnvoyException(fmt::format(
"Illegal ASCII value for gRPC initial metadata header key: {}.", header.key()));
}
}
}
RawAsyncClientPtr GoogleAsyncClientFactoryImpl::createUncachedRawAsyncClient() {
#ifdef ENVOY_GOOGLE_GRPC
GoogleGenericStubFactory stub_factory;
return std::make_unique<GoogleAsyncClientImpl>(
tls_.dispatcher(), google_tls_slot_->getTyped<GoogleAsyncClientThreadLocal>(), stub_factory,
scope_, config_, api_, stat_names_);
#else
return nullptr;
#endif
}
AsyncClientFactoryPtr
AsyncClientManagerImpl::factoryForGrpcService(const envoy::config::core::v3::GrpcService& config,
Stats::Scope& scope, bool skip_cluster_check) {
switch (config.target_specifier_case()) {
case envoy::config::core::v3::GrpcService::TargetSpecifierCase::kEnvoyGrpc:
return std::make_unique<AsyncClientFactoryImpl>(cm_, config, skip_cluster_check, time_source_);
case envoy::config::core::v3::GrpcService::TargetSpecifierCase::kGoogleGrpc:
return std::make_unique<GoogleAsyncClientFactoryImpl>(tls_, google_tls_slot_.get(), scope,
config, api_, stat_names_);
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
return nullptr;
}
RawAsyncClientSharedPtr AsyncClientManagerImpl::getOrCreateRawAsyncClient(
const envoy::config::core::v3::GrpcService& config, Stats::Scope& scope,
bool skip_cluster_check, CacheOption cache_option) {
if (cache_option == CacheOption::CacheWhenRuntimeEnabled &&
!Runtime::runtimeFeatureEnabled("envoy.reloadable_features.enable_grpc_async_client_cache")) {
return factoryForGrpcService(config, scope, skip_cluster_check)->createUncachedRawAsyncClient();
}
RawAsyncClientSharedPtr client = raw_async_client_cache_->getCache(config);
if (client != nullptr) {
return client;
}
client = factoryForGrpcService(config, scope, skip_cluster_check)->createUncachedRawAsyncClient();
raw_async_client_cache_->setCache(config, client);
return client;
}
RawAsyncClientSharedPtr AsyncClientManagerImpl::RawAsyncClientCache::getCache(
const envoy::config::core::v3::GrpcService& config) const {
auto it = cache_.find(config);
if (it == cache_.end()) {
return nullptr;
}
return it->second;
}
void AsyncClientManagerImpl::RawAsyncClientCache::setCache(
const envoy::config::core::v3::GrpcService& config, const RawAsyncClientSharedPtr& client) {
cache_[config] = client;
}
} // namespace Grpc
} // namespace Envoy
|
#include <utility>
#include <vector>
#include "core/rts.h"
#include "core/unroller.h"
#include "engines/kinduction.h"
#include "engines/mbic3.h"
#include "gtest/gtest.h"
#include "smt/available_solvers.h"
#include "utils/exceptions.h"
using namespace pono;
using namespace smt;
using namespace std;
namespace pono_tests {
class UFUnitTests : public ::testing::Test,
public ::testing::WithParamInterface<SolverEnum>
{
protected:
void SetUp() override
{
s = create_solver(GetParam());
boolsort = s->make_sort(BOOL);
bvsort = s->make_sort(BV, 8);
funsort = s->make_sort(FUNCTION, { bvsort, boolsort });
}
SmtSolver s;
Sort boolsort, bvsort, funsort;
};
TEST_P(UFUnitTests, InductiveProp)
{
// TODO: update this when boolector supports substitution for terms
// with UF without logging
if (s->get_solver_enum() == BTOR)
{
std::cout << "Warning: not running test with btor because it "
<< "doesn't support substitution (used in unrolling) for "
<< " terms containing UFs without using logging." << std::endl;
return;
}
RelationalTransitionSystem rts(s);
Term x = rts.make_statevar("x", bvsort);
Term f = s->make_symbol("f", funsort);
rts.constrain_init(rts.make_term(Equal, x, rts.make_term(1, bvsort)));
rts.assign_next(x, rts.make_term(BVAdd, x, rts.make_term(1, bvsort)));
rts.constrain_init(rts.make_term(Apply, f, rts.make_term(0, bvsort)));
// f(x-1) -> f(x)
// f(0) holds which is like the base case
// because x starts at 1
rts.constrain_trans(rts.make_term(
Implies,
rts.make_term(
Apply, f, rts.make_term(BVSub, x, rts.make_term(1, bvsort))),
rts.make_term(Apply, f, x)));
Term p = rts.make_term(
Apply, f, rts.make_term(BVSub, x, rts.make_term(1, bvsort)));
Property prop(rts.solver(), p);
s->push();
KInduction kind(prop, rts, s);
ProverResult r = kind.check_until(5);
EXPECT_EQ(r, ProverResult::TRUE);
s->pop();
// TODO: re-enable support for UF in ModelBasedIC3
// s->push();
// ModelBasedIC3 ic3(prop, s);
// r = ic3.check_until(10);
// EXPECT_EQ(r, ProverResult::TRUE);
// s->pop();
}
TEST_P(UFUnitTests, FalseProp)
{
// TODO: update this when boolector supports substitution for terms
// with UF without logging
if (s->get_solver_enum() == BTOR) {
std::cout << "Warning: not running btor because it doesn't support "
<< "substitution (used in unrolling) for terms containing "
<< "UFs without using logging." << std::endl;
return;
}
// TODO: update this when the bug is fixed
if (s->get_solver_enum() == CVC5) {
std::cout << "Warning: not running with CVC5 because it segfaults "
<< "in the TsatProof part of its modded minisat for "
<< "an unknown reason." << std::endl;
return;
}
RelationalTransitionSystem rts(s);
Term x = rts.make_statevar("x", bvsort);
Term f = s->make_symbol("f", funsort);
rts.constrain_init(rts.make_term(Equal, x, rts.make_term(1, bvsort)));
rts.assign_next(x, rts.make_term(BVAdd, x, rts.make_term(1, bvsort)));
// this time not including the base case condition (makes it false)
// rts.constrain_init(rts.make_term(Apply, f, rts.make_term(0, bvsort)));
// f(x-1) -> f(x)
// but this time f(0) isn't forced to hold
rts.constrain_trans(rts.make_term(
Implies,
rts.make_term(
Apply, f, rts.make_term(BVSub, x, rts.make_term(1, bvsort))),
rts.make_term(Apply, f, x)));
// guart property with a precondition so it doesn't fail in the initial state
Term p = rts.make_term(
Implies,
rts.make_term(BVUge, x, rts.make_term(10, bvsort)),
rts.make_term(
Apply, f, rts.make_term(BVSub, x, rts.make_term(1, bvsort))));
Property prop(rts.solver(), p);
ASSERT_FALSE(rts.is_functional());
s->push();
KInduction kind(prop, rts, s);
ProverResult r = kind.check_until(10);
EXPECT_EQ(r, ProverResult::FALSE);
s->pop();
// TODO: re-enable support for UF in ModelBasedIC3 once we handle it correctly
// s->push();
// ModelBasedIC3 ic3(prop, s);
// r = ic3.check_until(10);
// EXPECT_EQ(r, ProverResult::FALSE);
// s->pop();
}
INSTANTIATE_TEST_SUITE_P(ParameterizedUFUnitTests,
UFUnitTests,
testing::ValuesIn(available_solver_enums()));
} // namespace pono_tests
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "test/test_abosom.h"
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)
static CNetAddr ResolveIP(const char* ip)
{
CNetAddr addr;
LookupHost(ip, addr, false);
return addr;
}
static CSubNet ResolveSubNet(const char* subnet)
{
CSubNet ret;
LookupSubNet(subnet, ret);
return ret;
}
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(ResolveIP("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(ResolveIP("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(ResolveIP("127.0.0.1").IsIPv4());
BOOST_CHECK(ResolveIP("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(ResolveIP("::1").IsIPv6());
BOOST_CHECK(ResolveIP("10.0.0.1").IsRFC1918());
BOOST_CHECK(ResolveIP("192.168.1.1").IsRFC1918());
BOOST_CHECK(ResolveIP("172.31.255.255").IsRFC1918());
BOOST_CHECK(ResolveIP("2001:0DB8::").IsRFC3849());
BOOST_CHECK(ResolveIP("169.254.1.1").IsRFC3927());
BOOST_CHECK(ResolveIP("2002::1").IsRFC3964());
BOOST_CHECK(ResolveIP("FC00::").IsRFC4193());
BOOST_CHECK(ResolveIP("2001::2").IsRFC4380());
BOOST_CHECK(ResolveIP("2001:10::").IsRFC4843());
BOOST_CHECK(ResolveIP("FE80::").IsRFC4862());
BOOST_CHECK(ResolveIP("64:FF9B::").IsRFC6052());
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(ResolveIP("127.0.0.1").IsLocal());
BOOST_CHECK(ResolveIP("::1").IsLocal());
BOOST_CHECK(ResolveIP("8.8.8.8").IsRoutable());
BOOST_CHECK(ResolveIP("2001::1").IsRoutable());
BOOST_CHECK(ResolveIP("127.0.0.1").IsValid());
}
bool static TestSplitHost(std::string test, std::string host, int port)
{
std::string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:9999", "127.0.0.1", 9999));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:9999", "127.0.0.1", 9999));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:9999", "::ffff:127.0.0.1", 9999));
BOOST_CHECK(TestSplitHost("[::]:9999", "::", 9999));
BOOST_CHECK(TestSplitHost("::9999", "::9999", -1));
BOOST_CHECK(TestSplitHost(":9999", "", 9999));
BOOST_CHECK(TestSplitHost("[]:9999", "", 9999));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(std::string src, std::string canon)
{
CService addr(LookupNumeric(src.c_str(), 65535));
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:9999", "127.0.0.1:9999"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:9999", "[::]:9999"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", "[::]:0"));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1(ResolveIP("5wyqrzbvrdsumnok.onion"));
CNetAddr addr2(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"));
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_CASE(subnet_test)
{
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") == ResolveSubNet("1.2.3.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") != ResolveSubNet("1.2.4.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.2.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4/32").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4/32").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(ResolveSubNet("::ffff:127.0.0.1").Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:0/112").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(ResolveSubNet("192.168.0.1/24").Match(ResolveIP("192.168.0.2")));
BOOST_CHECK(ResolveSubNet("192.168.0.20/29").Match(ResolveIP("192.168.0.18")));
BOOST_CHECK(ResolveSubNet("1.2.2.1/24").Match(ResolveIP("1.2.2.4")));
BOOST_CHECK(ResolveSubNet("1.2.2.110/31").Match(ResolveIP("1.2.2.111")));
BOOST_CHECK(ResolveSubNet("1.2.2.20/26").Match(ResolveIP("1.2.2.63")));
// All-Matching IPv6 Matches arbitrary IPv4 and IPv6
BOOST_CHECK(ResolveSubNet("::/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(ResolveSubNet("::/0").Match(ResolveIP("1.2.3.4")));
// All-Matching IPv4 does not Match IPv6
BOOST_CHECK(!ResolveSubNet("0.0.0.0/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
// Invalid subnets Match nothing (not even invalid addresses)
BOOST_CHECK(!CSubNet().Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("").Match(ResolveIP("4.5.6.7")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("0.0.0.0")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("hab")));
// Check valid/invalid
BOOST_CHECK(ResolveSubNet("1.2.3.0/0").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1.2.3.0/32").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/33").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/0").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/33").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/128").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/129").IsValid());
BOOST_CHECK(!ResolveSubNet("fuzzy").IsValid());
//CNetAddr constructor test
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(!CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.2")));
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).ToString() == "127.0.0.1/32");
CSubNet subnet = CSubNet(ResolveIP("1.2.3.4"), 32);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), 8);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), 0);
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.255.255.255"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("0.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128");
subnet = ResolveSubNet("1.2.3.4/255.255.255.255");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = ResolveSubNet("1.2.3.4/255.255.255.254");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31");
subnet = ResolveSubNet("1.2.3.4/255.255.255.252");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30");
subnet = ResolveSubNet("1.2.3.4/255.255.255.248");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29");
subnet = ResolveSubNet("1.2.3.4/255.255.255.240");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28");
subnet = ResolveSubNet("1.2.3.4/255.255.255.224");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27");
subnet = ResolveSubNet("1.2.3.4/255.255.255.192");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26");
subnet = ResolveSubNet("1.2.3.4/255.255.255.128");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25");
subnet = ResolveSubNet("1.2.3.4/255.255.255.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24");
subnet = ResolveSubNet("1.2.3.4/255.255.254.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23");
subnet = ResolveSubNet("1.2.3.4/255.255.252.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22");
subnet = ResolveSubNet("1.2.3.4/255.255.248.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21");
subnet = ResolveSubNet("1.2.3.4/255.255.240.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20");
subnet = ResolveSubNet("1.2.3.4/255.255.224.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19");
subnet = ResolveSubNet("1.2.3.4/255.255.192.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18");
subnet = ResolveSubNet("1.2.3.4/255.255.128.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17");
subnet = ResolveSubNet("1.2.3.4/255.255.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16");
subnet = ResolveSubNet("1.2.3.4/255.254.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15");
subnet = ResolveSubNet("1.2.3.4/255.252.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14");
subnet = ResolveSubNet("1.2.3.4/255.248.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13");
subnet = ResolveSubNet("1.2.3.4/255.240.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12");
subnet = ResolveSubNet("1.2.3.4/255.224.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11");
subnet = ResolveSubNet("1.2.3.4/255.192.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10");
subnet = ResolveSubNet("1.2.3.4/255.128.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9");
subnet = ResolveSubNet("1.2.3.4/255.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = ResolveSubNet("1.2.3.4/254.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7");
subnet = ResolveSubNet("1.2.3.4/252.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6");
subnet = ResolveSubNet("1.2.3.4/248.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5");
subnet = ResolveSubNet("1.2.3.4/240.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4");
subnet = ResolveSubNet("1.2.3.4/224.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3");
subnet = ResolveSubNet("1.2.3.4/192.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2");
subnet = ResolveSubNet("1.2.3.4/128.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1");
subnet = ResolveSubNet("1.2.3.4/0.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "::/0");
subnet = ResolveSubNet("1.2.3.4/255.255.232.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/255.255.232.0");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
}
BOOST_AUTO_TEST_CASE(netbase_getgroup)
{
BOOST_CHECK(ResolveIP("127.0.0.1").GetGroup() == boost::assign::list_of(0)); // Local -> !Routable()
BOOST_CHECK(ResolveIP("257.0.0.1").GetGroup() == boost::assign::list_of(0)); // !Valid -> !Routable()
BOOST_CHECK(ResolveIP("10.0.0.1").GetGroup() == boost::assign::list_of(0)); // RFC1918 -> !Routable()
BOOST_CHECK(ResolveIP("169.254.1.1").GetGroup() == boost::assign::list_of(0)); // RFC3927 -> !Routable()
BOOST_CHECK(ResolveIP("1.2.3.4").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // IPv4
BOOST_CHECK(ResolveIP("::FFFF:0:102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6145
BOOST_CHECK(ResolveIP("64:FF9B::102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6052
BOOST_CHECK(ResolveIP("2002:102:304:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC3964
BOOST_CHECK(ResolveIP("2001:0:9999:9999:9999:9999:FEFD:FCFB").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC4380
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetGroup() == boost::assign::list_of((unsigned char)NET_TOR)(239)); // Tor
BOOST_CHECK(ResolveIP("2001:470:abcd:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(4)(112)(175)); //he.net
BOOST_CHECK(ResolveIP("2001:2001:9999:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(32)(1)); //IPv6
}
BOOST_AUTO_TEST_SUITE_END()
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "localsocketcontroller.h"
#include "errorhandler.h"
#include "ipaddress.h"
#include "leakdetector.h"
#include "logger.h"
#include "models/device.h"
#include "models/keys.h"
#include "models/server.h"
#include "mozillavpn.h"
#include "settingsholder.h"
#include <QDir>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QStandardPaths>
#include <QHostAddress>
namespace {
Logger logger(LOG_CONTROLLER, "LocalSocketController");
}
LocalSocketController::LocalSocketController() {
MVPN_COUNT_CTOR(LocalSocketController);
m_socket = new QLocalSocket(this);
connect(m_socket, &QLocalSocket::connected, this,
&LocalSocketController::daemonConnected);
connect(m_socket, &QLocalSocket::disconnected, this,
&LocalSocketController::disconnected);
connect(m_socket, &QLocalSocket::errorOccurred, this,
&LocalSocketController::errorOccurred);
connect(m_socket, &QLocalSocket::readyRead, this,
&LocalSocketController::readData);
}
LocalSocketController::~LocalSocketController() {
MVPN_COUNT_DTOR(LocalSocketController);
}
void LocalSocketController::errorOccurred(
QLocalSocket::LocalSocketError error) {
logger.error() << "Error occurred:" << error;
if (m_state == eInitializing) {
emit initialized(false, false, QDateTime());
}
m_state = eDisconnected;
MozillaVPN::instance()->errorHandle(ErrorHandler::ControllerError);
emit disconnected();
}
void LocalSocketController::initialize(const Device* device, const Keys* keys) {
logger.debug() << "Initializing";
Q_UNUSED(device);
Q_UNUSED(keys);
Q_ASSERT(m_state == eUnknown);
m_state = eInitializing;
#ifdef MVPN_WINDOWS
QString path = "\\\\.\\pipe\\mozillavpn";
#else
QString path = "/var/run/mozillavpn/daemon.socket";
if (!QFileInfo::exists(path)) {
path = "/tmp/mozillavpn.socket";
}
#endif
logger.debug() << "Connecting to:" << path;
m_socket->connectToServer(path);
}
void LocalSocketController::daemonConnected() {
logger.debug() << "Daemon connected";
Q_ASSERT(m_state == eInitializing);
checkStatus();
}
void LocalSocketController::activate(const HopConnection& hop,
const Device* device, const Keys* keys,
Reason reason) {
Q_UNUSED(reason);
QJsonObject json;
json.insert("type", "activate");
json.insert("hopindex", QJsonValue((double)hop.m_hopindex));
json.insert("privateKey", QJsonValue(keys->privateKey()));
json.insert("deviceIpv4Address", QJsonValue(device->ipv4Address()));
json.insert("deviceIpv6Address", QJsonValue(device->ipv6Address()));
json.insert("serverPublicKey", QJsonValue(hop.m_server.publicKey()));
json.insert("serverIpv4AddrIn", QJsonValue(hop.m_server.ipv4AddrIn()));
json.insert("serverIpv6AddrIn", QJsonValue(hop.m_server.ipv6AddrIn()));
json.insert("serverPort", QJsonValue((double)hop.m_server.choosePort()));
if (hop.m_hopindex == 0) {
json.insert("serverIpv4Gateway", QJsonValue(hop.m_server.ipv4Gateway()));
json.insert("serverIpv6Gateway", QJsonValue(hop.m_server.ipv6Gateway()));
json.insert("dnsServer", QJsonValue(hop.m_dnsServer.toString()));
}
QJsonArray jsAllowedIPAddesses;
for (const IPAddress& i : hop.m_allowedIPAddressRanges) {
QJsonObject range;
range.insert("address", QJsonValue(i.address().toString()));
range.insert("range", QJsonValue((double)i.prefixLength()));
range.insert("isIpv6",
QJsonValue(i.type() == QAbstractSocket::IPv6Protocol));
jsAllowedIPAddesses.append(range);
};
json.insert("allowedIPAddressRanges", jsAllowedIPAddesses);
QJsonArray jsExcludedAddresses;
for (const auto& address : hop.m_excludedAddresses) {
jsExcludedAddresses.append(QJsonValue(address));
}
json.insert("excludedAddresses", jsExcludedAddresses);
QJsonArray splitTunnelApps;
for (const auto& uri : hop.m_vpnDisabledApps) {
splitTunnelApps.append(QJsonValue(uri));
}
json.insert("vpnDisabledApps", splitTunnelApps);
write(json);
}
void LocalSocketController::deactivate(Reason reason) {
logger.debug() << "Deactivating";
if (m_state != eReady) {
logger.debug() << "No disconnect, controller is not ready";
emit disconnected();
return;
}
if (reason == ReasonSwitching) {
logger.debug() << "No disconnect for quick server switching";
emit disconnected();
return;
}
QJsonObject json;
json.insert("type", "deactivate");
write(json);
}
void LocalSocketController::checkStatus() {
logger.debug() << "Check status";
if (m_state == eReady || m_state == eInitializing) {
Q_ASSERT(m_socket);
QJsonObject json;
json.insert("type", "status");
write(json);
}
}
void LocalSocketController::getBackendLogs(
std::function<void(const QString&)>&& a_callback) {
logger.debug() << "Backend logs";
if (m_logCallback) {
m_logCallback("");
m_logCallback = nullptr;
}
if (m_state != eReady) {
std::function<void(const QString&)> callback = a_callback;
callback("");
return;
}
m_logCallback = std::move(a_callback);
QJsonObject json;
json.insert("type", "logs");
write(json);
}
void LocalSocketController::cleanupBackendLogs() {
logger.debug() << "Cleanup logs";
if (m_logCallback) {
m_logCallback("");
m_logCallback = nullptr;
}
if (m_state != eReady) {
return;
}
QJsonObject json;
json.insert("type", "cleanlogs");
write(json);
}
void LocalSocketController::readData() {
logger.debug() << "Reading";
Q_ASSERT(m_socket);
Q_ASSERT(m_state == eInitializing || m_state == eReady);
QByteArray input = m_socket->readAll();
m_buffer.append(input);
while (true) {
int pos = m_buffer.indexOf("\n");
if (pos == -1) {
break;
}
QByteArray line = m_buffer.left(pos);
m_buffer.remove(0, pos + 1);
QByteArray command(line);
command = command.trimmed();
if (command.isEmpty()) {
continue;
}
parseCommand(command);
}
}
void LocalSocketController::parseCommand(const QByteArray& command) {
logger.debug() << "Parse command:" << command.left(20);
QJsonDocument json = QJsonDocument::fromJson(command);
if (!json.isObject()) {
logger.error() << "Invalid JSON - object expected";
return;
}
QJsonObject obj = json.object();
QJsonValue typeValue = obj.value("type");
if (!typeValue.isString()) {
logger.error() << "Invalid JSON - no type";
return;
}
QString type = typeValue.toString();
if (m_state == eInitializing && type == "status") {
m_state = eReady;
QJsonValue connected = obj.value("connected");
if (!connected.isBool()) {
logger.error() << "Invalid JSON for status - connected expected";
return;
}
QDateTime datetime;
if (connected.toBool()) {
QJsonValue date = obj.value("date");
if (!date.isString()) {
logger.error() << "Invalid JSON for status - date expected";
return;
}
datetime = QDateTime::fromString(date.toString());
if (!datetime.isValid()) {
logger.error() << "Invalid JSON for status - date is invalid";
return;
}
}
emit initialized(true, connected.toBool(), datetime);
return;
}
if (m_state != eReady) {
logger.error() << "Unexpected command";
return;
}
if (type == "status") {
QJsonValue serverIpv4Gateway = obj.value("serverIpv4Gateway");
if (!serverIpv4Gateway.isString()) {
logger.error() << "Unexpected serverIpv4Gateway value";
return;
}
QJsonValue deviceIpv4Address = obj.value("deviceIpv4Address");
if (!deviceIpv4Address.isString()) {
logger.error() << "Unexpected deviceIpv4Address value";
return;
}
QJsonValue txBytes = obj.value("txBytes");
if (!txBytes.isDouble()) {
logger.error() << "Unexpected txBytes value";
return;
}
QJsonValue rxBytes = obj.value("rxBytes");
if (!rxBytes.isDouble()) {
logger.error() << "Unexpected rxBytes value";
return;
}
emit statusUpdated(serverIpv4Gateway.toString(),
deviceIpv4Address.toString(), txBytes.toDouble(),
rxBytes.toDouble());
return;
}
if (type == "disconnected") {
emit disconnected();
return;
}
if (type == "connected") {
QJsonValue pubkey = obj.value("pubkey");
if (!pubkey.isString()) {
logger.error() << "Unexpected pubkey value";
return;
}
logger.debug() << "Handshake completed with:" << pubkey.toString();
emit connected(pubkey.toString());
return;
}
if (type == "backendFailure") {
MozillaVPN::instance()->errorHandle(ErrorHandler::ControllerError);
return;
}
if (type == "logs") {
// We don't care if we are not waiting for logs.
if (!m_logCallback) {
return;
}
QJsonValue logs = obj.value("logs");
m_logCallback(logs.isString() ? logs.toString().replace("|", "\n")
: QString());
m_logCallback = nullptr;
return;
}
logger.warning() << "Invalid command received:" << command;
}
void LocalSocketController::write(const QJsonObject& json) {
Q_ASSERT(m_socket);
m_socket->write(QJsonDocument(json).toJson(QJsonDocument::Compact));
m_socket->write("\n");
m_socket->flush();
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/AI/ITargetTrackingListener.hpp>
namespace RED4ext
{
namespace AI {
struct ScriptsTargetTrackingListenerWrapper : AI::ITargetTrackingListener
{
static constexpr const char* NAME = "AIScriptsTargetTrackingListenerWrapper";
static constexpr const char* ALIAS = NAME;
uint8_t unk48[0x58 - 0x48]; // 48
};
RED4EXT_ASSERT_SIZE(ScriptsTargetTrackingListenerWrapper, 0x58);
} // namespace AI
} // namespace RED4ext
|
// -----------------------------------------------------------------------------------------
// <copyright file="executor_test.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "blob_test_base.h"
#include "check_macros.h"
SUITE(Core)
{
TEST_FIXTURE(test_base, timeout)
{
azure::storage::cloud_blob_client client = test_config::instance().account().create_cloud_blob_client();
azure::storage::cloud_blob_container container = client.get_container_reference(U("this-container-does-not-exist"));
utility::string_t timeout;
azure::storage::operation_context context;
context.set_sending_request([&timeout] (web::http::http_request& request, azure::storage::operation_context context) mutable
{
std::map<utility::string_t, utility::string_t> query_parameters = web::http::uri::split_query(request.request_uri().query());
std::map<utility::string_t, utility::string_t>::iterator timeout_it = query_parameters.find(U("timeout"));
if (timeout_it != query_parameters.end())
{
timeout = timeout_it->second;
}
else
{
timeout.clear();
}
});
{
azure::storage::blob_request_options options;
container.exists(options, context);
CHECK(timeout.empty());
}
{
azure::storage::blob_request_options options;
options.set_server_timeout(std::chrono::seconds(20));
container.exists(options, context);
CHECK(!timeout.empty());
CHECK_UTF8_EQUAL(U("20"), timeout);
}
}
TEST_FIXTURE(test_base, operation_context)
{
auto client = test_config::instance().account().create_cloud_blob_client();
utility::string_t client_request_id;
utility::string_t service_request_id;
utility::string_t test_key;
auto start_time = utility::datetime::utc_now();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
azure::storage::operation_context context;
context.set_client_request_id(U("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"));
context.user_headers().add(U("x-ms-test-key"), U("test-value"));
context.set_sending_request([&client_request_id, &test_key] (web::http::http_request& request, azure::storage::operation_context context) mutable
{
client_request_id = request.headers().find(U("x-ms-client-request-id"))->second;
test_key = request.headers().find(U("x-ms-test-key"))->second;
});
context.set_response_received([&service_request_id] (web::http::http_request&, const web::http::http_response& response, azure::storage::operation_context context) mutable
{
service_request_id = response.headers().find(U("x-ms-request-id"))->second;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
});
auto container = client.get_container_reference(U("this-container-does-not-exist"));
container.exists(azure::storage::blob_request_options(), context);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
auto end_time = utility::datetime::utc_now();
CHECK_EQUAL(1U, context.request_results().size());
auto result = context.request_results().front();
CHECK(result.is_response_available());
CHECK_UTF8_EQUAL(U("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"), client_request_id);
CHECK_UTF8_EQUAL(service_request_id, result.service_request_id());
CHECK_EQUAL(web::http::status_codes::NotFound, result.http_status_code());
CHECK(start_time.to_interval() < result.start_time().to_interval());
CHECK(end_time.to_interval() > result.end_time().to_interval());
CHECK(result.end_time().to_interval() > result.start_time().to_interval());
}
TEST_FIXTURE(test_base, storage_uri)
{
azure::storage::storage_uri(U("http://www.microsoft.com/test1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com/test1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U(""));
azure::storage::storage_uri(U(""), U("http://www.microsoft.com/test1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1/example1"), U("http://www.microsoft.com/test1/example1"));
CHECK_THROW(azure::storage::storage_uri(U("")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U(""), U("")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com/test2")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com/test1/")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com/test")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://www.microsoft.com/test11")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1/example1"), U("http://www.microsoft.com/test1/example2")), std::invalid_argument);
azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://www.microsoft.com/test1?parameter=value1"));
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://www.microsoft.com/test1")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://www.microsoft.com/test1?parameter=value2")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://www.microsoft.com/test1?parameter=value")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://www.microsoft.com/test1?parameter=value11")), std::invalid_argument);
azure::storage::storage_uri(U("http://127.0.0.1:10000/account/test1"), U("http://127.0.0.1:10000/account-secondary/test1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://127.0.0.1:10000/account/test1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1/example1"), U("http://127.0.0.1:10000/account/test1/example1"));
azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://127.0.0.1:10000/account/test1?parameter=value1"));
azure::storage::storage_uri(U("http://127.0.0.1:10000/account"), U("http://127.0.0.1:10000"));
CHECK_THROW(azure::storage::storage_uri(U("http://127.0.0.1:10000/account-secondary/test1"), U("http://127.0.0.1:10000/account/test2")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1"), U("http://127.0.0.1:10000/account/test2")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1/example1"), U("http://127.0.0.1:10000/account/test2/example2")), std::invalid_argument);
CHECK_THROW(azure::storage::storage_uri(U("http://www.microsoft.com/test1?parameter=value1"), U("http://127.0.0.1:10000/account/test1?parameter=value2")), std::invalid_argument);
}
TEST_FIXTURE(test_base, storage_exception)
{
azure::storage::cloud_blob blob(azure::storage::storage_uri(U("http://www.nonexistenthost.com/test1")));
bool caught_storage_exception = false;
bool caught_http_exception = false;
try
{
blob.exists();
}
catch (const azure::storage::storage_exception& ex1)
{
caught_storage_exception = true;
try
{
std::rethrow_exception(ex1.inner_exception());
}
catch (web::http::http_exception&)
{
caught_http_exception = true;
}
}
CHECK_EQUAL(true, caught_storage_exception);
CHECK_EQUAL(true, caught_http_exception);
}
}
|
/*
* Copyright (c) 2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Ron Dreslinski
*/
/**
* @file
* Describes a ghb prefetcher.
*/
#ifndef __MEM_CACHE_PREFETCH_GHB_PREFETCHER_HH__
#define __MEM_CACHE_PREFETCH_GHB_PREFETCHER_HH__
#include "mem/cache/prefetch/base.hh"
#include "params/GHBPrefetcher.hh"
class GHBPrefetcher : public BasePrefetcher
{
protected:
static const int Max_Masters = 64;
Addr secondLastMissAddr[Max_Masters];
Addr lastMissAddr[Max_Masters];
public:
GHBPrefetcher(const Params *p)
: BasePrefetcher(p)
{
}
~GHBPrefetcher() {}
void calculatePrefetch(PacketPtr &pkt, std::list<Addr> &addresses,
std::list<Tick> &delays);
};
#endif // __MEM_CACHE_PREFETCH_GHB_PREFETCHER_HH__
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <ctgmath>
#include <ctgmath.hxx>
#include "test_macros.h"
#ifndef _LIBCPP_VERSION
#error _LIBCPP_VERSION not defined
#endif
int main(int, char**)
{
std::complex<double> cd;
((void)cd);
double x = std::sin(0);
((void)x);
return 0;
}
|
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference
when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/tasks
*/
#include "SaveCriticalTasksReport.h"
#include <visualization/Reporting/ReportType.h>
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <Project.h>
#include "RunExamples.h"
using namespace Aspose::Tasks::Visualization;
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace Miscellaneous {
RTTI_INFO_IMPL_HASH(1583441671u, ::Aspose::Tasks::Examples::CPP::Miscellaneous::SaveCriticalTasksReport, ThisTypeBaseTypesInfo);
void SaveCriticalTasksReport::Run()
{
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:SaveCriticalTasksReport
System::SharedPtr<Project> project1 = System::MakeObject<Project>(dataDir + u"Residential Construction.mpp");
project1->SaveReport(dataDir + u"CriticalTasks_out.pdf", Aspose::Tasks::Visualization::ReportType::CriticalTasks);
// ExEnd:SaveCriticalTasksReport
}
} // namespace Miscellaneous
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
|
/* <stig/notification/system_shutdown.cc>
Implements <stig/notification/system_shutdown.h>.
Copyright 2010-2014 Tagged
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 <stig/notification/system_shutdown.h>
using namespace Io;
using namespace Stig::Notification;
bool TSystemShutdown::Matches(const TSystemShutdown &that) const {
assert(this);
assert(&that);
return TNotification::Matches(that) && Ttl == that.Ttl;
}
void TSystemShutdown::Write(TBinaryOutputStream &strm) const {
assert(this);
assert(&strm);
TNotification::Write(strm);
strm << Ttl;
}
TSystemShutdown::TSystemShutdown(TBinaryInputStream &strm)
: TNotification(strm) {
assert(&strm);
strm >> Ttl;
}
|
// This file was generated using Parlex's cpp_generator
#include "FOR_COLLECTION.hpp"
#include "plange_grammar.hpp"
#include "parlex/detail/document.hpp"
#include "EXPRESSION.hpp"
#include "IC.hpp"
#include "IDENTIFIER.hpp"
#include "IMPLICIT_TYPE_DEREFERENCE.hpp"
#include "TYPE_DEREFERENCE.hpp"
plc::FOR_COLLECTION::declaration::field_1_t_1_t plc::FOR_COLLECTION::declaration::field_1_t_1_t::build(parlex::detail::node const * b, parlex::detail::document::walk & w) {
auto const & children = b->children;
auto v0 = parlex::detail::document::element<std::variant<
erased<TYPE_DEREFERENCE>,
erased<IMPLICIT_TYPE_DEREFERENCE>
>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[1], w);
return field_1_t_1_t(std::move(v0), std::move(v1));
}
plc::FOR_COLLECTION::declaration plc::FOR_COLLECTION::declaration::build(parlex::detail::node const * b, parlex::detail::document::walk & w) {
auto const & children = b->children;
auto v0 = parlex::detail::document::element<std::optional<field_1_t_1_t>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<erased<IDENTIFIER>>::build(&*children[1], w);
return declaration(std::move(v0), std::move(v1));
}
plc::FOR_COLLECTION plc::FOR_COLLECTION::build(parlex::detail::ast_node const & n) {
static auto const * b = state_machine().behavior;
parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() };
auto const & children = b->children;
auto v0 = parlex::detail::document::element<parlex::detail::document::text<literal_for_t>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[1], w);
auto v2 = parlex::detail::document::element<parlex::detail::document::text<literal_0x28_t>>::build(&*children[2], w);
auto v3 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[3], w);
auto v4 = parlex::detail::document::element<std::variant<
declaration,
erased<EXPRESSION>
>>::build(&*children[4], w);
auto v5 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[5], w);
auto v6 = parlex::detail::document::element<std::variant<
parlex::detail::document::text<literal_in_t>,
parlex::detail::document::text<literal_0xE20x880x88_t>
>>::build(&*children[6], w);
auto v7 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[7], w);
auto v8 = parlex::detail::document::element<erased<EXPRESSION>>::build(&*children[8], w);
auto v9 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[9], w);
auto v10 = parlex::detail::document::element<parlex::detail::document::text<literal_0x29_t>>::build(&*children[10], w);
auto v11 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[11], w);
auto v12 = parlex::detail::document::element<erased<EXPRESSION>>::build(&*children[12], w);
return FOR_COLLECTION(std::move(v0), std::move(v1), std::move(v2), std::move(v3), std::move(v4), std::move(v5), std::move(v6), std::move(v7), std::move(v8), std::move(v9), std::move(v10), std::move(v11), std::move(v12));
}
parlex::detail::state_machine const & plc::FOR_COLLECTION::state_machine() {
static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().FOR_COLLECTION));
return result;
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "outputStream.hpp"
#include "_stream.h"
#include "getset.h"
#include "directio.h"
#include "../interactivity/inc/ServiceLocator.hpp"
#pragma hdrstop
using namespace Microsoft::Console;
using Microsoft::Console::Interactivity::ServiceLocator;
WriteBuffer::WriteBuffer(_In_ Microsoft::Console::IIoProvider& io) :
_io{ io },
_ntstatus{ STATUS_INVALID_DEVICE_STATE }
{
}
// Routine Description:
// - Handles the print action from the state machine
// Arguments:
// - wch - The character to be printed.
// Return Value:
// - <none>
void WriteBuffer::Print(const wchar_t wch)
{
_DefaultCase(wch);
}
// Routine Description:
// - Handles the print action from the state machine
// Arguments:
// - string - The string to be printed.
// Return Value:
// - <none>
void WriteBuffer::PrintString(const std::wstring_view string)
{
_DefaultStringCase(string);
}
// Routine Description:
// - Handles the execute action from the state machine
// Arguments:
// - wch - The C0 control character to be executed.
// Return Value:
// - <none>
void WriteBuffer::Execute(const wchar_t wch)
{
_DefaultCase(wch);
}
// Routine Description:
// - Default text editing/printing handler for all characters that were not routed elsewhere by other state machine intercepts.
// Arguments:
// - wch - The character to be processed by our default text editing/printing mechanisms.
// Return Value:
// - <none>
void WriteBuffer::_DefaultCase(const wchar_t wch)
{
_DefaultStringCase({ &wch, 1 });
}
// Routine Description:
// - Default text editing/printing handler for all characters that were not routed elsewhere by other state machine intercepts.
// Arguments:
// - string - The string to be processed by our default text editing/printing mechanisms.
// Return Value:
// - <none>
void WriteBuffer::_DefaultStringCase(const std::wstring_view string)
{
size_t dwNumBytes = string.size() * sizeof(wchar_t);
_io.GetActiveOutputBuffer().GetTextBuffer().GetCursor().SetIsOn(true);
_ntstatus = WriteCharsLegacy(_io.GetActiveOutputBuffer(),
string.data(),
string.data(),
string.data(),
&dwNumBytes,
nullptr,
_io.GetActiveOutputBuffer().GetTextBuffer().GetCursor().GetPosition().X,
WC_LIMIT_BACKSPACE | WC_NONDESTRUCTIVE_TAB | WC_DELAY_EOL_WRAP,
nullptr);
}
ConhostInternalGetSet::ConhostInternalGetSet(_In_ IIoProvider& io) :
_io{ io }
{
}
// Routine Description:
// - Connects the GetConsoleScreenBufferInfoEx API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - screenBufferInfo - Structure to hold screen buffer information like the public API call.
// Return Value:
// - true if successful (see DoSrvGetConsoleScreenBufferInfo). false otherwise.
bool ConhostInternalGetSet::GetConsoleScreenBufferInfoEx(CONSOLE_SCREEN_BUFFER_INFOEX& screenBufferInfo) const
{
ServiceLocator::LocateGlobals().api.GetConsoleScreenBufferInfoExImpl(_io.GetActiveOutputBuffer(), screenBufferInfo);
return true;
}
// Routine Description:
// - Connects the SetConsoleScreenBufferInfoEx API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - screenBufferInfo - Structure containing screen buffer information like the public API call.
// Return Value:
// - true if successful (see DoSrvSetConsoleScreenBufferInfo). false otherwise.
bool ConhostInternalGetSet::SetConsoleScreenBufferInfoEx(const CONSOLE_SCREEN_BUFFER_INFOEX& screenBufferInfo)
{
return SUCCEEDED(ServiceLocator::LocateGlobals().api.SetConsoleScreenBufferInfoExImpl(_io.GetActiveOutputBuffer(), screenBufferInfo));
}
// Routine Description:
// - Connects the SetConsoleCursorPosition API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - position - new cursor position to set like the public API call.
// Return Value:
// - true if successful (see DoSrvSetConsoleCursorPosition). false otherwise.
bool ConhostInternalGetSet::SetConsoleCursorPosition(const COORD position)
{
return SUCCEEDED(ServiceLocator::LocateGlobals().api.SetConsoleCursorPositionImpl(_io.GetActiveOutputBuffer(), position));
}
// Routine Description:
// - Connects the GetConsoleCursorInfo API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - cursorInfo - Structure to receive console cursor rendering info
// Return Value:
// - true if successful (see DoSrvGetConsoleCursorInfo). false otherwise.
bool ConhostInternalGetSet::GetConsoleCursorInfo(CONSOLE_CURSOR_INFO& cursorInfo) const
{
bool visible;
DWORD size;
ServiceLocator::LocateGlobals().api.GetConsoleCursorInfoImpl(_io.GetActiveOutputBuffer(), size, visible);
cursorInfo.bVisible = visible;
cursorInfo.dwSize = size;
return true;
}
// Routine Description:
// - Connects the SetConsoleCursorInfo API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - cursorInfo - Updated size/visibility information to modify the cursor rendering behavior.
// Return Value:
// - true if successful (see DoSrvSetConsoleCursorInfo). false otherwise.
bool ConhostInternalGetSet::SetConsoleCursorInfo(const CONSOLE_CURSOR_INFO& cursorInfo)
{
const bool visible = !!cursorInfo.bVisible;
return SUCCEEDED(ServiceLocator::LocateGlobals().api.SetConsoleCursorInfoImpl(_io.GetActiveOutputBuffer(), cursorInfo.dwSize, visible));
}
// Routine Description:
// - Connects the SetConsoleTextAttribute API call directly into our Driver Message servicing call inside Conhost.exe
// Sets BOTH the FG and the BG component of the attributes.
// Arguments:
// - attr - new color/graphical attributes to apply as default within the console text buffer
// Return Value:
// - true if successful (see DoSrvSetConsoleTextAttribute). false otherwise.
bool ConhostInternalGetSet::SetConsoleTextAttribute(const WORD attr)
{
return SUCCEEDED(ServiceLocator::LocateGlobals().api.SetConsoleTextAttributeImpl(_io.GetActiveOutputBuffer(), attr));
}
// Routine Description:
// - Connects the PrivateSetDefaultAttributes API call directly into our Driver Message servicing call inside Conhost.exe
// Sets the FG and/or BG to the Default attributes values.
// Arguments:
// - foreground - Set the foreground to the default attributes
// - background - Set the background to the default attributes
// Return Value:
// - true if successful (see DoSrvPrivateSetDefaultAttributes). false otherwise.
bool ConhostInternalGetSet::PrivateSetDefaultAttributes(const bool foreground,
const bool background)
{
DoSrvPrivateSetDefaultAttributes(_io.GetActiveOutputBuffer(), foreground, background);
return true;
}
// Routine Description:
// - Connects the PrivateSetLegacyAttributes API call directly into our Driver Message servicing call inside Conhost.exe
// Sets only the components of the attributes requested with the foreground, background, and meta flags.
// Arguments:
// - attr - new color/graphical attributes to apply as default within the console text buffer
// - foreground - The new attributes contain an update to the foreground attributes
// - background - The new attributes contain an update to the background attributes
// - meta - The new attributes contain an update to the meta attributes
// Return Value:
// - true if successful (see DoSrvVtSetLegacyAttributes). false otherwise.
bool ConhostInternalGetSet::PrivateSetLegacyAttributes(const WORD attr,
const bool foreground,
const bool background,
const bool meta)
{
DoSrvPrivateSetLegacyAttributes(_io.GetActiveOutputBuffer(), attr, foreground, background, meta);
return true;
}
// Routine Description:
// - Sets the current attributes of the screen buffer to use the color table entry specified by
// the xtermTableEntry. Sets either the FG or the BG component of the attributes.
// Arguments:
// - xtermTableEntry - The entry of the xterm table to use.
// - isForeground - Whether or not the color applies to the foreground.
// Return Value:
// - true if successful (see DoSrvPrivateSetConsoleXtermTextAttribute). false otherwise.
bool ConhostInternalGetSet::SetConsoleXtermTextAttribute(const int xtermTableEntry, const bool isForeground)
{
DoSrvPrivateSetConsoleXtermTextAttribute(_io.GetActiveOutputBuffer(), xtermTableEntry, isForeground);
return true;
}
// Routine Description:
// - Sets the current attributes of the screen buffer to use the given rgb color.
// Sets either the FG or the BG component of the attributes.
// Arguments:
// - rgbColor - The rgb color to use.
// - isForeground - Whether or not the color applies to the foreground.
// Return Value:
// - true if successful (see DoSrvPrivateSetConsoleRGBTextAttribute). false otherwise.
bool ConhostInternalGetSet::SetConsoleRGBTextAttribute(const COLORREF rgbColor, const bool isForeground)
{
DoSrvPrivateSetConsoleRGBTextAttribute(_io.GetActiveOutputBuffer(), rgbColor, isForeground);
return true;
}
bool ConhostInternalGetSet::PrivateBoldText(const bool bolded)
{
DoSrvPrivateBoldText(_io.GetActiveOutputBuffer(), bolded);
return true;
}
// Method Description:
// - Retrieves the currently active ExtendedAttributes. See also
// DoSrvPrivateGetExtendedTextAttributes
// Arguments:
// - attrs: Recieves the ExtendedAttributes value.
// Return Value:
// - true if successful (see DoSrvPrivateGetExtendedTextAttributes). false otherwise.
bool ConhostInternalGetSet::PrivateGetExtendedTextAttributes(ExtendedAttributes& attrs)
{
attrs = DoSrvPrivateGetExtendedTextAttributes(_io.GetActiveOutputBuffer());
return true;
}
// Method Description:
// - Sets the active ExtendedAttributes of the active screen buffer. Text
// written to this buffer will be written with these attributes.
// Arguments:
// - extendedAttrs: The new ExtendedAttributes to use
// Return Value:
// - true if successful (see DoSrvPrivateSetExtendedTextAttributes). false otherwise.
bool ConhostInternalGetSet::PrivateSetExtendedTextAttributes(const ExtendedAttributes attrs)
{
DoSrvPrivateSetExtendedTextAttributes(_io.GetActiveOutputBuffer(), attrs);
return true;
}
// Method Description:
// - Retrieves the current TextAttribute of the active screen buffer.
// Arguments:
// - attrs: Receives the TextAttribute value.
// Return Value:
// - true if successful. false otherwise.
bool ConhostInternalGetSet::PrivateGetTextAttributes(TextAttribute& attrs) const
{
attrs = _io.GetActiveOutputBuffer().GetAttributes();
return true;
}
// Method Description:
// - Sets the current TextAttribute of the active screen buffer. Text
// written to this buffer will be written with these attributes.
// Arguments:
// - attrs: The new TextAttribute to use
// Return Value:
// - true if successful. false otherwise.
bool ConhostInternalGetSet::PrivateSetTextAttributes(const TextAttribute& attrs)
{
_io.GetActiveOutputBuffer().SetAttributes(attrs);
return true;
}
// Routine Description:
// - Connects the WriteConsoleInput API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - events - the input events to be copied into the head of the input
// buffer for the underlying attached process
// - eventsWritten - on output, the number of events written
// Return Value:
// - true if successful (see DoSrvWriteConsoleInput). false otherwise.
bool ConhostInternalGetSet::PrivateWriteConsoleInputW(std::deque<std::unique_ptr<IInputEvent>>& events,
size_t& eventsWritten)
{
eventsWritten = 0;
return SUCCEEDED(DoSrvPrivateWriteConsoleInputW(_io.GetActiveInputBuffer(),
events,
eventsWritten,
true)); // append
}
// Routine Description:
// - Connects the SetConsoleWindowInfo API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - absolute - Should the window be moved to an absolute position? If false, the movement is relative to the current pos.
// - window - Info about how to move the viewport
// Return Value:
// - true if successful (see DoSrvSetConsoleWindowInfo). false otherwise.
bool ConhostInternalGetSet::SetConsoleWindowInfo(const bool absolute, const SMALL_RECT& window)
{
return SUCCEEDED(ServiceLocator::LocateGlobals().api.SetConsoleWindowInfoImpl(_io.GetActiveOutputBuffer(), absolute, window));
}
// Routine Description:
// - Connects the PrivateSetCursorKeysMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateSetCursorKeysMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - fApplicationMode - set to true to enable Application Mode Input, false for Normal Mode.
// Return Value:
// - true if successful (see DoSrvPrivateSetCursorKeysMode). false otherwise.
bool ConhostInternalGetSet::PrivateSetCursorKeysMode(const bool fApplicationMode)
{
return NT_SUCCESS(DoSrvPrivateSetCursorKeysMode(fApplicationMode));
}
// Routine Description:
// - Connects the PrivateSetKeypadMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateSetKeypadMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - fApplicationMode - set to true to enable Application Mode Input, false for Numeric Mode.
// Return Value:
// - true if successful (see DoSrvPrivateSetKeypadMode). false otherwise.
bool ConhostInternalGetSet::PrivateSetKeypadMode(const bool fApplicationMode)
{
return NT_SUCCESS(DoSrvPrivateSetKeypadMode(fApplicationMode));
}
// Routine Description:
// - Connects the PrivateShowCursor call directly into our Driver Message servicing call inside Conhost.exe
// PrivateShowCursor is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - show - set to true to make the cursor visible, false to hide.
// Return Value:
// - true if successful (see DoSrvPrivateShowCursor). false otherwise.
bool ConhostInternalGetSet::PrivateShowCursor(const bool show) noexcept
{
DoSrvPrivateShowCursor(_io.GetActiveOutputBuffer(), show);
return true;
}
// Routine Description:
// - Connects the PrivateAllowCursorBlinking call directly into our Driver Message servicing call inside Conhost.exe
// PrivateAllowCursorBlinking is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - fEnable - set to true to enable blinking, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateAllowCursorBlinking). false otherwise.
bool ConhostInternalGetSet::PrivateAllowCursorBlinking(const bool fEnable)
{
DoSrvPrivateAllowCursorBlinking(_io.GetActiveOutputBuffer(), fEnable);
return true;
}
// Routine Description:
// - Connects the PrivateSetScrollingRegion call directly into our Driver Message servicing call inside Conhost.exe
// PrivateSetScrollingRegion is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - scrollMargins - The bounds of the region to be the scrolling region of the viewport.
// Return Value:
// - true if successful (see DoSrvPrivateSetScrollingRegion). false otherwise.
bool ConhostInternalGetSet::PrivateSetScrollingRegion(const SMALL_RECT& scrollMargins)
{
return NT_SUCCESS(DoSrvPrivateSetScrollingRegion(_io.GetActiveOutputBuffer(), scrollMargins));
}
// Routine Description:
// - Connects the PrivateReverseLineFeed call directly into our Driver Message servicing call inside Conhost.exe
// PrivateReverseLineFeed is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Return Value:
// - true if successful (see DoSrvPrivateReverseLineFeed). false otherwise.
bool ConhostInternalGetSet::PrivateReverseLineFeed()
{
return NT_SUCCESS(DoSrvPrivateReverseLineFeed(_io.GetActiveOutputBuffer()));
}
// Routine Description:
// - Connects the MoveCursorVertically call directly into our Driver Message servicing call inside Conhost.exe
// MoveCursorVertically is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Return Value:
// - true if successful (see DoSrvMoveCursorVertically). false otherwise.
bool ConhostInternalGetSet::MoveCursorVertically(const ptrdiff_t lines)
{
SHORT l;
if (FAILED(PtrdiffTToShort(lines, &l)))
{
return false;
}
return SUCCEEDED(DoSrvMoveCursorVertically(_io.GetActiveOutputBuffer(), l));
}
// Routine Description:
// - Connects the SetConsoleTitleW API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - title - The null-terminated string to set as the window title
// Return Value:
// - true if successful (see DoSrvSetConsoleTitle). false otherwise.
bool ConhostInternalGetSet::SetConsoleTitleW(std::wstring_view title)
{
return SUCCEEDED(DoSrvSetConsoleTitleW(title));
}
// Routine Description:
// - Connects the PrivateUseAlternateScreenBuffer call directly into our Driver Message servicing call inside Conhost.exe
// PrivateUseAlternateScreenBuffer is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Return Value:
// - true if successful (see DoSrvPrivateUseAlternateScreenBuffer). false otherwise.
bool ConhostInternalGetSet::PrivateUseAlternateScreenBuffer()
{
return NT_SUCCESS(DoSrvPrivateUseAlternateScreenBuffer(_io.GetActiveOutputBuffer()));
}
// Routine Description:
// - Connects the PrivateUseMainScreenBuffer call directly into our Driver Message servicing call inside Conhost.exe
// PrivateUseMainScreenBuffer is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Return Value:
// - true if successful (see DoSrvPrivateUseMainScreenBuffer). false otherwise.
bool ConhostInternalGetSet::PrivateUseMainScreenBuffer()
{
DoSrvPrivateUseMainScreenBuffer(_io.GetActiveOutputBuffer());
return true;
}
// - Connects the PrivateHorizontalTabSet call directly into our Driver Message servicing call inside Conhost.exe
// PrivateHorizontalTabSet is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// <none>
// Return Value:
// - true if successful (see PrivateHorizontalTabSet). false otherwise.
bool ConhostInternalGetSet::PrivateHorizontalTabSet()
{
return NT_SUCCESS(DoSrvPrivateHorizontalTabSet());
}
// Routine Description:
// - Connects the PrivateForwardTab call directly into our Driver Message servicing call inside Conhost.exe
// PrivateForwardTab is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - sNumTabs - the number of tabs to execute
// Return Value:
// - true if successful (see PrivateForwardTab). false otherwise.
bool ConhostInternalGetSet::PrivateForwardTab(const size_t numTabs)
{
SHORT tabs;
if (FAILED(SizeTToShort(numTabs, &tabs)))
{
return false;
}
return NT_SUCCESS(DoSrvPrivateForwardTab(tabs));
}
// Routine Description:
// - Connects the PrivateBackwardsTab call directly into our Driver Message servicing call inside Conhost.exe
// PrivateBackwardsTab is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - numTabs - the number of tabs to execute
// Return Value:
// - true if successful (see PrivateBackwardsTab). false otherwise.
bool ConhostInternalGetSet::PrivateBackwardsTab(const size_t numTabs)
{
SHORT tabs;
if (FAILED(SizeTToShort(numTabs, &tabs)))
{
return false;
}
return NT_SUCCESS(DoSrvPrivateBackwardsTab(tabs));
}
// Routine Description:
// - Connects the PrivateTabClear call directly into our Driver Message servicing call inside Conhost.exe
// PrivateTabClear is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - clearAll - set to true to enable blinking, false to disable
// Return Value:
// - true if successful (see PrivateTabClear). false otherwise.
bool ConhostInternalGetSet::PrivateTabClear(const bool clearAll)
{
DoSrvPrivateTabClear(clearAll);
return true;
}
// Routine Description:
// - Connects the PrivateSetDefaultTabStops call directly into the private api point
// Return Value:
// - true
bool ConhostInternalGetSet::PrivateSetDefaultTabStops()
{
DoSrvPrivateSetDefaultTabStops();
return true;
}
// Routine Description:
// - Connects the PrivateEnableVT200MouseMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableVT200MouseMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable vt200 mouse mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableVT200MouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableVT200MouseMode(const bool enabled)
{
DoSrvPrivateEnableVT200MouseMode(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEnableUTF8ExtendedMouseMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableUTF8ExtendedMouseMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable utf8 extended mouse mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableUTF8ExtendedMouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableUTF8ExtendedMouseMode(const bool enabled)
{
DoSrvPrivateEnableUTF8ExtendedMouseMode(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEnableSGRExtendedMouseMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableSGRExtendedMouseMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable SGR extended mouse mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableSGRExtendedMouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableSGRExtendedMouseMode(const bool enabled)
{
DoSrvPrivateEnableSGRExtendedMouseMode(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEnableButtonEventMouseMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableButtonEventMouseMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable button-event mouse mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableButtonEventMouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableButtonEventMouseMode(const bool enabled)
{
DoSrvPrivateEnableButtonEventMouseMode(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEnableAnyEventMouseMode call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableAnyEventMouseMode is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable any-event mouse mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableAnyEventMouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableAnyEventMouseMode(const bool enabled)
{
DoSrvPrivateEnableAnyEventMouseMode(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEnableAlternateScroll call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEnableAlternateScroll is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on out public API surface.
// Arguments:
// - enabled - set to true to enable alternate scroll mode, false to disable
// Return Value:
// - true if successful (see DoSrvPrivateEnableAnyEventMouseMode). false otherwise.
bool ConhostInternalGetSet::PrivateEnableAlternateScroll(const bool enabled)
{
DoSrvPrivateEnableAlternateScroll(enabled);
return true;
}
// Routine Description:
// - Connects the PrivateEraseAll call directly into our Driver Message servicing call inside Conhost.exe
// PrivateEraseAll is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on our public API surface.
// Arguments:
// <none>
// Return Value:
// - true if successful (see DoSrvPrivateEraseAll). false otherwise.
bool ConhostInternalGetSet::PrivateEraseAll()
{
return NT_SUCCESS(DoSrvPrivateEraseAll(_io.GetActiveOutputBuffer()));
}
// Routine Description:
// - Connects the SetCursorStyle call directly into our Driver Message servicing call inside Conhost.exe
// SetCursorStyle is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on our public API surface.
// Arguments:
// - style: The style of cursor to change the cursor to.
// Return Value:
// - true if successful (see DoSrvSetCursorStyle). false otherwise.
bool ConhostInternalGetSet::SetCursorStyle(const CursorType style)
{
DoSrvSetCursorStyle(_io.GetActiveOutputBuffer(), style);
return true;
}
// Routine Description:
// - Retrieves the default color attributes information for the active screen buffer.
// - This function is used to optimize SGR calls in lieu of calling GetConsoleScreenBufferInfoEx.
// Arguments:
// - pwAttributes - Pointer to space to receive color attributes data
// Return Value:
// - true if successful. false otherwise.
bool ConhostInternalGetSet::PrivateGetConsoleScreenBufferAttributes(WORD& attributes)
{
return NT_SUCCESS(DoSrvPrivateGetConsoleScreenBufferAttributes(_io.GetActiveOutputBuffer(), attributes));
}
// Routine Description:
// - Connects the PrivatePrependConsoleInput API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - events - the input events to be copied into the head of the input
// buffer for the underlying attached process
// - eventsWritten - on output, the number of events written
// Return Value:
// - true if successful (see DoSrvPrivatePrependConsoleInput). false otherwise.
bool ConhostInternalGetSet::PrivatePrependConsoleInput(std::deque<std::unique_ptr<IInputEvent>>& events,
size_t& eventsWritten)
{
return SUCCEEDED(DoSrvPrivatePrependConsoleInput(_io.GetActiveInputBuffer(),
events,
eventsWritten));
}
// Routine Description:
// - Connects the PrivatePrependConsoleInput API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - <none>
// Return Value:
// - true if successful (see DoSrvPrivateRefreshWindow). false otherwise.
bool ConhostInternalGetSet::PrivateRefreshWindow()
{
DoSrvPrivateRefreshWindow(_io.GetActiveOutputBuffer());
return true;
}
// Routine Description:
// - Connects the PrivateWriteConsoleControlInput API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - key - a KeyEvent representing a special type of keypress, typically Ctrl-C
// Return Value:
// - true if successful (see DoSrvPrivateWriteConsoleControlInput). false otherwise.
bool ConhostInternalGetSet::PrivateWriteConsoleControlInput(const KeyEvent key)
{
return SUCCEEDED(DoSrvPrivateWriteConsoleControlInput(_io.GetActiveInputBuffer(),
key));
}
// Routine Description:
// - Connects the GetConsoleOutputCP API call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - codepage - recieves the outputCP of the console.
// Return Value:
// - true if successful (see DoSrvPrivateWriteConsoleControlInput). false otherwise.
bool ConhostInternalGetSet::GetConsoleOutputCP(unsigned int& codepage)
{
DoSrvGetConsoleOutputCodePage(codepage);
return true;
}
// Routine Description:
// - Connects the PrivateSuppressResizeRepaint API call directly into our Driver
// Message servicing call inside Conhost.exe
// Arguments:
// - <none>
// Return Value:
// - true if successful (see DoSrvPrivateSuppressResizeRepaint). false otherwise.
bool ConhostInternalGetSet::PrivateSuppressResizeRepaint()
{
return SUCCEEDED(DoSrvPrivateSuppressResizeRepaint());
}
// Routine Description:
// - Connects the SetCursorStyle call directly into our Driver Message servicing call inside Conhost.exe
// SetCursorStyle is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on our public API surface.
// Arguments:
// - cursorColor: The color to change the cursor to. INVALID_COLOR will revert
// it to the legacy inverting behavior.
// Return Value:
// - true if successful (see DoSrvSetCursorStyle). false otherwise.
bool ConhostInternalGetSet::SetCursorColor(const COLORREF cursorColor)
{
DoSrvSetCursorColor(_io.GetActiveOutputBuffer(), cursorColor);
return true;
}
// Routine Description:
// - Connects the IsConsolePty call directly into our Driver Message servicing call inside Conhost.exe
// Arguments:
// - isPty: recieves the bool indicating whether or not we're in pty mode.
// Return Value:
// - true if successful (see DoSrvIsConsolePty). false otherwise.
bool ConhostInternalGetSet::IsConsolePty(bool& isPty) const
{
DoSrvIsConsolePty(isPty);
return true;
}
bool ConhostInternalGetSet::DeleteLines(const size_t count)
{
DoSrvPrivateDeleteLines(count);
return true;
}
bool ConhostInternalGetSet::InsertLines(const size_t count)
{
DoSrvPrivateInsertLines(count);
return true;
}
// Method Description:
// - Connects the MoveToBottom call directly into our Driver Message servicing
// call inside Conhost.exe
// Arguments:
// <none>
// Return Value:
// - true if successful (see DoSrvPrivateMoveToBottom). false otherwise.
bool ConhostInternalGetSet::MoveToBottom() const
{
DoSrvPrivateMoveToBottom(_io.GetActiveOutputBuffer());
return true;
}
// Method Description:
// - Connects the PrivateSetColorTableEntry call directly into our Driver Message servicing
// call inside Conhost.exe
// Arguments:
// - index: the index in the table to change.
// - value: the new RGB value to use for that index in the color table.
// Return Value:
// - true if successful (see DoSrvPrivateSetColorTableEntry). false otherwise.
bool ConhostInternalGetSet::PrivateSetColorTableEntry(const short index, const COLORREF value) const noexcept
{
return SUCCEEDED(DoSrvPrivateSetColorTableEntry(index, value));
}
// Method Description:
// - Connects the PrivateSetDefaultForeground call directly into our Driver Message servicing
// call inside Conhost.exe
// Arguments:
// - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR.
// Return Value:
// - true if successful (see DoSrvPrivateSetDefaultForegroundColor). false otherwise.
bool ConhostInternalGetSet::PrivateSetDefaultForeground(const COLORREF value) const noexcept
{
return SUCCEEDED(DoSrvPrivateSetDefaultForegroundColor(value));
}
// Method Description:
// - Connects the PrivateSetDefaultBackground call directly into our Driver Message servicing
// call inside Conhost.exe
// Arguments:
// - value: the new RGB value to use, as a COLORREF, format 0x00BBGGRR.
// Return Value:
// - true if successful (see DoSrvPrivateSetDefaultBackgroundColor). false otherwise.
bool ConhostInternalGetSet::PrivateSetDefaultBackground(const COLORREF value) const noexcept
{
return SUCCEEDED(DoSrvPrivateSetDefaultBackgroundColor(value));
}
// Routine Description:
// - Connects the PrivateFillRegion call directly into our Driver Message servicing
// call inside Conhost.exe
// PrivateFillRegion is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on our public API surface.
// Arguments:
// - screenInfo - Reference to screen buffer info.
// - startPosition - The position to begin filling at.
// - fillLength - The number of characters to fill.
// - fillChar - Character to fill the target region with.
// - standardFillAttrs - If true, fill with the standard erase attributes.
// If false, fill with the default attributes.
// Return value:
// - true if successful (see DoSrvPrivateScrollRegion). false otherwise.
bool ConhostInternalGetSet::PrivateFillRegion(const COORD startPosition,
const size_t fillLength,
const wchar_t fillChar,
const bool standardFillAttrs) noexcept
{
return SUCCEEDED(DoSrvPrivateFillRegion(_io.GetActiveOutputBuffer(),
startPosition,
fillLength,
fillChar,
standardFillAttrs));
}
// Routine Description:
// - Connects the PrivateScrollRegion call directly into our Driver Message servicing
// call inside Conhost.exe
// PrivateScrollRegion is an internal-only "API" call that the vt commands can execute,
// but it is not represented as a function call on our public API surface.
// Arguments:
// - scrollRect - Region to copy/move (source and size).
// - clipRect - Optional clip region to contain buffer change effects.
// - destinationOrigin - Upper left corner of target region.
// - standardFillAttrs - If true, fill with the standard erase attributes.
// If false, fill with the default attributes.
// Return value:
// - true if successful (see DoSrvPrivateScrollRegion). false otherwise.
bool ConhostInternalGetSet::PrivateScrollRegion(const SMALL_RECT scrollRect,
const std::optional<SMALL_RECT> clipRect,
const COORD destinationOrigin,
const bool standardFillAttrs) noexcept
{
return SUCCEEDED(DoSrvPrivateScrollRegion(_io.GetActiveOutputBuffer(),
scrollRect,
clipRect,
destinationOrigin,
standardFillAttrs));
}
|
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <openspace/engine/configuration.h>
#include <openspace/documentation/documentation.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/interaction/joystickinputstate.h>
#include <openspace/util/keys.h>
#include <ghoul/ghoul.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/cmdparser/commandlineparser.h>
#include <ghoul/cmdparser/singlecommand.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/consolelog.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/logging/visualstudiooutputlog.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/misc/assert.h>
#include <ghoul/misc/boolean.h>
#include <sgct.h>
#include <chrono>
#include <ctime>
#include <stb_image.h>
#ifdef WIN32
#include <openspace/openspace.h>
#include <ghoul/misc/stacktrace.h>
#include <ghoul/fmt.h>
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#include <Windows.h>
#endif // WIN32
#ifdef OPENVR_SUPPORT
#include <SGCTOpenVR.h>
#endif // OPENVR_SUPPORT
#ifdef OPENSPACE_HAS_SPOUT
#include "SpoutLibrary.h"
#endif // OPENSPACE_HAS_SPOUT
#ifdef OPENSPACE_HAS_VTUNE
#include <ittnotify.h>
// If this is set to 'true', it will disable all frame markers in this file and expect
// you to place them in the code you actually want to inspect
constexpr const bool EnableDetailedVtune = false;
#endif // OPENSPACE_HAS_VTUNE
#ifdef OPENSPACE_HAS_NVTOOLS
#include "nvToolsExt.h"
#endif // OPENSPACE_HAS_NVTOOLS
namespace {
constexpr const char* _loggerCat = "main";
constexpr const char* SpoutTag = "Spout";
constexpr const char* OpenVRTag = "OpenVR";
sgct::Engine* SgctEngine;
sgct::SharedVector<char> _synchronizationBuffer;
#ifdef OPENVR_SUPPORT
sgct::SGCTWindow* FirstOpenVRWindow = nullptr;
#endif
#ifdef OPENSPACE_HAS_VTUNE
struct {
__itt_domain* init;
__itt_domain* preSync;
__itt_domain* postSyncPreDraw;
__itt_domain* render;
__itt_domain* draw2D;
__itt_domain* postDraw;
__itt_domain* keyboard;
__itt_domain* mouseButton;
__itt_domain* mousePos;
__itt_domain* mouseScroll;
__itt_domain* character;
__itt_domain* encode;
__itt_domain* decode;
} _vTune;
#endif // OPENSPACE_HAS_VTUNE
//
// SPOUT-support
//
#ifdef OPENSPACE_HAS_SPOUT
/**
* This struct stores all information about a single render window. Depending on the
* frame setup, each window can be mono or stereo, the information of which is stored in
* the \c leftOrMain and \c right members respectively.
*/
struct SpoutWindow {
struct SpoutData {
SPOUTHANDLE handle = nullptr;
bool initialized = false;
};
/// The left framebuffer (or main, if there is no stereo rendering)
SpoutData leftOrMain;
/// The right framebuffer
SpoutData right;
/// The window ID of this windows
size_t windowId = size_t(-1);
};
/// The list of all windows with spout senders
std::vector<SpoutWindow> SpoutWindows;
#endif // OPENSPACE_HAS_SPOUT
//
// MiniDump generation
//
#ifdef WIN32
LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) {
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
LFATAL("Printing Stack Trace that lead to the crash:");
std::vector<std::string> stackTrace = ghoul::stackTrace();
for (const std::string& s : stackTrace) {
LINFO(s);
}
std::string dumpFile = fmt::format(
"OpenSpace_{}_{}_{}-{}-{}-{}-{}-{}-{}--{}--{}.dmp",
openspace::OPENSPACE_VERSION_MAJOR,
openspace::OPENSPACE_VERSION_MINOR,
openspace::OPENSPACE_VERSION_PATCH,
stLocalTime.wYear,
stLocalTime.wMonth,
stLocalTime.wDay,
stLocalTime.wHour,
stLocalTime.wMinute,
stLocalTime.wSecond,
GetCurrentProcessId(),
GetCurrentThreadId()
);
LINFO(fmt::format("Creating dump file: {}", dumpFile));
HANDLE hDumpFile = CreateFileA(
dumpFile.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,
nullptr,
CREATE_ALWAYS,
0,
nullptr
);
MINIDUMP_EXCEPTION_INFORMATION exceptionParameter;
exceptionParameter.ThreadId = GetCurrentThreadId();
exceptionParameter.ExceptionPointers = exceptionPointers;
exceptionParameter.ClientPointers = TRUE;
BOOL success = MiniDumpWriteDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hDumpFile,
MiniDumpWithDataSegs,
&exceptionParameter,
nullptr,
nullptr
);
CloseHandle(hDumpFile);
if (success) {
LINFO("Created successfully");
}
else {
LERROR("Dumpfile created unsuccessfully");
}
return EXCEPTION_EXECUTE_HANDLER;
}
#endif // WIN32
//
// Detect OpenGL version
//
std::pair<int, int> supportedOpenGLVersion() {
// Just create a window in order to retrieve the available OpenGL version before we
// create the real window
glfwInit();
// On OS X we need to explicitly set the version and specify that we are using CORE
// profile to be able to use glGetIntegerv(GL_MAJOR_VERSION, &major) and
// glGetIntegerv(GL_MINOR_VERSION, &minor) explicitly setting to OGL 3.3 CORE works
// since all Mac's now support at least 3.3
#ifdef __APPLE__
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
// By creating an offscreen window, the user will not know that we created this window
GLFWwindow* offscreen = glfwCreateWindow(128, 128, "", nullptr, nullptr);
glfwMakeContextCurrent(offscreen);
// Get the OpenGL version
int major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
// And get rid of the window again
glfwDestroyWindow(offscreen);
glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
return { major, minor };
}
//
// Init function
//
void mainInitFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.init, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainInitFunc(begin)");
LDEBUG("Initializing OpenSpace Engine started");
openspace::global::openSpaceEngine.initialize();
LDEBUG("Initializing OpenSpace Engine finished");
{
std::string path = absPath("${DATA}/openspace-icon.png");
int x;
int y;
int n;
unsigned char* data = stbi_load(path.c_str(), &x, &y, &n, 0);
GLFWimage icons[1];
icons[0].pixels = data;
icons[0].width = x;
icons[0].height = y;
const size_t nWindows = SgctEngine->getNumberOfWindows();
for (size_t i = 0; i < nWindows; ++i) {
const sgct::SGCTWindow* windowPtr = SgctEngine->getWindowPtr(i);
glfwSetWindowIcon(windowPtr->getWindowHandle(), 1, icons);
}
stbi_image_free(icons[0].pixels);
}
LDEBUG("Initializing OpenGL in OpenSpace Engine started");
openspace::global::openSpaceEngine.initializeGL();
LDEBUG("Initializing OpenGL in OpenSpace Engine finished");
// Find if we have at least one OpenVR window
// Save reference to first OpenVR window, which is the one we will copy to the HMD.
for (size_t i = 0; i < SgctEngine->getNumberOfWindows(); ++i) {
if (SgctEngine->getWindowPtr(i)->checkIfTagExists(OpenVRTag)) {
#ifdef OPENVR_SUPPORT
FirstOpenVRWindow = SgctEngine->getWindowPtr(i);
// If we have an OpenVRWindow, initialize OpenVR.
sgct::SGCTOpenVR::initialize(
SgctEngine->getNearClippingPlane(), SgctEngine->getFarClippingPlane()
);
#else
LWARNING("OpenVR was requested, but program was compiled without VR support");
#endif
break;
}
}
const size_t nWindows = SgctEngine->getNumberOfWindows();
for (size_t i = 0; i < nWindows; ++i) {
const sgct::SGCTWindow* windowPtr = SgctEngine->getWindowPtr(i);
if (!windowPtr->checkIfTagExists(SpoutTag)) {
continue;
}
#ifdef OPENSPACE_HAS_SPOUT
SpoutWindow w;
w.windowId = i;
const sgct::SGCTWindow::StereoMode sm = windowPtr->getStereoMode();
const bool hasStereo = (sm != sgct::SGCTWindow::No_Stereo) &&
(sm < sgct::SGCTWindow::Side_By_Side_Stereo);
if (hasStereo) {
SpoutWindow::SpoutData& left = w.leftOrMain;
left.handle = GetSpout();
left.initialized = left.handle->CreateSender(
(windowPtr->getName() + "_left").c_str(),
windowPtr->getXFramebufferResolution(),
windowPtr->getYFramebufferResolution()
);
SpoutWindow::SpoutData& right = w.right;
right.handle = GetSpout();
right.initialized = right.handle->CreateSender(
(windowPtr->getName() + "_right").c_str(),
windowPtr->getXFramebufferResolution(),
windowPtr->getYFramebufferResolution()
);
}
else {
SpoutWindow::SpoutData& main = w.leftOrMain;
main.handle = GetSpout();
main.initialized = main.handle->CreateSender(
windowPtr->getName().c_str(),
windowPtr->getXFramebufferResolution(),
windowPtr->getYFramebufferResolution()
);
}
SpoutWindows.push_back(std::move(w));
#else
LWARNING("Spout was requested, but program was compiled without Spout support");
#endif // OPENSPACE_HAS_SPOUT
}
//
// Screenshots
//
std::string screenshotPath = "${SCREENSHOTS}";
if (openspace::global::configuration.shouldUseScreenshotDate) {
std::time_t now = std::time(nullptr);
std::tm* nowTime = std::localtime(&now);
char mbstr[128];
strftime(mbstr, sizeof(mbstr), "%Y-%m-%d-%H-%M", nowTime);
FileSys.registerPathToken(
"${SCREENSHOTS}",
absPath(screenshotPath + '/' + std::string(mbstr)),
ghoul::filesystem::FileSystem::Override::Yes
);
}
for (size_t i = 0; i < nWindows; ++i) {
sgct::SGCTWindow* w = SgctEngine->getWindowPtr(i);
constexpr const char* screenshotNames = "OpenSpace";
sgct_core::ScreenCapture* cpt0 = w->getScreenCapturePointer(0);
sgct_core::ScreenCapture* cpt1 = w->getScreenCapturePointer(1);
if (cpt0) {
cpt0->setPathAndFileName(absPath(screenshotPath), screenshotNames);
}
if (cpt1) {
cpt1->setPathAndFileName(absPath(screenshotPath), screenshotNames);
}
}
LTRACE("main::mainInitFunc(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.init, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainPreSyncFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.preSync, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainPreSyncFunc(begin)");
openspace::global::openSpaceEngine.preSynchronization();
// Query joystick status
using namespace openspace::interaction;
for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) {
JoystickInputState& state = openspace::global::joystickInputStates[i];
int present = glfwJoystickPresent(i);
if (present == GLFW_FALSE) {
state.isConnected = false;
continue;
}
if (!state.isConnected) {
// Joystick was added
state.isConnected = true;
state.name = sgct::Engine::getJoystickName(i);
std::fill(state.axes.begin(), state.axes.end(), 0.f);
std::fill(state.buttons.begin(), state.buttons.end(), JoystickAction::Idle);
}
const float* axes = sgct::Engine::getJoystickAxes(i, &state.nAxes);
if (state.nAxes > JoystickInputState::MaxAxes) {
LWARNING(fmt::format(
"Joystick/Gamepad {} has {} axes, but only {} axes are supported. "
"All excess axes are ignored",
state.name, state.nAxes, JoystickInputState::MaxAxes
));
state.nAxes = JoystickInputState::MaxAxes;
}
std::memcpy(state.axes.data(), axes, state.nAxes * sizeof(float));
const unsigned char* buttons = sgct::Engine::getJoystickButtons(
i,
&state.nButtons
);
if (state.nButtons > JoystickInputState::MaxButtons) {
LWARNING(fmt::format(
"Joystick/Gamepad {} has {} buttons, but only {} buttons are "
"supported. All excess buttons are ignored",
state.name, state.nButtons, JoystickInputState::MaxButtons
));
state.nButtons = JoystickInputState::MaxButtons;
}
for (int j = 0; j < state.nButtons; ++j) {
const bool currentlyPressed = buttons[j] == GLFW_PRESS;
if (currentlyPressed) {
switch (state.buttons[j]) {
case JoystickAction::Idle:
case JoystickAction::Release:
state.buttons[j] = JoystickAction::Press;
break;
case JoystickAction::Press:
case JoystickAction::Repeat:
state.buttons[j] = JoystickAction::Repeat;
break;
}
}
else {
switch (state.buttons[j]) {
case JoystickAction::Idle:
case JoystickAction::Release:
state.buttons[j] = JoystickAction::Idle;
break;
case JoystickAction::Press:
case JoystickAction::Repeat:
state.buttons[j] = JoystickAction::Release;
break;
}
}
}
}
LTRACE("main::mainPreSyncFunc(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.preSync, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainPostSyncPreDrawFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.postSyncPreDraw, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
#ifdef OPENSPACE_HAS_NVTOOLS
nvtxRangePush("postSyncPreDraw");
#endif // OPENSPACE_HAS_NVTOOLS
LTRACE("main::postSynchronizationPreDraw(begin)");
openspace::global::openSpaceEngine.postSynchronizationPreDraw();
#ifdef OPENVR_SUPPORT
if (FirstOpenVRWindow) {
// Update pose matrices for all tracked OpenVR devices once per frame
sgct::SGCTOpenVR::updatePoses();
}
#endif // OPENVR_SUPPORT
LTRACE("main::postSynchronizationPreDraw(end)");
#ifdef OPENSPACE_HAS_NVTOOLS
nvtxRangePop();
#endif // OPENSPACE_HAS_NVTOOLS
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.postSyncPreDraw, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainRenderFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.render, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
#ifdef OPENSPACE_HAS_NVTOOLS
nvtxRangePush("render");
#endif // OPENSPACE_HAS_NVTOOLS
LTRACE("main::mainRenderFunc(begin)");
glm::mat4 viewMatrix = SgctEngine->getCurrentViewMatrix() *
glm::translate(glm::mat4(1.f), sgct::Engine::getDefaultUserPtr()->getPos());
glm::mat4 projectionMatrix = SgctEngine->getCurrentProjectionMatrix();
#ifdef OPENVR_SUPPORT
bool currentWindowIsHMD = FirstOpenVRWindow == SgctEngine->getCurrentWindowPtr();
if (sgct::SGCTOpenVR::isHMDActive() && currentWindowIsHMD) {
projectionMatrix = sgct::SGCTOpenVR::getHMDCurrentViewProjectionMatrix(
SgctEngine->getCurrentFrustumMode()
);
}
#endif
try {
openspace::global::openSpaceEngine.render(
SgctEngine->getModelMatrix(),
viewMatrix,
projectionMatrix
);
}
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
LTRACE("main::mainRenderFunc(end)");
#ifdef OPENSPACE_HAS_NVTOOLS
nvtxRangePop();
#endif // OPENSPACE_HAS_NVTOOLS
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.render, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainDraw2DFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.draw2D, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainDraw2DFunc(begin)");
try {
openspace::global::openSpaceEngine.drawOverlays();
}
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
// SGCT gets angry if we change this in our function
glEnable(GL_BLEND);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
LTRACE("main::mainDraw2DFunc(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.draw2D, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainPostDrawFunc() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.postDraw, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainPostDrawFunc(begin)");
#ifdef OPENVR_SUPPORT
if (FirstOpenVRWindow) {
// Copy the first OpenVR window to the HMD
sgct::SGCTOpenVR::copyWindowToHMD(FirstOpenVRWindow);
}
#endif // OPENVR_SUPPORT
openspace::global::openSpaceEngine.postDraw();
#ifdef OPENSPACE_HAS_SPOUT
for (const SpoutWindow& w : SpoutWindows) {
sgct::SGCTWindow* window = SgctEngine->getWindowPtr(w.windowId);
if (w.leftOrMain.initialized) {
const GLuint texId = window->getFrameBufferTexture(sgct::Engine::LeftEye);
glBindTexture(GL_TEXTURE_2D, texId);
w.leftOrMain.handle->SendTexture(
texId,
GL_TEXTURE_2D,
window->getXFramebufferResolution(),
window->getYFramebufferResolution()
);
}
if (w.right.initialized) {
const GLuint texId = window->getFrameBufferTexture(sgct::Engine::RightEye);
glBindTexture(GL_TEXTURE_2D, texId);
w.right.handle->SendTexture(
texId,
GL_TEXTURE_2D,
window->getXFramebufferResolution(),
window->getYFramebufferResolution()
);
}
}
glBindTexture(GL_TEXTURE_2D, 0);
#endif // OPENSPACE_HAS_SPOUT
LTRACE("main::mainPostDrawFunc(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.postDraw, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainKeyboardCallback(int key, int, int action, int mods) {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.keyboard, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainKeyboardCallback(begin)");
openspace::global::openSpaceEngine.keyboardCallback(
openspace::Key(key),
openspace::KeyModifier(mods),
openspace::KeyAction(action)
);
LTRACE("main::mainKeyboardCallback(begin)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.keyboard, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainMouseButtonCallback(int key, int action, int modifiers) {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.mouseButton, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainMouseButtonCallback(begin)");
openspace::global::openSpaceEngine.mouseButtonCallback(
openspace::MouseButton(key),
openspace::MouseAction(action),
openspace::KeyModifier(modifiers)
);
LTRACE("main::mainMouseButtonCallback(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.mouseButton, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainMousePosCallback(double x, double y) {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.mousePos, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
openspace::global::openSpaceEngine.mousePositionCallback(x, y);
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.mousePos, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainMouseScrollCallback(double posX, double posY) {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.mouseScroll, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainMouseScrollCallback(begin");
openspace::global::openSpaceEngine.mouseScrollWheelCallback(posX, posY);
LTRACE("main::mainMouseScrollCallback(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.mouseScroll, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainCharCallback(unsigned int codepoint, int mods) {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.character, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
openspace::global::openSpaceEngine.charCallback(
codepoint,
openspace::KeyModifier(mods)
);
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.character, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainEncodeFun() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.encode, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainEncodeFun(begin)");
std::vector<char> data = openspace::global::openSpaceEngine.encode();
_synchronizationBuffer.setVal(std::move(data));
sgct::SharedData::instance()->writeVector(&_synchronizationBuffer);
LTRACE("main::mainEncodeFun(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.encode, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainDecodeFun() {
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_begin_v3(_vTune.decode, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
LTRACE("main::mainDecodeFun(begin)");
sgct::SharedData::instance()->readVector(&_synchronizationBuffer);
std::vector<char> data = _synchronizationBuffer.getVal();
openspace::global::openSpaceEngine.decode(std::move(data));
LTRACE("main::mainDecodeFun(end)");
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
__itt_frame_end_v3(_vTune.decode, nullptr);
}
#endif // OPENSPACE_HAS_VTUNE
}
void mainLogCallback(const char* msg) {
std::string message = msg;
if (message.empty() || message == ".") {
// We don't want the empty '.' message that SGCT sends while it is waiting for
// connections from other network nodes
return;
}
// Remove the trailing \n that is passed along
LINFOC("SGCT", message.substr(0, message.size() - 1));
}
} // namespace
void setSgctDelegateFunctions() {
openspace::WindowDelegate& sgctDelegate = openspace::global::windowDelegate;
sgctDelegate.terminate = []() { sgct::Engine::instance()->terminate(); };
sgctDelegate.setBarrier = [](bool enabled) {
sgct::SGCTWindow::setBarrier(enabled);
};
sgctDelegate.setSynchronization = [](bool enabled) {
sgct_core::ClusterManager::instance()->setUseIgnoreSync(enabled);
};
sgctDelegate.clearAllWindows = [](const glm::vec4& clearColor) {
size_t n = sgct::Engine::instance()->getNumberOfWindows();
for (size_t i = 0; i < n; ++i) {
glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLFWwindow* w = sgct::Engine::instance()->getWindowPtr(i)->getWindowHandle();
glfwSwapBuffers(w);
}
};
sgctDelegate.windowHasResized = []() {
return sgct::Engine::instance()->getCurrentWindowPtr()->isWindowResized();
};
sgctDelegate.averageDeltaTime = []() { return sgct::Engine::instance()->getAvgDt(); };
sgctDelegate.deltaTimeStandardDeviation = []() {
return sgct::Engine::instance()->getDtStandardDeviation();
};
sgctDelegate.minDeltaTime = []() {
return sgct::Engine::instance()->getMinDt();
};
sgctDelegate.maxDeltaTime = []() {
return sgct::Engine::instance()->getMaxDt();
};
sgctDelegate.deltaTime = []() { return sgct::Engine::instance()->getDt(); };
sgctDelegate.applicationTime = []() { return sgct::Engine::getTime(); };
sgctDelegate.mousePosition = []() {
int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId();
double posX, posY;
sgct::Engine::getMousePos(id, &posX, &posY);
return glm::vec2(posX, posY);
};
sgctDelegate.mouseButtons = [](int maxNumber) {
int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId();
uint32_t result = 0;
for (int i = 0; i < maxNumber; ++i) {
bool button = (sgct::Engine::getMouseButton(id, i) != 0);
if (button) {
result |= (1 << i);
}
}
return result;
};
sgctDelegate.currentWindowSize = []() {
return glm::ivec2(
sgct::Engine::instance()->getCurrentWindowPtr()->getXResolution(),
sgct::Engine::instance()->getCurrentWindowPtr()->getYResolution());
};
sgctDelegate.currentSubwindowSize = []() {
auto window = sgct::Engine::instance()->getCurrentWindowPtr();
switch (window->getStereoMode()) {
case sgct::SGCTWindow::Side_By_Side_Stereo:
case sgct::SGCTWindow::Side_By_Side_Inverted_Stereo:
return glm::ivec2(window->getXResolution() / 2, window->getYResolution());
case sgct::SGCTWindow::Top_Bottom_Stereo:
case sgct::SGCTWindow::Top_Bottom_Inverted_Stereo:
return glm::ivec2(window->getXResolution(), window->getYResolution() / 2);
default:
return glm::ivec2(window->getXResolution(), window->getYResolution());
}
};
sgctDelegate.currentWindowResolution = []() {
int x, y;
auto window = sgct::Engine::instance()->getCurrentWindowPtr();
window->getFinalFBODimensions(x, y);
return glm::ivec2(x, y);
};
sgctDelegate.currentDrawBufferResolution = []() {
sgct_core::Viewport* viewport =
sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0);
if (viewport != nullptr) {
if (viewport->hasSubViewports() && viewport->getNonLinearProjectionPtr()) {
int res = viewport->getNonLinearProjectionPtr()->getCubemapResolution();
return glm::ivec2(res, res);
}
else {
int x, y;
auto window = sgct::Engine::instance()->getCurrentWindowPtr();
window->getFinalFBODimensions(x, y);
return glm::ivec2(x, y);
}
}
return glm::ivec2(-1, -1);
};
sgctDelegate.currentViewportSize = []() {
sgct_core::Viewport* viewport =
sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0);
if (viewport != nullptr) {
int x = 0;
int y = 0;
sgct::Engine::instance()->getCurrentViewportSize(x, y);
return glm::ivec2(x, y);
}
return glm::ivec2(-1, -1);
};
sgctDelegate.dpiScaling = []() {
return glm::vec2(
sgct::Engine::instance()->getCurrentWindowPtr()->getXScale(),
sgct::Engine::instance()->getCurrentWindowPtr()->getYScale()
);
};
sgctDelegate.currentNumberOfAaSamples = []() {
return sgct::Engine::instance()->getCurrentWindowPtr()->getNumberOfAASamples();
};
sgctDelegate.isRegularRendering = []() {
sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr();
ghoul_assert(
w->getNumberOfViewports() > 0,
"At least one viewport must exist at this time"
);
sgct_core::Viewport* vp = w->getViewport(0);
sgct_core::NonLinearProjection* nlp = vp->getNonLinearProjectionPtr();
return nlp == nullptr;
};
sgctDelegate.hasGuiWindow = []() {
auto engine = sgct::Engine::instance();
for (size_t i = 0; i < engine->getNumberOfWindows(); ++i) {
if (engine->getWindowPtr(i)->checkIfTagExists("GUI")) {
return true;
}
}
return false;
};
sgctDelegate.isGuiWindow = []() {
return sgct::Engine::instance()->getCurrentWindowPtr()->checkIfTagExists("GUI");
};
sgctDelegate.isMaster = []() { return sgct::Engine::instance()->isMaster(); };
sgctDelegate.isUsingSwapGroups = []() {
return sgct::SGCTWindow::isUsingSwapGroups();
};
sgctDelegate.isSwapGroupMaster = []() {
return sgct::SGCTWindow::isSwapGroupMaster();
};
sgctDelegate.viewProjectionMatrix = []() {
return sgct::Engine::instance()->getCurrentModelViewProjectionMatrix();
};
sgctDelegate.modelMatrix = []() {
return sgct::Engine::instance()->getModelMatrix();
};
sgctDelegate.setNearFarClippingPlane = [](float nearPlane, float farPlane) {
sgct::Engine::instance()->setNearAndFarClippingPlanes(nearPlane, farPlane);
};
sgctDelegate.setEyeSeparationDistance = [](float distance) {
sgct::Engine::instance()->setEyeSeparation(distance);
};
sgctDelegate.viewportPixelCoordinates = []() {
sgct::SGCTWindow* window = sgct::Engine::instance()->getCurrentWindowPtr();
if (!window || !window->getCurrentViewport()) {
return glm::ivec4(0, 0, 0, 0);
}
else {
const int* data = sgct::Engine::instance()->getCurrentViewportPixelCoords();
return glm::ivec4(data[0], data[2], data[1], data[3]);
}
};
sgctDelegate.isExternalControlConnected = []() {
return sgct::Engine::instance()->isExternalControlConnected();
};
sgctDelegate.sendMessageToExternalControl = [](const std::vector<char>& message) {
sgct::Engine::instance()->sendMessageToExternalControl(
message.data(),
static_cast<int>(message.size())
);
};
sgctDelegate.isSimpleRendering = []() {
return (sgct::Engine::instance()->getCurrentRenderTarget() !=
sgct::Engine::NonLinearBuffer);
};
sgctDelegate.isFisheyeRendering = []() {
sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr();
return dynamic_cast<sgct_core::FisheyeProjection*>(
w->getViewport(0)->getNonLinearProjectionPtr()
) != nullptr;
};
sgctDelegate.takeScreenshot = [](bool applyWarping) {
sgct::SGCTSettings::instance()->setCaptureFromBackBuffer(applyWarping);
sgct::Engine::instance()->takeScreenshot();
};
sgctDelegate.swapBuffer = []() {
GLFWwindow* w = glfwGetCurrentContext();
glfwSwapBuffers(w);
glfwPollEvents();
};
sgctDelegate.nWindows = []() {
return static_cast<int>(sgct::Engine::instance()->getNumberOfWindows());
};
sgctDelegate.currentWindowId = []() {
return sgct::Engine::instance()->getCurrentWindowPtr()->getId();
};
sgctDelegate.openGLProcedureAddress = [](const char* func) {
return glfwGetProcAddress(func);
};
sgctDelegate.getHorizFieldOfView = []() {
return static_cast<double>(
sgct::Engine::instance()->getWindowPtr(0)->getHorizFieldOfViewDegrees()
);
};
sgctDelegate.setHorizFieldOfView = [](float hFovDeg) {
sgct::SGCTWindow* w = sgct::Engine::instance()->getWindowPtr(0);
w->setHorizFieldOfView(hFovDeg);
};
}
int main(int argc, char** argv) {
#ifdef WIN32
SetUnhandledExceptionFilter(generateMiniDump);
#endif // WIN32
#ifdef OPENSPACE_HAS_VTUNE
if (EnableDetailedVtune) {
_vTune.init = __itt_domain_create("init");
_vTune.preSync = __itt_domain_create("preSync");
_vTune.postSyncPreDraw = __itt_domain_create("postSyncPreDraw");
_vTune.render = __itt_domain_create("render");
_vTune.draw2D = __itt_domain_create("draw2D");
_vTune.postDraw = __itt_domain_create("postDraw");
_vTune.keyboard = __itt_domain_create("keyboard");
_vTune.mouseButton = __itt_domain_create("mouseButton");
_vTune.mousePos = __itt_domain_create("mousePos");
_vTune.mouseScroll = __itt_domain_create("mouseScroll");
_vTune.character = __itt_domain_create("character");
_vTune.encode = __itt_domain_create("encode");
_vTune.decode = __itt_domain_create("decode");
}
#endif // OPENSPACE_HAS_VTUNE
// Initialize the LogManager and add the console log as this will be used every time
// and we need a fall back if something goes wrong between here and when we add the
// logs from the configuration file. If the user requested as specific loglevel in the
// configuration file, we will deinitialize this LogManager and reinitialize it later
// with the correct LogLevel
{
using namespace ghoul::logging;
LogManager::initialize(LogLevel::Debug, LogManager::ImmediateFlush::Yes);
LogMgr.addLog(std::make_unique<ConsoleLog>());
#ifdef WIN32
if (IsDebuggerPresent()) {
LogMgr.addLog(std::make_unique<ghoul::logging::VisualStudioOutputLog>());
}
#endif // WIN32
}
ghoul::initialize();
// Register the path of the executable,
// to make it possible to find other files in the same directory.
FileSys.registerPathToken(
"${BIN}",
ghoul::filesystem::File(absPath(argv[0])).directoryName(),
ghoul::filesystem::FileSystem::Override::Yes
);
//
// Parse commandline arguments
//
ghoul::cmdparser::CommandlineParser parser(
std::string(argv[0]),
ghoul::cmdparser::CommandlineParser::AllowUnknownCommands::Yes
);
openspace::CommandlineArguments commandlineArguments;
parser.addCommand(std::make_unique<ghoul::cmdparser::SingleCommand<std::string>>(
commandlineArguments.configurationName, "--file", "-f",
"Provides the path to the OpenSpace configuration file. Only the '${TEMPORARY}' "
"path token is available and any other path has to be specified relative to the "
"current working directory."
));
parser.addCommand(std::make_unique<ghoul::cmdparser::SingleCommand<std::string>>(
commandlineArguments.configurationOverride, "--config", "-c",
"Provides the ability to pass arbitrary Lua code to the application that will be "
"evaluated after the configuration file has been loaded but before the other "
"commandline arguments are triggered. This can be used to manipulate the "
"configuration file without editing the file on disk, for example in a "
"planetarium environment. Please not that the Lua script must not contain any - "
"or they will be interpreted as a new command. Similar, in Bash, ${...} will be "
"evaluated before it is passed to OpenSpace."
));
// setCommandLine returns a referece to the vector that will be filled later
const std::vector<std::string>& sgctArguments = parser.setCommandLine(
{ argv, argv + argc }
);
bool showHelp = parser.execute();
if (showHelp) {
parser.displayHelp(std::cout);
exit(EXIT_SUCCESS);
}
// Take an actual copy of the arguments
std::vector<std::string> arguments = sgctArguments;
//
// Set up SGCT functions for window delegate
//
setSgctDelegateFunctions();
// Create the OpenSpace engine and get arguments for the SGCT engine
std::string windowConfiguration;
try {
using namespace openspace;
// Find configuration
std::string configurationFilePath = commandlineArguments.configurationName;
if (commandlineArguments.configurationName.empty()) {
LDEBUG("Finding configuration");
configurationFilePath = configuration::findConfiguration();
}
configurationFilePath = absPath(configurationFilePath);
if (!FileSys.fileExists(configurationFilePath)) {
LFATALC("main", "Could not find configuration: " + configurationFilePath);
exit(EXIT_FAILURE);
}
LINFO(fmt::format("Configuration Path: '{}'", configurationFilePath));
// Loading configuration from disk
LDEBUG("Loading configuration from disk");
global::configuration = configuration::loadConfigurationFromFile(
configurationFilePath
);
// If the user requested a commandline-based configuation script that should
// overwrite some of the values, this is the time to do it
if (!commandlineArguments.configurationOverride.empty()) {
LDEBUG("Executing Lua script passed through the commandline:");
LDEBUG(commandlineArguments.configurationOverride);
ghoul::lua::runScript(
global::configuration.state,
commandlineArguments.configurationOverride
);
parseLuaState(global::configuration);
}
// Determining SGCT configuration file
LDEBUG("SGCT Configuration file: " + global::configuration.windowConfiguration);
windowConfiguration = openspace::global::configuration.windowConfiguration;
}
catch (const openspace::documentation::SpecificationError& e) {
LFATALC("main", "Loading of configuration file failed");
for (const openspace::documentation::TestResult::Offense& o : e.result.offenses) {
LERRORC(o.offender, ghoul::to_string(o.reason));
}
for (const openspace::documentation::TestResult::Warning& w : e.result.warnings) {
LWARNINGC(w.offender, ghoul::to_string(w.reason));
}
exit(EXIT_FAILURE);
}
catch (const ghoul::RuntimeError& e) {
// Write out all of the information about the exception and flush the logs
LFATALC(e.component, e.message);
if (ghoul::logging::LogManager::isInitialized()) {
LogMgr.flushLogs();
}
return EXIT_FAILURE;
}
openspace::global::openSpaceEngine.registerPathTokens();
// Prepend the outgoing sgctArguments with the program name
// as well as the configuration file that sgct is supposed to use
arguments.insert(arguments.begin(), argv[0]);
arguments.insert(arguments.begin() + 1, "-config");
arguments.insert(arguments.begin() + 2, absPath(windowConfiguration));
// Need to set this before the creation of the sgct::Engine
sgct::MessageHandler::instance()->setLogToConsole(false);
sgct::MessageHandler::instance()->setShowTime(false);
sgct::MessageHandler::instance()->setLogToCallback(true);
sgct::MessageHandler::instance()->setLogCallback(mainLogCallback);
#ifdef __APPLE__
glfwWindowHint(GLFW_STENCIL_BITS, 8);
#endif
LDEBUG("Creating SGCT Engine");
SgctEngine = new sgct::Engine(arguments);
// Bind functions
SgctEngine->setInitOGLFunction(mainInitFunc);
SgctEngine->setPreSyncFunction(mainPreSyncFunc);
SgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc);
SgctEngine->setDrawFunction(mainRenderFunc);
SgctEngine->setDraw2DFunction(mainDraw2DFunc);
SgctEngine->setPostDrawFunction(mainPostDrawFunc);
SgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback);
SgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback);
SgctEngine->setMousePosCallbackFunction(mainMousePosCallback);
SgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback);
SgctEngine->setCharCallbackFunction(mainCharCallback);
// Disable the immediate exit of the application when the ESC key is pressed
SgctEngine->setExitKey(SGCT_KEY_UNKNOWN);
sgct::MessageHandler::instance()->setNotifyLevel(sgct::MessageHandler::NOTIFY_ALL);
// Set encode and decode functions
// NOTE: starts synchronizing before init functions
sgct::SharedData::instance()->setEncodeFunction(mainEncodeFun);
sgct::SharedData::instance()->setDecodeFunction(mainDecodeFun);
// Try to open a window
LDEBUG("Initialize SGCT Engine");
std::map<std::pair<int, int>, sgct::Engine::RunMode> versionMapping = {
{ { 3, 3 }, sgct::Engine::RunMode::OpenGL_3_3_Core_Profile },
{ { 4, 0 }, sgct::Engine::RunMode::OpenGL_4_0_Core_Profile },
{ { 4, 1 }, sgct::Engine::RunMode::OpenGL_4_1_Core_Profile },
{ { 4, 2 }, sgct::Engine::RunMode::OpenGL_4_2_Core_Profile },
{ { 4, 3 }, sgct::Engine::RunMode::OpenGL_4_3_Core_Profile },
{ { 4, 4 }, sgct::Engine::RunMode::OpenGL_4_4_Core_Profile },
{ { 4, 5 }, sgct::Engine::RunMode::OpenGL_4_5_Core_Profile },
{ { 4, 6 }, sgct::Engine::RunMode::OpenGL_4_6_Core_Profile }
};
std::pair<int, int> version = supportedOpenGLVersion();
LINFO(fmt::format("Detected OpenGL version: {}.{}", version.first, version.second));
bool initSuccess = SgctEngine->init(versionMapping[version]);
#ifdef __APPLE__
// Workaround for OpenGL bug that Apple introduced in 10.14 Mojave that prevents an
// OpenGL context to display anything until it is first moved or resized in dark
// mode. So we are going through all windows here and resize them a bit larger and
// then back to the desired resolution. Resizing the window to the same size doesn't
// work as GLFW probably has a check for setting the current values.
// This can be removed once the OpenGL bug is fixed.
// In order to check, comment out the following lines and start OpenSpace on a 10.14
// machine. If the loading screen shows up without doing anything to the window, it
// is fixed. With the bug, the rendering stays gray even well after the main render
// loop has started -- 2018-10-28 abock
size_t n = sgct::Engine::instance()->getNumberOfWindows();
for (size_t i = 0; i < n; ++i) {
GLFWwindow* w = sgct::Engine::instance()->getWindowPtr(i)->getWindowHandle();
int x, y;
glfwGetWindowPos(w, &x, &y);
glfwSetWindowPos(w, x + 1, y + 1);
glfwSwapBuffers(w);
glfwPollEvents();
glfwSetWindowPos(w, x, y);
glfwSwapBuffers(w);
glfwPollEvents();
}
#endif // __APPLE__
// Do not print message if slaves are waiting for the master
// Only timeout after 15 minutes
SgctEngine->setSyncParameters(false, 15.f * 60.f);
auto cleanup = [&](bool isInitialized) {
if (isInitialized) {
openspace::global::openSpaceEngine.deinitializeGL();
openspace::global::openSpaceEngine.deinitialize();
}
// Clear function bindings to avoid crash after destroying the OpenSpace Engine
sgct::MessageHandler::instance()->setLogToCallback(false);
sgct::MessageHandler::instance()->setLogCallback(nullptr);
LDEBUG("Destroying SGCT Engine");
delete SgctEngine;
#ifdef OPENVR_SUPPORT
// Clean up OpenVR
sgct::SGCTOpenVR::shutdown();
#endif
#ifdef OPENSPACE_HAS_SPOUT
for (SpoutWindow& w : SpoutWindows) {
if (w.leftOrMain.handle) {
w.leftOrMain.handle->ReleaseReceiver();
w.leftOrMain.handle->Release();
}
if (w.right.handle) {
w.right.handle->ReleaseReceiver();
w.right.handle->Release();
}
}
#endif // OPENSPACE_HAS_SPOUT
};
if (!initSuccess) {
LFATAL("Initializing failed");
cleanup(false);
return EXIT_FAILURE;
}
LINFO("Starting rendering loop");
SgctEngine->render();
LINFO("Ending rendering loop");
cleanup(true);
exit(EXIT_SUCCESS);
}
|
/*
* Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/PlayRho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "UnitTests.hpp"
#include <PlayRho/Dynamics/Contacts/Contact.hpp>
#include <PlayRho/Dynamics/Fixture.hpp>
#include <PlayRho/Dynamics/Body.hpp>
#include <PlayRho/Dynamics/World.hpp>
#include <PlayRho/Dynamics/BodyConf.hpp>
#include <PlayRho/Dynamics/FixtureConf.hpp>
#include <PlayRho/Collision/Shapes/DiskShapeConf.hpp>
using namespace playrho;
using namespace playrho::d2;
TEST(Contact, ByteSize)
{
switch (sizeof(Real))
{
case 4: EXPECT_EQ(sizeof(Contact), std::size_t(128)); break;
case 8: EXPECT_EQ(sizeof(Contact), std::size_t(192)); break;
case 16: EXPECT_EQ(sizeof(Contact), std::size_t(384)); break;
default: FAIL(); break;
}
}
TEST(Contact, Traits)
{
EXPECT_FALSE(std::is_default_constructible<Contact>::value);
EXPECT_TRUE(std::is_copy_constructible<Contact>::value);
EXPECT_FALSE(std::is_copy_assignable<Contact>::value);
EXPECT_FALSE(IsAddable<Contact>::value);
EXPECT_FALSE((IsAddable<Contact, Contact>::value));
EXPECT_FALSE(IsIterable<Contact>::value);
}
TEST(Contact, Enabled)
{
const auto shape = DiskShapeConf{};
auto world = World{};
const auto bA = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto bB = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto fA = bA->CreateFixture(Shape{shape});
const auto fB = bB->CreateFixture(Shape{shape});
auto c = Contact{fA, 0u, fB, 0u};
EXPECT_TRUE(c.IsEnabled());
c.UnsetEnabled();
EXPECT_FALSE(c.IsEnabled());
c.SetEnabled();
EXPECT_TRUE(c.IsEnabled());
}
TEST(Contact, SetAwake)
{
const auto shape = DiskShapeConf{};
auto world = World{};
const auto bA = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto bB = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto fA = bA->CreateFixture(Shape{shape});
const auto fB = bB->CreateFixture(Shape{shape});
const auto c = Contact{fA, 0u, fB, 0u};
bA->UnsetAwake();
ASSERT_FALSE(bA->IsAwake());
bB->UnsetAwake();
ASSERT_FALSE(bB->IsAwake());
SetAwake(c);
EXPECT_TRUE(bA->IsAwake());
EXPECT_TRUE(bB->IsAwake());
}
TEST(Contact, ResetFriction)
{
const auto shape = DiskShapeConf{};
auto world = World{};
const auto bA = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto bB = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto fA = bA->CreateFixture(Shape{shape});
const auto fB = bB->CreateFixture(Shape{shape});
auto c = Contact{fA, 0u, fB, 0u};
ASSERT_GT(GetFriction(shape), Real(0));
ASSERT_NEAR(static_cast<double>(c.GetFriction()), static_cast<double>(Real{GetFriction(shape)}), 0.01);
c.SetFriction(GetFriction(shape) * Real(2));
ASSERT_NE(c.GetFriction(), GetFriction(shape));
ResetFriction(c);
EXPECT_NEAR(static_cast<double>(c.GetFriction()), static_cast<double>(Real{GetFriction(shape)}), 0.01);
}
TEST(Contact, ResetRestitution)
{
const auto shape = DiskShapeConf{};
auto world = World{};
const auto bA = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto bB = world.CreateBody(BodyConf{}.UseType(BodyType::Dynamic));
const auto fA = bA->CreateFixture(Shape{shape});
const auto fB = bB->CreateFixture(Shape{shape});
auto c = Contact{fA, 0u, fB, 0u};
ASSERT_EQ(GetRestitution(shape), Real(0));
ASSERT_EQ(c.GetRestitution(), GetRestitution(shape));
c.SetRestitution(Real(2));
ASSERT_NE(c.GetRestitution(), GetRestitution(shape));
ResetRestitution(c);
EXPECT_EQ(c.GetRestitution(), GetRestitution(shape));
}
|
/*
* 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.
*/
/**
* @author Intel, Pavel A. Ozhdikhin
*
*/
#include <iostream>
#include "Opcode.h"
#include "optarithmetic.h"
#include "Log.h"
#include "optimizer.h"
namespace Jitrino {
// new MODIFIER system
// to allow some checking of modifiers and opcodes, an Operation value is checked
// at construction time to make sure that the modifiers appropriate to the Opcode
// are present.
//
// To add a new Modifier, use "NewModifier1" and "NewModifier2" as a model,
// but please leave them there as models for others. See Opcode.h as well;
// there, numbers (_IsShiftedBy and Modifier::Kind values) should be adjusted after adding
// the new modifier before Modifier1
//
// Next, any instruction which uses the modifier must have the modifier as part of its
// modifierKind field in opcodeTable. Unfortunately, due to typing issues when there are
// several modifiers present, the combination must be defined in Modifer::Kind. See
// the definition of Overflow_and_Exception_and_Strict in Opcode.h for an example.
//
// (There may be a way to abstract some of the numeric constants, but I was hitted by a compiler
// issues with a more elegant solution and backed off to this.)
struct Mobility {
enum Kind {
None, // phis, labels, pis, and the like
Movable, // totally movable (but must also check for Overflow modifier)
CSEable, // can be CSEed
Check, // see also
Exception, // can generate an exception
StoreOrSync, // affects memory state
Call, // may end a block, may have exception, may affect memory state
ControlFlow, // is control flow
Load, // is a load
MustEndBlock // --- not used
};
};
typedef Modifier::Kind MK;
typedef Mobility MB;
struct OpcodeInfo {
Opcode opcode;
bool essential;
Mobility::Kind mobility;
MK::Enum modifierKind;
const char *opcodeString;
const char *opcodeFormatString;
};
static OpcodeInfo opcodeTable[] = {
{ Op_Add, false, MB::Movable, MK::Overflow_and_Exception_and_Strict, "add ", "add%m %s -) %l" },
{ Op_Mul, false, MB::Movable, MK::Overflow_and_Exception_and_Strict, "mul ", "mul%m %s -) %l", },
{ Op_Sub, false, MB::Movable, MK::Overflow_and_Exception_and_Strict, "sub ", "sub%m %s -) %l", },
{ Op_TauDiv, false, MB::Movable, MK::Signed_and_Strict, "div ", "div%m %0,%1 ((%2)) -) %l", }, // (opnds must already be checked for 0/overflow)
{ Op_TauRem, false, MB::Movable, MK::Signed_and_Strict, "rem ", "rem%m %0,%1 ((%2)) -) %l", }, // (opnds must already be checked for 0/overflow)
{ Op_Neg, false, MB::Movable, MK::None, "neg ", "neg %s -) %l", },
{ Op_MulHi, false, MB::Movable, MK::Signed, "mulhi ", "mulhi%m %s -) %l", }, // SignedModifier (but only signed needed now)
{ Op_Min, false, MB::Movable, MK::None, "min ", "min %s -) %l", },
{ Op_Max, false, MB::Movable, MK::None, "max ", "max %s -) %l", },
{ Op_Abs, false, MB::Movable, MK::None, "abs ", "abs %s -) %l", },
{ Op_And, false, MB::Movable, MK::None, "and ", "and %s -) %l", },
{ Op_Or, false, MB::Movable, MK::None, "or ", "or %s -) %l", },
{ Op_Xor, false, MB::Movable, MK::None, "xor ", "xor %s -) %l", },
{ Op_Not, false, MB::Movable, MK::None, "not ", "not %s -) %l", },
{ Op_Select, false, MB::Movable, MK::None, "select", "select %s -) %l", }, // (src1 ? src2 : src3)
{ Op_Conv, false, MB::Movable, MK::Overflow_and_Exception_and_Strict, "conv ", "conv%t%m %s -) %l", },
{ Op_ConvZE, false, MB::Movable, MK::Overflow_and_Exception_and_Strict, "convze ", "conv_ze_%t%m %s -) %l", },
{ Op_ConvUnmanaged, false, MB::StoreOrSync, MK::Overflow_and_Exception_and_Strict, "convu ", "conv_unm_%t%m %s -) %l", },
{ Op_Shladd, false, MB::Movable, MK::None, "shladd", "shladd %s -) %l", }, // no mods, 2nd operand must be LdConstant
{ Op_Shl, false, MB::Movable, MK::ShiftMask, "shl ", "shl%m %s -) %l", },
{ Op_Shr, false, MB::Movable, MK::ShiftMask_and_Signed, "shr ", "shr%m %s -) %l", },
{ Op_Cmp, false, MB::Movable, MK::Comparison, "cmp ", "c%m:%t %s -) %l", },
{ Op_Cmp3, false, MB::Movable, MK::Comparison, "cmp3 ", "c3%m:%t %s -) %l", }, // 3-way compare, e.g.: ((s0>s1)?1:((s1>s0)?-1:0))
{ Op_Branch, true, MB::ControlFlow, MK::Comparison, "br ", "if c%m.%t %s goto %l", },
{ Op_Jump, true, MB::ControlFlow, MK::None, "jmp ", "goto %l", }, // (different from the CLI jmp opcode)
{ Op_Switch, true, MB::ControlFlow, MK::None, "switch", "switch (%l)[%0]", },
{ Op_DirectCall, true, MB::Call, MK::Exception, "call ", "call %d(%p) ((%0,%1)) -) %l %b", },
{ Op_TauVirtualCall, true, MB::Call, MK::Exception, "callvirt", "callvrt [%2.%d](%a) ((%0,%1)) -) %l %b", },
{ Op_IndirectCall, true, MB::Call, MK::Exception, "calli", "calli [%0](%a) ((%1,%2)) -) %l", },
{ Op_IndirectMemoryCall, true, MB::Call, MK::Exception, "callimem", "callimem [%0](%a) ((%1,%2)) -) %l", },
{ Op_JitHelperCall, true, MB::Call, MK::Exception, "callhelper", "callhelper %d(%s) -) %l", },
{ Op_VMHelperCall, true, MB::Call, MK::Exception, "callvmhelper", "callvmhelper %d(%s) -) %l %b", },
{ Op_Return, true, MB::ControlFlow, MK::None, "return", "return %s", },
{ Op_Catch, true, MB::ControlFlow, MK::None, "catch", "catch -) %l", },
{ Op_Throw, true, MB::Exception, MK::Throw, "throw ", "throw %0 %b", },
{ Op_PseudoThrow, true, MB::Exception, MK::Exception, "pseudoThrow ", "pseudoThrow %b", },
{ Op_ThrowSystemException, true, MB::Exception, MK::None, "throwsys ", "throwsys %d %b", },
{ Op_ThrowLinkingException, true, MB::Exception, MK::None, "throwLink ", "throwLink", },
{ Op_JSR, true, MB::Call, MK::None, "jsr", "jsr %l", }, // Java only, JSR's -- DELETE
{ Op_Ret, true, MB::ControlFlow, MK::None, "ret", "ret %s", }, // Java only, JSR's -- DELETE
{ Op_SaveRet, true, MB::ControlFlow, MK::None, "saveret", "saveret -) %l", }, // Java only, JSR's -- DELETE
// Move instruction
{ Op_Copy, false, MB::Movable, MK::None, "copy", "copy %s -) %l", },
{ Op_DefArg, true, MB::None, MK::DefArg, "defarg", "defarg%m -) %l", },
// Load instructions
{ Op_LdConstant, false, MB::Movable, MK::None, "ldc ", "ldc%t #%c -) %l", },
{ Op_LdRef, false, MB::Movable, MK::AutoCompress, "ldref ", "ldref%m (%d) -) %l %b", },
{ Op_LdVar, false, MB::None, MK::None, "ldvar ", "ldvar %0 -) %l", },
{ Op_LdVarAddr, false, MB::Movable, MK::None, "ldvara", "ldvara %0 -) %l", },
{ Op_TauLdInd, false, MB::Load, MK::AutoCompress_Speculative, "ldind", "ldind%m:%t [%0] ((%1,%2)) -) %l", },
{ Op_TauLdField, false, MB::Load, MK::AutoCompress, "ldfld", "ldfld:%t [%0.%d] ((%1,%2)) -) %l", },
{ Op_LdStatic, false, MB::Load, MK::AutoCompress, "ldsfld", "ldsfld:%t [%d] -) %l", },
{ Op_TauLdElem, false, MB::Load, MK::AutoCompress, "ldelem", "ldelem:%t [%0[%1]] ((%2,%3)) -) %l", },
{ Op_LdFieldAddr, false, MB::Movable, MK::None, "ldflda", "ldflda [%0.%d] -) %l", },
{ Op_LdStaticAddr, false, MB::Movable, MK::None, "ldsflda", "ldsflda [%d] -) %l", },
{ Op_LdElemAddr, false, MB::Movable, MK::None, "ldelema", "ldelema [%0[%1]] -) %l", },
{ Op_TauLdVTableAddr, false, MB::Movable, MK::None, "ldvtable", "ldvtable %0 ((%1)) -) %l", },
{ Op_TauLdIntfcVTableAddr, false, MB::Movable, MK::None, "ldintfcvt", "ldintfcvt %0,%d -) %l", },
{ Op_TauLdVirtFunAddr, false, MB::CSEable, MK::None, "ldvfn ", "ldvfn [%0.%d] ((%1)) -) %l", },
{ Op_TauLdVirtFunAddrSlot, false, MB::CSEable, MK::None, "ldvfnslot", "ldvfnslot [%0.%d] ((%1)) -) %l", },
{ Op_LdFunAddr, false, MB::CSEable, MK::None, "ldfn ", "ldfn [%d] -) %l", },
{ Op_LdFunAddrSlot, false, MB::CSEable, MK::None, "ldfnslot", "ldfnslot [%d] -) %l", },
{ Op_GetVTableAddr, false, MB::Movable, MK::None, "getvtable", "getvtable %d -) %l", }, // obtains the address of the vtable for a particular object type
{ Op_GetClassObj, false, MB::Movable, MK::None, "getclassobj", "getclassobj %d -) %l", }, // obtains the java.lang.class object for a particular type
{ Op_TauArrayLen, false, MB::CSEable, MK::None, "arraylen ", "arraylen %0 ((%1,%2)) -) %l", },
{ Op_LdArrayBaseAddr, false, MB::CSEable, MK::None, "ldbase", "ldbase %s -) %l", }, // load the base (zero'th element) address of array
{ Op_AddScaledIndex, false, MB::Movable, MK::None, "addindex", "addindex %s -) %l", }, // Add a scaled index to an array element address
{ Op_StVar, true, MB::None, MK::None, "stvar ", "stvar %0 -) %l", },
{ Op_TauStInd, true, MB::StoreOrSync, MK::Store_AutoCompress, "stind", "stind%m:%t %0 ((%2,%3,%4)) -) [%1]", },
{ Op_TauStField, true, MB::StoreOrSync, MK::Store_AutoCompress, "stfld", "stfld%m:%t %0 ((%2,%3)) -) [%1.%d]", },
{ Op_TauStElem, true, MB::StoreOrSync, MK::Store_AutoCompress, "stelem", "stelem%m:%t %0 ((%3,%4,%5)) -) [%1[%2]]", },
{ Op_TauStStatic, true, MB::StoreOrSync, MK::Store_AutoCompress, "stsfld", "stsfld:%t %0 ((%1)) -) [%d]", },
{ Op_TauStRef, true, MB::StoreOrSync, MK::Store_AutoCompress, "stref ", "stref%m %0 ((%3,%4,%5)) -) [%1 %2] ", }, // high-level version that will make a call to the VM
{ Op_TauCheckBounds, false, MB::Check, MK::Overflow_and_Exception, "chkbounds", "chkbounds %1 .lt. %0 -) %l %b", }, // takes index and array length arguments, },
{ Op_TauCheckLowerBound, false, MB::Check, MK::Overflow_and_Exception, "chklb", "chklb %0 .le. %1 -) %l", }, // throws unless src0 <= src1
{ Op_TauCheckUpperBound, false, MB::Check, MK::Overflow_and_Exception, "chkub", "chkub %0 .lt. %1 -) %l", }, // throws unless src0 < src1
{ Op_TauCheckNull, false, MB::Check, MK::Exception_and_DefArg, "chknull", "chknull %0 -) %l %b", }, // throws NullPointerException if src is null
{ Op_TauCheckZero, false, MB::Check, MK::Exception, "chkzero", "chkzero %0 -) %l %b", }, // for divide by zero exceptions (div and rem)
{ Op_TauCheckDivOpnds, false, MB::Check, MK::Exception, "chkdivopnds", "chkdivopnds %0,%1 -) %l", }, // for signed divide overflow in CLI (div/rem of MAXNEGINT, -1): generates an ArithmeticException
{ Op_TauCheckElemType, false, MB::Check, MK::Exception, "chkelemtype", "chkelemtype %0,%1 ((%2,%3)) -) %l", }, // Array element type check for aastore
{ Op_TauCheckFinite, false, MB::Check, MK::Exception, "ckfinite", "ckfinite %s -) %l", }, // throws ArithmeticException if value is NaN or +- inifinity
{ Op_NewObj, false, MB::Exception, MK::Exception, "newobj", "newobj %d -) %l %b", }, // OutOfMemoryException
{ Op_NewArray, false, MB::Exception, MK::Exception, "newarray", "newarray %d[%0] -) %l %b", }, // OutOfMemoryException, NegativeArraySizeException
{ Op_NewMultiArray, false, MB::Exception, MK::Exception, "newmultiarray", "newmultiarray %d[%s] -) %l", }, // OutOfMemoryException, NegativeArraySizeException
{ Op_TauMonitorEnter, true, MB::StoreOrSync, MK::None, "monenter", "monenter %0 ((%1))", }, // (opnd must be non-null)
{ Op_TauMonitorExit, true, MB::StoreOrSync, MK::Exception, "monexit", "monexit %0 ((%1))", }, // (opnd must be non-null), IllegalMonitorStateException
{ Op_TypeMonitorEnter, true, MB::StoreOrSync, MK::None, "tmonenter", "monenter %d", },
{ Op_TypeMonitorExit, true, MB::StoreOrSync, MK::Exception, "tmonexit", "monexit %d", },
{ Op_LdLockAddr, false, MB::Movable, MK::None, "ldlockaddr", "ldlockaddr %0 -) %l", }, // yields ref:int16
{ Op_IncRecCount, true, MB::StoreOrSync, MK::None, "increccnt", "increccnt %s", }, // allows BalancedMonitorEnter to be used with regular MonitorExit
{ Op_TauBalancedMonitorEnter, true, MB::StoreOrSync, MK::None, "balmonenter", "balmonenter %0,%1 ((%2)) -) %l", }, // (opnd must be non-null), postdominated by BalancedMonitorExit
{ Op_BalancedMonitorExit, true, MB::StoreOrSync, MK::None, "balmonexit", "balmonexit %s", }, // (cannot yield exception), },dominated by BalancedMonitorEnter
{ Op_TauOptimisticBalancedMonitorEnter, true, MB::StoreOrSync, MK::None, "optbalmonenter", "optbalmonenter %0,%1 ((%2)) -) %l", }, // (opnd must be non-null), postdominated by BalancedMonitorExit
{ Op_OptimisticBalancedMonitorExit, true, MB::StoreOrSync, MK::Exception, "optbalmonexit", "optbalmonexit %s", }, // (cannot yield exception), },dominated by BalancedMonitorEnter
{ Op_MonitorEnterFence, true, MB::StoreOrSync, MK::None, "monenterfence", "monenterfence %0", }, // (opnd must be non-null)
{ Op_MonitorExitFence, true, MB::StoreOrSync, MK::None, "monexitfence", "monexitfence %0", }, // (opnd must be non-null)
{ Op_TauStaticCast, false, MB::Movable, MK::None, "staticcast", "staticcast %0,%d ((%1)) -) %l", }, // Compile-time assertion. Asserts that cast is legal.
{ Op_TauCast, false, MB::Check, MK::Exception, "cast ", "cast %0,%d ((%1)) -) %l %b", }, // CastException (suceeds if argument is null, returns casted object)
{ Op_TauAsType, false, MB::Movable, MK::None, "astype", "astype %0,%d -) %l", }, // returns casted object if argument is an instance of, null otherwise
{ Op_TauInstanceOf, false, MB::Movable, MK::None, "instanceof", "instanceof %0,%d ((%1)) -) %l",}, // returns true if argument is an instance of type T, tau opnd isNonNull
{ Op_InitType, true, MB::CSEable, MK::Exception, "inittype", "inittype %d %b", }, // can throw a linking exception during class initialization
{ Op_Label, true, MB::None, MK::None, "label ", "%l: %b", }, // special label instructions for branch labels, finally, catch
{ Op_MethodEntry, true, MB::None, MK::None, "methodentry", "--- MethodEntry(%d): (%s) %b",}, // method entry label
{ Op_MethodEnd, true, MB::None, MK::None, "methodend", "+++ MethodEnd(%d) (%s)", }, // end of a method
// Memory instructions
// Special SSA nodes
{ Op_Phi, false, MB::None, MK::None, "phi ", "phi(%s) -) %l", }, // merge point
{ Op_TauPi, false, MB::Movable, MK::None, "pi ", "pi(%0 : %d) ((%1)) -) %l", }, // liverange split based on condition
// Profile instrumentation instructions
{ Op_IncCounter, true, MB::None, MK::None, "inccounter", "inccounter(%d)", }, // Increment a profile counter by 1
{ Op_Prefetch, true, MB::StoreOrSync, MK::None, "prefetch", "prefetch %0 ", }, //StoreOrSync
// Compressed Pointer instructions
{ Op_UncompressRef, false, MB::Movable, MK::None, "uncmpref", "uncmpref %s -) %l", },
{ Op_CompressRef, false, MB::Movable, MK::None, "cmpref", "cmpref %s -) %l", },
{ Op_LdFieldOffset, false, MB::Movable, MK::None, "ldfldoff", "ldfldoff [.%d] -) %l", },
{ Op_LdFieldOffsetPlusHeapbase,
false, MB::Movable, MK::None, "ldfldophb", "ldfldoffphb [.%d] -) %l", },
{ Op_LdArrayBaseOffset, false, MB::Movable, MK::None, "ldbaseoff", "ldbaseoff -) %l", },
{ Op_LdArrayBaseOffsetPlusHeapbase,
false, MB::Movable, MK::None, "ldbaseoffphb", "ldbaseoffphb -) %l", },
{ Op_LdArrayLenOffset, false, MB::Movable, MK::None, "ldlenoff", "ldlenoff -) %l", },
{ Op_LdArrayLenOffsetPlusHeapbase,
false, MB::Movable, MK::None, "ldlenoffphb", "ldlenoffphb -) %l", },
{ Op_AddOffset, false, MB::Movable, MK::None, "addoffset", "addoff %s -) %l", },
{ Op_AddOffsetPlusHeapbase, false, MB::Movable, MK::None, "addoffphb", "addoffphb %s -) %l", },
{ Op_TauPoint, false, MB::None, MK::None, "taupoint ", "taupoint() -) %l", }, // mark
{ Op_TauEdge, false, MB::None, MK::None, "tauedge ", "tauedge() -) %l", }, // mark
{ Op_TauAnd, false, MB::Movable, MK::None, "tauand ", "tauand %s -) %l", },
{ Op_TauUnsafe, false, MB::None, MK::None, "tauunsafe", "tauunsafe() -) %l", }, // mark
{ Op_TauSafe, false, MB::None, MK::None, "tauunsafe", "tausafe() -) %l", }, // mark
{ Op_TauCheckCast, false, MB::Check, MK::Exception, "tauchkcast ", "tauchkcast %0,%d ((%1)) -) %l", }, // CastException (suceeds if argument is null, returns casted object)
{ Op_TauHasType, false, MB::Movable, MK::None, "tauhastype ", "tauhastype %0,%d -) %l", }, // temporary declaration that source is of given type
{ Op_TauHasExactType, false, MB::CSEable, MK::None, "tauexacttype ", "tauexacttype %0,%d -) %l", }, // temporary declaration that source is exactly of given type
{ Op_TauIsNonNull, true, MB::CSEable, MK::None, "tauisnonnull ", "tauisnonnull %0 -) %l", }, // temporary declaration that source null
{ Op_IdentHC, true, MB::Call, MK::None, "identityHC", "identityHC %s -) %l ", },
};
unsigned short Modifier::encode(Opcode opcode, U_32 numbits) const
{
assert((opcode >= 0) && (opcode < NumOpcodes));
Modifier::Kind::Enum kinds = opcodeTable[opcode].modifierKind;
if (kinds == 0) return 0;
U_32 encoded = 0;
U_32 bitsused = 0;
if ((kinds & Modifier::Kind::Overflow) != 0) addEncoding(encoded, bitsused, Overflow_Mask, Overflow_None, Overflow_Unsigned, OverflowModifier_IsShiftedBy, OverflowModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Signed) != 0) addEncoding(encoded, bitsused, Signed_Mask, SignedOp, UnsignedOp, SignedModifier_IsShiftedBy, SignedModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Comparison) != 0) addEncoding(encoded, bitsused, Cmp_Mask, Cmp_EQ, Cmp_NonZero, ComparisonModifier_IsShiftedBy, ComparisonModifier_BitsToEncode);
if ((kinds & Modifier::Kind::ShiftMask) != 0) addEncoding(encoded, bitsused, ShiftMask_Mask, ShiftMask_None, ShiftMask_Masked, ShiftMaskModifier_IsShiftedBy, ShiftMaskModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Strict) != 0) addEncoding(encoded, bitsused, Strict_Mask, Strict_No, Strict_Yes, StrictModifier_IsShiftedBy, StrictModifier_BitsToEncode);
if ((kinds & Modifier::Kind::DefArg) != 0) addEncoding(encoded, bitsused, DefArg_Mask, DefArgNoModifier, DefArgBothModifiers, DefArgModifier_IsShiftedBy, DefArgModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Store) != 0) addEncoding(encoded, bitsused, Store_Mask, Store_NoWriteBarrier, Store_WriteBarrier, StoreModifier_IsShiftedBy, StoreModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Exception) != 0) addEncoding(encoded, bitsused, Exception_Mask, Exception_Sometimes, Exception_Never, ExceptionModifier_IsShiftedBy, ExceptionModifier_BitsToEncode);
if ((kinds & Modifier::Kind::AutoCompress) != 0) addEncoding(encoded, bitsused, AutoCompress_Mask, AutoCompress_Yes, AutoCompress_No, AutoCompressModifier_IsShiftedBy, AutoCompressModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Speculative) != 0) addEncoding(encoded, bitsused,
Speculative_Mask, Speculative_Yes, Speculative_No, SpeculativeModifier_IsShiftedBy, SpeculativeModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Throw) != 0) addEncoding(encoded, bitsused, Throw_Mask, Throw_NoModifier, Throw_CreateStackTrace, ThrowModifier_IsShiftedBy, ThrowModifier_BitsToEncode);
if ((kinds & Modifier::Kind::NewModifier1) != 0) addEncoding(encoded, bitsused, NewModifier1_Mask, NewModifier1_Value1, NewModifier1_Value2, NewModifier1_IsShiftedBy, NewModifier1_BitsToEncode);
if ((kinds & Modifier::Kind::NewModifier2) != 0) addEncoding(encoded, bitsused, NewModifier2_Mask, NewModifier2_Value1, NewModifier2_Value3, NewModifier2_IsShiftedBy, NewModifier2_BitsToEncode);
assert(bitsused <= numbits);
unsigned short usencoded = (unsigned short) encoded;
assert(encoded == (U_32) usencoded);
if (0 && Log::isEnabled()) {
Log::out() << ::std::endl << "Modifier " << ::std::hex << (int) value << " and Opcode "
<< (int) opcode << " encoded as " << (int) usencoded << ::std::dec << ::std::endl;
}
return (unsigned short) usencoded;
}
Modifier::Modifier(Opcode opcode, U_32 encoding) : value(0)
{
assert((opcode >= 0) && (opcode < NumOpcodes));
Modifier::Kind::Enum kinds = opcodeTable[opcode].modifierKind;
if (kinds == 0) return;
U_32 bitsused = 0;
if ((kinds & Modifier::Kind::Overflow) != 0) addDecoding(encoding, bitsused, Overflow_Mask, Overflow_None, Overflow_Unsigned, OverflowModifier_IsShiftedBy, OverflowModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Signed) != 0) addDecoding(encoding, bitsused, Signed_Mask, SignedOp, UnsignedOp, SignedModifier_IsShiftedBy, SignedModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Comparison) != 0) addDecoding(encoding, bitsused, Cmp_Mask, Cmp_EQ, Cmp_NonZero, ComparisonModifier_IsShiftedBy, ComparisonModifier_BitsToEncode);
if ((kinds & Modifier::Kind::ShiftMask) != 0) addDecoding(encoding, bitsused, ShiftMask_Mask, ShiftMask_None, ShiftMask_Masked, ShiftMaskModifier_IsShiftedBy, ShiftMaskModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Strict) != 0) addDecoding(encoding, bitsused, Strict_Mask, Strict_No, Strict_Yes, StrictModifier_IsShiftedBy, StrictModifier_BitsToEncode);
if ((kinds & Modifier::Kind::DefArg) != 0) addDecoding(encoding, bitsused, DefArg_Mask, DefArgNoModifier, DefArgBothModifiers, DefArgModifier_IsShiftedBy, DefArgModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Store) != 0) addDecoding(encoding, bitsused, Store_Mask, Store_NoWriteBarrier, Store_WriteBarrier, StoreModifier_IsShiftedBy, StoreModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Exception) != 0) addDecoding(encoding, bitsused, Exception_Mask, Exception_Sometimes, Exception_Never, ExceptionModifier_IsShiftedBy, ExceptionModifier_BitsToEncode);
if ((kinds & Modifier::Kind::AutoCompress) != 0) addDecoding(encoding, bitsused, AutoCompress_Mask, AutoCompress_Yes, AutoCompress_No, AutoCompressModifier_IsShiftedBy, AutoCompressModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Speculative) != 0) addDecoding(encoding, bitsused, Speculative_Mask, Speculative_Yes, Speculative_No, SpeculativeModifier_IsShiftedBy, SpeculativeModifier_BitsToEncode);
if ((kinds & Modifier::Kind::Throw) != 0) addDecoding(encoding, bitsused, Throw_Mask, Throw_NoModifier, Throw_CreateStackTrace, ThrowModifier_IsShiftedBy, ThrowModifier_BitsToEncode);
if ((kinds & Modifier::Kind::NewModifier1) != 0) addDecoding(encoding, bitsused, NewModifier1_Mask, NewModifier1_Value1, NewModifier1_Value2, NewModifier1_IsShiftedBy, NewModifier1_BitsToEncode);
if ((kinds & Modifier::Kind::NewModifier2) != 0) addDecoding(encoding, bitsused, NewModifier2_Mask, NewModifier2_Value1, NewModifier2_Value3, NewModifier2_IsShiftedBy, NewModifier2_BitsToEncode);
assert(bitsused <= OPERATION_MODIFIER_BITS);
if (0 && Log::isEnabled()) {
Log::out() << ::std::endl << "Opcode " << ::std::hex << (int) opcode << " and bits " << (int) encoding
<< " decoded to Modifier " << (int) value << ::std::dec << ::std::endl;
}
assert(((U_32)encode(opcode, OPERATION_MODIFIER_BITS)) == encoding);
}
void Modifier::addEncoding(U_32 &encoded, U_32 &bitsused, U_32 mask,
U_32 minval, U_32 maxval,
U_32 isshiftedby,
U_32 bitstoencode) const
{
U_32 thisval = value & mask;
assert((minval <= thisval) && (thisval <= maxval));
U_32 encodedval = ((thisval - minval) >> isshiftedby) << bitsused;
encoded = encoded | encodedval ;
bitsused = bitsused + bitstoencode;
}
void Modifier::addDecoding(U_32 &encoding, U_32 &bitsused, U_32 mask,
U_32 minval, U_32 maxval,
U_32 isshiftedby,
U_32 bitstoencode)
{
U_32 maskedbits = (1 << bitstoencode)-1;
U_32 shifted = ((encoding >> bitsused) & maskedbits) << isshiftedby;
U_32 decoded = shifted + minval;
U_32 masked = decoded & mask;
assert(masked != 0);
value |= masked;
bitsused = bitsused + bitstoencode;
}
const char*
Operation::getModifierString() const {
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
switch (info.modifierKind) {
case MK::None:
return "";
case MK::Overflow_and_Exception:
{
enum OverflowModifier omod = getOverflowModifier();
enum ExceptionModifier emod = getExceptionModifier();
switch (emod) {
case Exception_Sometimes:
switch (omod) {
case Overflow_None: return "";
case Overflow_Signed: return ".ovf";
case Overflow_Unsigned: return ".ovf.un";
default: assert(0);
}
case Exception_Always:
switch (omod) {
case Overflow_None: assert(0);
case Overflow_Signed: return ".ovf.throw";
case Overflow_Unsigned: return ".ovf.un.throw";
default: assert(0);
}
case Exception_Never:
switch (omod) {
case Overflow_None: return "";
case Overflow_Signed: return ".ovf.safe";
case Overflow_Unsigned: return ".ovf.un.safe";
default: assert(0);
}
default: assert(0);
}
}
break;
case MK::Overflow_and_Exception_and_Strict:
{
enum OverflowModifier omod = getOverflowModifier();
enum ExceptionModifier emod = getExceptionModifier();
enum StrictModifier smod = getStrictModifier();
switch (emod) {
case Exception_Sometimes:
assert(smod == Strict_No);
switch (omod) {
case Overflow_None: return "";
case Overflow_Signed: return ".ovf";
case Overflow_Unsigned: return ".ovf.un";
default: assert(0);
}
case Exception_Always:
assert(smod == Strict_No);
switch (omod) {
case Overflow_None: assert(0);
case Overflow_Signed: return ".ovf.throw";
case Overflow_Unsigned: return ".ovf.un.throw";
default: assert(0);
}
case Exception_Never:
switch (omod) {
case Overflow_None:
switch (smod) {
case Strict_No:
return "";
case Strict_Yes:
return ".strict";
default:
assert(0);
}
return "";
case Overflow_Signed:
assert(smod == Strict_No);
return ".ovf.safe";
case Overflow_Unsigned:
assert(smod == Strict_No);
return ".ovf.un.safe";
default: assert(0);
}
default: assert(0);
}
}
break;
case MK::Signed:
{
enum SignedModifier smod = getSignedModifier();
switch (smod) {
case SignedOp: return "";
case UnsignedOp: return ".un";
default: assert(0);
}
}
break;
case MK::Signed_and_Strict:
{
enum SignedModifier smod = getSignedModifier();
enum StrictModifier stmod = getStrictModifier();
switch (smod) {
case SignedOp:
switch (stmod) {
case Strict_No: return "";
case Strict_Yes: return ".strict";
default: assert(0);
}
return "";
case UnsignedOp:
switch (stmod) {
case Strict_No: return "";
case Strict_Yes: return ".un.strict";
default: assert(0);
}
return ".un";
default: assert(0);
}
}
break;
case MK::Comparison:
{
enum ComparisonModifier mod = getComparisonModifier();
switch (mod) {
case Cmp_EQ: return "eq";
case Cmp_NE_Un: return "ne";
case Cmp_GT: return "gt";
case Cmp_GT_Un: return "gtu";
case Cmp_GTE: return "ge";
case Cmp_GTE_Un: return "geu";
case Cmp_Zero: return "z";
case Cmp_NonZero: return "nz";
default:
assert(0);
}
}
break;
case MK::ShiftMask:
{
enum ShiftMaskModifier shmod = getShiftMaskModifier();
switch (shmod) {
case ShiftMask_None: return "";
case ShiftMask_Masked: return ".mask";
default: assert(0);
}
}
break;
case MK::ShiftMask_and_Signed:
{
enum SignedModifier smod = getSignedModifier();
enum ShiftMaskModifier shmod = getShiftMaskModifier();
switch (smod) {
case SignedOp:
switch (shmod) {
case ShiftMask_None: return "";
case ShiftMask_Masked: return ".mask";
default: assert(0);
}
case UnsignedOp:
switch (shmod) {
case ShiftMask_None: return ".un";
case ShiftMask_Masked: return ".un.mask";
default: assert(0);
}
default: assert(0);
}
}
break;
case MK::Strict:
{
enum StrictModifier stmod = getStrictModifier();
switch (stmod) {
case Strict_Yes: return ".strict";
case Strict_No: return "";
default: assert(0);
}
}
break;
case MK::DefArg:
{
enum DefArgModifier damod = getDefArgModifier();
switch (damod) {
case DefArgNoModifier: return "";
case NonNullThisArg: return ".ths";
case SpecializedToExactType: return ".xt";
case DefArgBothModifiers: return ".ths.xt";
default: assert(0);
}
}
break;
case MK::Store:
{
enum StoreModifier smod = getStoreModifier();
switch (smod) {
case Store_NoWriteBarrier: return "";
case Store_WriteBarrier: return ".wb";
default: assert(0);
}
}
break;
case MK::Store_AutoCompress:
{
enum StoreModifier smod = getStoreModifier();
enum AutoCompressModifier acmod = getAutoCompressModifier();
switch (smod) {
case Store_NoWriteBarrier:
switch (acmod) {
case AutoCompress_Yes: return "";
case AutoCompress_No: return ".unc";
default: assert(0);
}
break;
case Store_WriteBarrier:
switch (acmod) {
case AutoCompress_Yes: return ".wb";
case AutoCompress_No: return ".wb.unc";
default: assert(0);
}
break;
default:
assert(0);
}
break;
}
case MK::AutoCompress_Speculative:
{
enum AutoCompressModifier acmod = getAutoCompressModifier();
enum SpeculativeModifier smod = getSpeculativeModifier();
switch (acmod) {
case AutoCompress_Yes:
switch(smod) {
case Speculative_Yes: return ".s";
case Speculative_No: return "";
default: assert(false);
}
case AutoCompress_No:
switch(smod) {
case Speculative_Yes: return ".s.unc";
case Speculative_No: return ".unc";
default: assert(false);
}
default: assert(0);
}
break;
}
case MK::Exception:
{
enum ExceptionModifier emod = getExceptionModifier();
switch (emod) {
case Exception_Sometimes: return "";
case Exception_Always: return ".throw";
case Exception_Never: return ".safe";
default: assert(0);
}
break;
}
case MK::AutoCompress:
{
enum AutoCompressModifier acmod = getAutoCompressModifier();
switch (acmod) {
case AutoCompress_Yes: return "";
case AutoCompress_No: return ".unc";
default: assert(0);
}
break;
}
case MK::Throw:
{
// if this occurs in conjunction with other modifiers, then
// should modify a case above to check for it
enum ThrowModifier throwmod = getThrowModifier();
switch (throwmod) {
case Throw_NoModifier: return "";
case Throw_CreateStackTrace: return ".newtrace";
default: assert(0);
}
break;
}
case MK::NewModifier1:
{
// if this occurs in conjunction with other modifiers, then
// should modify a case above to check for it
enum NewModifier1 new1mod = getNewModifier1();
switch (new1mod) {
case NewModifier1_Value1: return ".new1v1";
case NewModifier1_Value2: return ".new1v2";
default: assert(0);
}
break;
}
case MK::NewModifier2:
{
// if this occurs in conjunction with other modifiers, then
// should modify a case above to check for it
enum NewModifier2 new2mod = getNewModifier2();
switch (new2mod) {
case NewModifier2_Value1: return ".new2v1";
case NewModifier2_Value2: return ".new2v2";
case NewModifier2_Value3: return ".new2v3";
default: assert(0);
}
break;
}
default:
assert(0);
}
assert(0);
return "ERROR";
}
const char*
Operation::getOpcodeString() const {
assert(opcode < NumOpcodes);
assert(opcodeTable[opcode].opcode == opcode);
const char* s = opcodeTable[opcode].opcodeString;
return s;
}
const char*
Operation::getOpcodeFormatString() const {
assert(opcode < NumOpcodes);
assert(opcodeTable[opcode].opcode == opcode);
const char* s = opcodeTable[opcode].opcodeFormatString;
return s;
}
bool Operation::canThrow() const
{
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
if ((info.mobility == MB::Exception) || (info.mobility == MB::Check)) {
return true;
}
if (opcode == Op_InitType) return true;
Modifier mod = getModifier();
if (mod.hasExceptionModifier()) {
enum ExceptionModifier emod = mod.getExceptionModifier();
if (emod != Exception_Never) return true;
}
return false;
}
bool Operation::isCheck() const
{
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
if ((info.mobility == MB::Check)) {
return true;
}
return false;
}
bool Operation::isMovable() const
{
if (canThrow()) return false;
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
switch (info.mobility) {
case MB::None: return false;
case MB::Movable: return true; // overflow case is handled above
case MB::CSEable: return false;
case MB::Check: return false;
case MB::Exception: return false;
case MB::StoreOrSync: return false;
case MB::Call: return false;
case MB::ControlFlow: return false;
case MB::MustEndBlock: return false;
case MB::Load: return false;
default: assert(0);
}
return false;
}
bool Operation::isCSEable() const {
assert(opcode < NumOpcodes);
assert(opcodeTable[opcode].opcode == opcode);
Mobility::Kind mobility = opcodeTable[opcode].mobility;
switch (mobility) {
case MB::Movable: // even operations with overflow are CSEable; first instance will throw
case MB::CSEable:
case MB::Check:
return true;
case MB::Load: // is CSEable for final fields, but we can't check that here.
default:
return false;
}
}
bool Operation::isStoreOrSync() const {
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
switch (info.mobility) {
case MB::Call:
case MB::StoreOrSync:
return true;
default:
break;
}
return false;
}
bool Operation::mustEndBlock() const {
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
switch (info.mobility) {
case MB::MustEndBlock:
case MB::Exception:
return true;
case MB::ControlFlow:
if (opcode == Op_Catch) return false;
return true;
case MB::CSEable:
if (opcode == Op_InitType) return true;
case MB::Call:
case MB::Movable:
case MB::Check:
case MB::StoreOrSync:
// must check Exception modifier
{
if (hasExceptionModifier()) {
enum ExceptionModifier exc = getExceptionModifier();
switch (exc) {
case Exception_Never:
return false;
case Exception_Sometimes:
case Exception_Always:
return true;
default:
assert(0);
}
} else
return false;
}
default:
return false;
}
}
bool Operation::isLoad() const
{
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
return (info.mobility == MB::Load);
}
bool Operation::isNonEssential() const
{
assert(opcode < NumOpcodes);
const OpcodeInfo &info = opcodeTable[opcode];
assert(info.opcode == opcode);
if (info.essential) {
return false;
} else {
Modifier mod = getModifier();
if (mod.hasExceptionModifier()) {
enum ExceptionModifier emod = mod.getExceptionModifier();
if (emod != Exception_Never) {
return false;
}
}
return true;
}
}
bool Operation::isConstant() const
{
switch (opcode) {
case Op_LdConstant:
case Op_LdRef:
case Op_LdVarAddr:
case Op_GetVTableAddr:
case Op_LdFieldOffset:
case Op_LdFieldOffsetPlusHeapbase:
case Op_LdArrayBaseOffset:
case Op_LdArrayBaseOffsetPlusHeapbase:
case Op_LdArrayLenOffset:
case Op_LdArrayLenOffsetPlusHeapbase:
return true;
default:
return false;
}
}
} //namespace Jitrino
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// 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:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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 H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_HWLOC_HPP
#define KOKKOS_HWLOC_HPP
#include <utility>
namespace Kokkos {
/** \brief Minimal subset of logical 'hwloc' functionality available
* from http://www.open-mpi.org/projects/hwloc/.
*
* The calls are NOT thread safe in order to avoid mutexes,
* memory allocations, or other actions which could give the
* runtime system an opportunity to migrate the threads or
* touch allocated memory during the function calls.
*
* All calls to these functions should be performed by a thread
* when it has guaranteed exclusive access; e.g., for OpenMP
* within a 'critical' region.
*/
namespace hwloc {
/** \brief Query if hwloc is available */
bool available();
/** \brief Query number of available NUMA regions.
* This will be less than the hardware capacity
* if the MPI process is pinned to a NUMA region.
*/
unsigned get_available_numa_count();
/** \brief Query number of available cores per NUMA regions.
* This will be less than the hardware capacity
* if the MPI process is pinned to a set of cores.
*/
unsigned get_available_cores_per_numa();
/** \brief Query number of available "hard" threads per core; i.e., hyperthreads */
unsigned get_available_threads_per_core();
} /* namespace hwloc */
} /* namespace Kokkos */
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Internal functions for binding persistent spawned threads.
namespace Kokkos {
namespace hwloc {
/** \brief Recommend mapping of threads onto cores.
*
* If thread_count == 0 then choose and set a value.
* If use_numa_count == 0 then choose and set a value.
* If use_cores_per_numa == 0 then choose and set a value.
*
* Return 0 if asynchronous,
* Return 1 if synchronous and threads_coord[0] is process core
*/
unsigned thread_mapping( const char * const label ,
const bool allow_async ,
unsigned & thread_count ,
unsigned & use_numa_count ,
unsigned & use_cores_per_numa ,
std::pair<unsigned,unsigned> threads_coord[] );
/** \brief Query core-coordinate of the current thread
* with respect to the core_topology.
*
* As long as the thread is running within the
* process binding the following condition holds.
*
* core_coordinate.first < core_topology.first
* core_coordinate.second < core_topology.second
*/
std::pair<unsigned,unsigned> get_this_thread_coordinate();
/** \brief Bind the current thread to a core. */
bool bind_this_thread( const std::pair<unsigned,unsigned> );
/** \brief Can hwloc bind threads? */
bool can_bind_threads();
/** \brief Bind the current thread to one of the cores in the list.
* Set that entry to (~0,~0) and return the index.
* If binding fails return ~0.
*/
unsigned bind_this_thread( const unsigned coordinate_count ,
std::pair<unsigned,unsigned> coordinate[] );
/** \brief Unbind the current thread back to the original process binding */
bool unbind_this_thread();
} /* namespace hwloc */
} /* namespace Kokkos */
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#endif /* #define KOKKOS_HWLOC_HPP */
|
#include "DXUT.h"
#include "Resources.h"
void Resources::AddMeshList(LPD3DXMESH* object)
{
for (auto l : m_meshlist)
{
if (l == object) return;
}
m_meshlist.push_back(object);
}
void Resources::DeleteMeshList(LPD3DXMESH* object)
{
for (auto l : m_meshlist)
{
if (l == object)
{
m_meshlist.remove(object);
return;
}
}
}
void Resources::Release()
{
for (LPD3DXMESH* l : m_meshlist)
{
delete(l);
}
m_meshlist.clear();
}
|
#include "../bench/util.hpp"
#include <GLFW/glfw3.h>
#include <mapbox/geojson.hpp>
#include <mapbox/geojson_impl.hpp>
#include <mapbox/geojsonvt.hpp>
#include <memory>
using namespace mapbox::geojsonvt;
template <typename T>
void drawLine(const T points) {
glColor4f(1, 0, 0, 1);
glBegin(GL_LINE_STRIP);
for (const auto& pt : points) {
glVertex2s(pt.x, pt.y);
}
glEnd();
}
struct DrawFeature {
void operator()(const mapbox::geometry::point<int16_t>&) {
}
void operator()(const mapbox::geometry::line_string<int16_t>& points) {
drawLine(points);
}
void operator()(const mapbox::geometry::linear_ring<int16_t>& points) {
drawLine(points);
}
void operator()(const mapbox::geometry::geometry<int16_t>& geometry) {
mapbox::geometry::geometry<int16_t>::visit(geometry, DrawFeature{});
}
template <class T>
void operator()(const T& vector) {
for (const auto& e : vector) {
operator()(e);
}
}
};
int main() {
if (glfwInit() == 0) {
return -1;
}
static int width = 768;
static int fbWidth = width;
static int height = 768;
static int fbHeight = height;
GLFWwindow* window =
glfwCreateWindow(width, height, "GeoJSON VT — Drop a GeoJSON file", nullptr, nullptr);
if (window == nullptr) {
glfwTerminate();
return -1;
}
static std::unique_ptr<GeoJSONVT> vt;
static bool dirty = true;
static struct TileID {
int z;
int x;
int y;
} pos = { 0, 0, 0 };
enum class Horizontal { Left, Right, Outside };
enum class Vertical { Top, Bottom, Outside };
static Horizontal horizontal = Horizontal::Outside;
static Vertical vertical = Vertical::Outside;
Tile* tile = nullptr;
static const auto updateTile = [&] {
const std::string name =
std::to_string(pos.z) + "/" + std::to_string(pos.x) + "/" + std::to_string(pos.y);
if (vt) {
Timer tileTimer;
tile = const_cast<Tile*>(&vt->getTile(pos.z, pos.x, pos.y));
tileTimer("tile " + name);
glfwSetWindowTitle(window, (std::string{ "GeoJSON VT — " } + name).c_str());
}
dirty = true;
};
static const auto loadGeoJSON = [&](const std::string& filename) {
Timer timer;
const std::string data = loadFile(filename);
timer("loadFile");
const auto features =
mapbox::geojson::parse(data).get<mapbox::geojson::feature_collection>();
timer("parse into geometry");
vt = std::make_unique<GeoJSONVT>(features);
timer("generate tile index");
updateTile();
};
static const auto updateLocation = [](const Horizontal newHorizontal,
const Vertical newVertical) {
if (newHorizontal != horizontal || newVertical != vertical) {
dirty = true;
horizontal = newHorizontal;
vertical = newVertical;
}
};
glfwSetDropCallback(window, [](GLFWwindow*, int count, const char* name[]) {
if (count >= 1) {
loadGeoJSON(name[0]);
}
});
glfwSetKeyCallback(
window, [](GLFWwindow* w, const int key, const int, const int action, const int) {
if (key == GLFW_KEY_Q && action == GLFW_RELEASE) {
glfwSetWindowShouldClose(w, 1);
}
if ((key == GLFW_KEY_BACKSPACE || key == GLFW_KEY_ESCAPE) && action == GLFW_RELEASE) {
// zoom out
if (pos.z > 0) {
pos.z--;
pos.x /= 2;
pos.y /= 2;
updateTile();
}
}
});
glfwSetWindowSizeCallback(window, [](GLFWwindow*, const int w, const int h) {
width = w;
height = h;
dirty = true;
});
glfwSetFramebufferSizeCallback(window, [](GLFWwindow*, const int w, const int h) {
fbWidth = w;
fbHeight = h;
});
glfwSetCursorPosCallback(window, [](GLFWwindow*, const double x, const double y) {
updateLocation((x > 0 && x < width) ? (x * 2 < width ? Horizontal::Left : Horizontal::Right)
: Horizontal::Outside,
(y > 0 && y < height) ? (y * 2 < height ? Vertical::Top : Vertical::Bottom)
: Vertical::Outside);
});
glfwSetCursorEnterCallback(window, [](GLFWwindow*, int entered) {
if (entered == 0) {
updateLocation(Horizontal::Outside, Vertical::Outside);
}
});
glfwSetMouseButtonCallback(window, [](GLFWwindow*, int button, int action, int) {
if (button == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {
// zoom into a particular tile
if (pos.z < 18 && horizontal != Horizontal::Outside && vertical != Vertical::Outside) {
pos.z++;
pos.x *= 2;
pos.y *= 2;
if (horizontal == Horizontal::Right) {
pos.x++;
}
if (vertical == Vertical::Bottom) {
pos.y++;
}
updateTile();
}
} else if (button == GLFW_MOUSE_BUTTON_2 && action == GLFW_RELEASE) {
// zoom out
if (pos.z > 0) {
pos.z--;
pos.x /= 2;
pos.y /= 2;
updateTile();
}
}
});
glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
glfwMakeContextCurrent(window);
const auto drawTile = [](bool active) {
if (active) {
glLineWidth(2);
glColor4f(0, 0, 1, 1);
} else {
glLineWidth(1);
glColor4f(0, 1, 0, 1);
}
glBegin(GL_LINE_STRIP);
glVertex3f(0, 0, -static_cast<int>(active));
glVertex3f(0, 4096, -static_cast<int>(active));
glVertex3f(4096, 4096, -static_cast<int>(active));
glVertex3f(4096, 0, -static_cast<int>(active));
glVertex3f(0, 0, -static_cast<int>(active));
glEnd();
};
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
loadGeoJSON("data/countries.geojson");
while (glfwWindowShouldClose(window) == 0) {
if (dirty) {
dirty = false;
if (vt) {
glClearColor(1, 1, 1, 1);
} else {
glClearColor(0.8, 0.8, 0.8, 1);
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, fbWidth, fbHeight);
if (tile != nullptr) {
// main tile
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-128, 4096 + 128, 4096 + 128, -128, 10, -10);
glLineWidth(1);
for (const auto& feature : tile->features) {
mapbox::geometry::geometry<int16_t>::visit(feature.geometry, DrawFeature{});
}
// top left
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-256, 8192 + 256, 8192 + 256, -256, 10, -10);
drawTile(horizontal == Horizontal::Left && vertical == Vertical::Top);
// top right
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256, -256, 10, -10);
drawTile(horizontal == Horizontal::Right && vertical == Vertical::Top);
// bottom left
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-256, 8192 + 256, 8192 + 256 - 4096, -256 - 4096, 10, -10);
drawTile(horizontal == Horizontal::Left && vertical == Vertical::Bottom);
// bottom right
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-4096 - 256, 8192 + 256 - 4096, 8192 + 256 - 4096, -256 - 4096, 10, -10);
drawTile(horizontal == Horizontal::Right && vertical == Vertical::Bottom);
} else {
}
glfwSwapBuffers(window);
}
glfwWaitEvents();
}
glfwTerminate();
return 0;
}
|
#include <iostream>
using namespace std;
class Term {
};
class None : Term {
};
class Var : Term {
Term val=(Term)*this;
};
class Atomic : Term {
string val;
};
class Pair : Term {
Term* left;
Term* right;
};
//Term :: *Term deref() {
// return this;
//};
int main () {
string s="hello";
cout << s << "\n";
cout << sizeof(Pair) << "\n";
return 0;
};
|
//===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the IdentifierInfo, IdentifierVisitor, and
// IdentifierTable interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <string>
using namespace clang;
//===----------------------------------------------------------------------===//
// IdentifierTable Implementation
//===----------------------------------------------------------------------===//
IdentifierIterator::~IdentifierIterator() = default;
IdentifierInfoLookup::~IdentifierInfoLookup() = default;
namespace {
/// A simple identifier lookup iterator that represents an
/// empty sequence of identifiers.
class EmptyLookupIterator : public IdentifierIterator
{
public:
StringRef Next() override { return StringRef(); }
};
} // namespace
IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
return new EmptyLookupIterator();
}
IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
: HashTable(8192), // Start with space for 8K identifiers.
ExternalLookup(ExternalLookup) {}
IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
IdentifierInfoLookup *ExternalLookup)
: IdentifierTable(ExternalLookup) {
// Populate the identifier table with info about keywords for the current
// language.
AddKeywords(LangOpts);
}
//===----------------------------------------------------------------------===//
// Language Keyword Implementation
//===----------------------------------------------------------------------===//
// Constants for TokenKinds.def
namespace {
enum {
KEYC99 = 0x1,
KEYCXX = 0x2,
KEYCXX11 = 0x4,
KEYGNU = 0x8,
KEYMS = 0x10,
BOOLSUPPORT = 0x20,
KEYALTIVEC = 0x40,
KEYNOCXX = 0x80,
KEYBORLAND = 0x100,
KEYOPENCLC = 0x200,
KEYC11 = 0x400,
KEYNOMS18 = 0x800,
KEYNOOPENCL = 0x1000,
WCHARSUPPORT = 0x2000,
HALFSUPPORT = 0x4000,
CHAR8SUPPORT = 0x8000,
KEYCONCEPTS = 0x10000,
KEYOBJC = 0x20000,
KEYZVECTOR = 0x40000,
KEYCOROUTINES = 0x80000,
KEYMODULES = 0x100000,
KEYCXX2A = 0x200000,
KEYOPENCLCXX = 0x400000,
KEYMSCOMPAT = 0x800000,
KEYSCAF = 0x1000000,
KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A,
KEYALL = (0xffffff & ~KEYNOMS18 &
~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
};
/// How a keyword is treated in the selected standard.
enum KeywordStatus {
KS_Disabled, // Disabled
KS_Extension, // Is an extension
KS_Enabled, // Enabled
KS_Future // Is a keyword in future standard
};
} // namespace
/// Translates flags as specified in TokenKinds.def into keyword status
/// in the given language standard.
static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
unsigned Flags) {
if (Flags == KEYALL) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled;
if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled;
if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
if (LangOpts.Scaffold && (Flags & KEYSCAF)) return KS_Extension;
if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled;
if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC))
return KS_Enabled;
if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled;
if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
// We treat bridge casts as objective-C keywords so we can warn on them
// in non-arc mode.
if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled;
if (LangOpts.CPlusPlus2a && (Flags & KEYCONCEPTS)) return KS_Enabled;
if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled;
if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
return KS_Disabled;
}
/// AddKeyword - This method is used to associate a token ID with specific
/// identifiers because they are language keywords. This causes the lexer to
/// automatically map matching identifiers to specialized token codes.
static void AddKeyword(StringRef Keyword,
tok::TokenKind TokenCode, unsigned Flags,
const LangOptions &LangOpts, IdentifierTable &Table) {
KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
// Don't add this keyword under MSVCCompat.
if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
return;
// Don't add this keyword under OpenCL.
if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
return;
// Don't add this keyword if disabled in this language.
if (AddResult == KS_Disabled) return;
IdentifierInfo &Info =
Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
Info.setIsExtensionToken(AddResult == KS_Extension);
Info.setIsFutureCompatKeyword(AddResult == KS_Future);
}
/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
/// representations.
static void AddCXXOperatorKeyword(StringRef Keyword,
tok::TokenKind TokenCode,
IdentifierTable &Table) {
IdentifierInfo &Info = Table.get(Keyword, TokenCode);
Info.setIsCPlusPlusOperatorKeyword();
}
/// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
/// or "property".
static void AddObjCKeyword(StringRef Name,
tok::ObjCKeywordKind ObjCID,
IdentifierTable &Table) {
Table.get(Name).setObjCKeywordID(ObjCID);
}
/// AddKeywords - Add all keywords to the symbol table.
///
void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
// Add keywords and tokens for the current language.
#define KEYWORD(NAME, FLAGS) \
AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
FLAGS, LangOpts, *this);
#define ALIAS(NAME, TOK, FLAGS) \
AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
FLAGS, LangOpts, *this);
#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
if (LangOpts.CXXOperatorNames) \
AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
#define OBJC_AT_KEYWORD(NAME) \
if (LangOpts.ObjC) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define TESTING_KEYWORD(NAME, FLAGS)
#include "clang/Basic/TokenKinds.def"
if (LangOpts.ParseUnknownAnytype)
AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
LangOpts, *this);
if (LangOpts.DeclSpecKeyword)
AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
// Add the 'import' contextual keyword.
get("import").setModulesImport(true);
}
/// Checks if the specified token kind represents a keyword in the
/// specified language.
/// \returns Status of the keyword in the language.
static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
tok::TokenKind K) {
switch (K) {
#define KEYWORD(NAME, FLAGS) \
case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
#include "clang/Basic/TokenKinds.def"
default: return KS_Disabled;
}
}
/// Returns true if the identifier represents a keyword in the
/// specified language.
bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
switch (getTokenKwStatus(LangOpts, getTokenID())) {
case KS_Enabled:
case KS_Extension:
return true;
default:
return false;
}
}
/// Returns true if the identifier represents a C++ keyword in the
/// specified language.
bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
return false;
// This is a C++ keyword if this identifier is not a keyword when checked
// using LangOptions without C++ support.
LangOptions LangOptsNoCPP = LangOpts;
LangOptsNoCPP.CPlusPlus = false;
LangOptsNoCPP.CPlusPlus11 = false;
LangOptsNoCPP.CPlusPlus2a = false;
return !isKeyword(LangOptsNoCPP);
}
tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
// We use a perfect hash function here involving the length of the keyword,
// the first and third character. For preprocessor ID's there are no
// collisions (if there were, the switch below would complain about duplicate
// case values). Note that this depends on 'if' being null terminated.
#define HASH(LEN, FIRST, THIRD) \
(LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
#define CASE(LEN, FIRST, THIRD, NAME) \
case HASH(LEN, FIRST, THIRD): \
return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
unsigned Len = getLength();
if (Len < 2) return tok::pp_not_keyword;
const char *Name = getNameStart();
switch (HASH(Len, Name[0], Name[2])) {
default: return tok::pp_not_keyword;
CASE( 2, 'i', '\0', if);
CASE( 4, 'e', 'i', elif);
CASE( 4, 'e', 's', else);
CASE( 4, 'l', 'n', line);
CASE( 4, 's', 'c', sccs);
CASE( 5, 'e', 'd', endif);
CASE( 5, 'e', 'r', error);
CASE( 5, 'i', 'e', ident);
CASE( 5, 'i', 'd', ifdef);
CASE( 5, 'u', 'd', undef);
CASE( 6, 'a', 's', assert);
CASE( 6, 'd', 'f', define);
CASE( 6, 'i', 'n', ifndef);
CASE( 6, 'i', 'p', import);
CASE( 6, 'p', 'a', pragma);
CASE( 7, 'd', 'f', defined);
CASE( 7, 'i', 'c', include);
CASE( 7, 'w', 'r', warning);
CASE( 8, 'u', 'a', unassert);
CASE(12, 'i', 'c', include_next);
CASE(14, '_', 'p', __public_macro);
CASE(15, '_', 'p', __private_macro);
CASE(16, '_', 'i', __include_macros);
#undef CASE
#undef HASH
}
}
//===----------------------------------------------------------------------===//
// Stats Implementation
//===----------------------------------------------------------------------===//
/// PrintStats - Print statistics about how well the identifier table is doing
/// at hashing identifiers.
void IdentifierTable::PrintStats() const {
unsigned NumBuckets = HashTable.getNumBuckets();
unsigned NumIdentifiers = HashTable.getNumItems();
unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
unsigned AverageIdentifierSize = 0;
unsigned MaxIdentifierLength = 0;
// TODO: Figure out maximum times an identifier had to probe for -stats.
for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
unsigned IdLen = I->getKeyLength();
AverageIdentifierSize += IdLen;
if (MaxIdentifierLength < IdLen)
MaxIdentifierLength = IdLen;
}
fprintf(stderr, "\n*** Identifier Table Stats:\n");
fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
NumIdentifiers/(double)NumBuckets);
fprintf(stderr, "Ave identifier length: %f\n",
(AverageIdentifierSize/(double)NumIdentifiers));
fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
// Compute statistics about the memory allocated for identifiers.
HashTable.getAllocator().PrintStats();
}
//===----------------------------------------------------------------------===//
// SelectorTable Implementation
//===----------------------------------------------------------------------===//
unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
}
namespace clang {
/// One of these variable length records is kept for each
/// selector containing more than one keyword. We use a folding set
/// to unique aggregate names (keyword selectors in ObjC parlance). Access to
/// this class is provided strictly through Selector.
class alignas(IdentifierInfoAlignment) MultiKeywordSelector
: public detail::DeclarationNameExtra,
public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
public:
// Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
: DeclarationNameExtra(nKeys) {
assert((nKeys > 1) && "not a multi-keyword selector");
// Fill in the trailing keyword array.
IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
for (unsigned i = 0; i != nKeys; ++i)
KeyInfo[i] = IIV[i];
}
// getName - Derive the full selector name and return it.
std::string getName() const;
using DeclarationNameExtra::getNumArgs;
using keyword_iterator = IdentifierInfo *const *;
keyword_iterator keyword_begin() const {
return reinterpret_cast<keyword_iterator>(this + 1);
}
keyword_iterator keyword_end() const {
return keyword_begin() + getNumArgs();
}
IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
return keyword_begin()[i];
}
static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
unsigned NumArgs) {
ID.AddInteger(NumArgs);
for (unsigned i = 0; i != NumArgs; ++i)
ID.AddPointer(ArgTys[i]);
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, keyword_begin(), getNumArgs());
}
};
} // namespace clang.
bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
assert(!Names.empty() && "must have >= 1 selector slots");
if (getNumArgs() != Names.size())
return false;
for (unsigned I = 0, E = Names.size(); I != E; ++I) {
if (getNameForSlot(I) != Names[I])
return false;
}
return true;
}
bool Selector::isUnarySelector(StringRef Name) const {
return isUnarySelector() && getNameForSlot(0) == Name;
}
unsigned Selector::getNumArgs() const {
unsigned IIF = getIdentifierInfoFlag();
if (IIF <= ZeroArg)
return 0;
if (IIF == OneArg)
return 1;
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getNumArgs();
}
IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
if (getIdentifierInfoFlag() < MultiArg) {
assert(argIndex == 0 && "illegal keyword index");
return getAsIdentifierInfo();
}
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getIdentifierInfoForSlot(argIndex);
}
StringRef Selector::getNameForSlot(unsigned int argIndex) const {
IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
return II ? II->getName() : StringRef();
}
std::string MultiKeywordSelector::getName() const {
SmallString<256> Str;
llvm::raw_svector_ostream OS(Str);
for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
if (*I)
OS << (*I)->getName();
OS << ':';
}
return OS.str();
}
std::string Selector::getAsString() const {
if (InfoPtr == 0)
return "<null selector>";
if (getIdentifierInfoFlag() < MultiArg) {
IdentifierInfo *II = getAsIdentifierInfo();
if (getNumArgs() == 0) {
assert(II && "If the number of arguments is 0 then II is guaranteed to "
"not be null.");
return II->getName();
}
if (!II)
return ":";
return II->getName().str() + ":";
}
// We have a multiple keyword selector.
return getMultiKeywordSelector()->getName();
}
void Selector::print(llvm::raw_ostream &OS) const {
OS << getAsString();
}
LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
/// Interpreting the given string using the normal CamelCase
/// conventions, determine whether the given string starts with the
/// given "word", which is assumed to end in a lowercase letter.
static bool startsWithWord(StringRef name, StringRef word) {
if (name.size() < word.size()) return false;
return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
name.startswith(word));
}
ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OMF_None;
StringRef name = first->getName();
if (sel.isUnarySelector()) {
if (name == "autorelease") return OMF_autorelease;
if (name == "dealloc") return OMF_dealloc;
if (name == "finalize") return OMF_finalize;
if (name == "release") return OMF_release;
if (name == "retain") return OMF_retain;
if (name == "retainCount") return OMF_retainCount;
if (name == "self") return OMF_self;
if (name == "initialize") return OMF_initialize;
}
if (name == "performSelector" || name == "performSelectorInBackground" ||
name == "performSelectorOnMainThread")
return OMF_performSelector;
// The other method families may begin with a prefix of underscores.
while (!name.empty() && name.front() == '_')
name = name.substr(1);
if (name.empty()) return OMF_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "alloc")) return OMF_alloc;
break;
case 'c':
if (startsWithWord(name, "copy")) return OMF_copy;
break;
case 'i':
if (startsWithWord(name, "init")) return OMF_init;
break;
case 'm':
if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
break;
case 'n':
if (startsWithWord(name, "new")) return OMF_new;
break;
default:
break;
}
return OMF_None;
}
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OIT_None;
StringRef name = first->getName();
if (name.empty()) return OIT_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "array")) return OIT_Array;
break;
case 'd':
if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
break;
case 's':
if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
if (startsWithWord(name, "standard")) return OIT_Singleton;
break;
case 'i':
if (startsWithWord(name, "init")) return OIT_Init;
break;
default:
break;
}
return OIT_None;
}
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return SFF_None;
StringRef name = first->getName();
switch (name.front()) {
case 'a':
if (name == "appendFormat") return SFF_NSString;
break;
case 'i':
if (name == "initWithFormat") return SFF_NSString;
break;
case 'l':
if (name == "localizedStringWithFormat") return SFF_NSString;
break;
case 's':
if (name == "stringByAppendingFormat" ||
name == "stringWithFormat") return SFF_NSString;
break;
}
return SFF_None;
}
namespace {
struct SelectorTableImpl {
llvm::FoldingSet<MultiKeywordSelector> Table;
llvm::BumpPtrAllocator Allocator;
};
} // namespace
static SelectorTableImpl &getSelectorTableImpl(void *P) {
return *static_cast<SelectorTableImpl*>(P);
}
SmallString<64>
SelectorTable::constructSetterName(StringRef Name) {
SmallString<64> SetterName("set");
SetterName += Name;
SetterName[3] = toUppercase(SetterName[3]);
return SetterName;
}
Selector
SelectorTable::constructSetterSelector(IdentifierTable &Idents,
SelectorTable &SelTable,
const IdentifierInfo *Name) {
IdentifierInfo *SetterName =
&Idents.get(constructSetterName(Name->getName()));
return SelTable.getUnarySelector(SetterName);
}
std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
StringRef Name = Sel.getNameForSlot(0);
assert(Name.startswith("set") && "invalid setter name");
return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
}
size_t SelectorTable::getTotalMemory() const {
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
return SelTabImpl.Allocator.getTotalMemory();
}
Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
if (nKeys < 2)
return Selector(IIV[0], nKeys);
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
// Unique selector, to guarantee there is one per name.
llvm::FoldingSetNodeID ID;
MultiKeywordSelector::Profile(ID, IIV, nKeys);
void *InsertPos = nullptr;
if (MultiKeywordSelector *SI =
SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
return Selector(SI);
// MultiKeywordSelector objects are not allocated with new because they have a
// variable size array (for parameter types) at the end of them.
unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
MultiKeywordSelector *SI =
(MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
Size, alignof(MultiKeywordSelector));
new (SI) MultiKeywordSelector(nKeys, IIV);
SelTabImpl.Table.InsertNode(SI, InsertPos);
return Selector(SI);
}
SelectorTable::SelectorTable() {
Impl = new SelectorTableImpl();
}
SelectorTable::~SelectorTable() {
delete &getSelectorTableImpl(Impl);
}
const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
switch (Operator) {
case OO_None:
case NUM_OVERLOADED_OPERATORS:
return nullptr;
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case OO_##Name: return Spelling;
#include "clang/Basic/OperatorKinds.def"
}
llvm_unreachable("Invalid OverloadedOperatorKind!");
}
StringRef clang::getNullabilitySpelling(NullabilityKind kind,
bool isContextSensitive) {
switch (kind) {
case NullabilityKind::NonNull:
return isContextSensitive ? "nonnull" : "_Nonnull";
case NullabilityKind::Nullable:
return isContextSensitive ? "nullable" : "_Nullable";
case NullabilityKind::Unspecified:
return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
}
llvm_unreachable("Unknown nullability kind.");
}
|
#include <bits/stdc++.h>
using namespace std;
int prepross(string a,string b,int i)
{
int n=a.length();
if(n%2==0)
{
if(b[i]==b[n-1-i])
{
if(a[i]==a[n-1-i]) return 0;
else return 1;
}
else
{
if(a[i]==b[i]&&a[n-1-i]==b[n-1-i]) return 0;
else if(a[i]==b[n-1-i]&&a[n-1-i]==b[i]) return 0;
else if(a[i]==b[i]&&a[n-1-i]!=b[n-1-i]) return 1;
else if(a[i]==b[n-1-i]&&a[n-1-i]!=b[i]) return 1;
else if(a[i]!=b[i]&&a[n-1-i]==b[n-1-i]) return 1;
else if(a[i]!=b[n-1-i]&&a[n-1-i]==b[i]) return 1;
else return 2;
}
}
else
{
if(i==(n-1)/2)
{
if(a[i]==b[i]) return 0;
else return 1;
}
else
{
if(b[i]==b[n-1-i])
{
if(a[i]==a[n-1-i]) return 0;
else return 1;
}
else
{
if(a[i]==b[i]&&a[n-1-i]==b[n-1-i]) return 0;
else if(a[i]==b[n-1-i]&&a[n-1-i]==b[i]) return 0;
else if(a[i]==b[i]&&a[n-1-i]!=b[n-1-i]) return 1;
else if(a[i]==b[n-1-i]&&a[n-1-i]!=b[i]) return 1;
else if(a[i]!=b[i]&&a[n-1-i]==b[n-1-i]) return 1;
else if(a[i]!=b[n-1-i]&&a[n-1-i]==b[i]) return 1;
else return 2;
}
}
}
}
int main()
{
int n;
scanf("%d",&n);
string a;
string b;
cin>>a;
cin>>b;
int s=0;
for(int i=0;i<=(n-1)/2;i++)
{
s=s+prepross(a,b,i);
}
printf("%d",s);
return 0;
}
|
#include "IEntity_API.h"
uint16_t alt_IEntity_GetID(uintptr_t entityPointer) {
auto* entity = dynamic_cast<alt::IEntity*>(reinterpret_cast<alt::IBaseObject*>(entityPointer));
return entity->GetID();
}
uint32_t alt_IEntity_GetModel(uintptr_t entityPointer) {
auto* entity = dynamic_cast<alt::IEntity*>(reinterpret_cast<alt::IBaseObject*>(entityPointer));
return entity->GetModel();
}
|
#include "Log.h"
namespace LFHE
{
std::shared_ptr<spdlog::logger> Log::s_CoreLogger;
std::shared_ptr<spdlog::logger> Log::s_ClientLogger;
void Log::Init()
{
//[%T] timestamp
//%n: name logger
//%v%$ log message
spdlog::set_pattern("%^[%T] %n: %v%$");
s_CoreLogger = spdlog::stdout_color_mt("LFHE");
s_CoreLogger->set_level(spdlog::level::trace);
s_ClientLogger = spdlog::stdout_color_mt("APP");
s_ClientLogger->set_level(spdlog::level::trace);
}
}
|
#include "c_b2ChainShape.h"
extern "C" {
b2ChainShape* b2ChainShape_New() {
return new b2ChainShape;
}
void b2ChainShape_Delete(b2ChainShape* self) {
delete self;
}
b2Shape* b2ChainShape_Upcast(b2ChainShape* self) {
return static_cast<b2Shape*>(reinterpret_cast<b2ChainShape*>(self));
}
void b2ChainShape_CreateChain(b2ChainShape* self, const b2Vec2* vertices, int32 count) {
self->CreateChain(vertices, count);
}
int32 b2ChainShape_GetChildCount(b2ChainShape* self) {
return self->GetChildCount();
}
int32 b2ChainShape_m_count(b2ChainShape* self) {
return self->m_count;
}
b2Vec2* b2ChainShape_m_vertices(b2ChainShape* self) {
return self->m_vertices;
}
} // extern C
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sstream>
#include "nlohmann/json.hpp"
#include "parameter.h"
#include "dm_ability_manager.h"
#include "response_session.h"
#include "constants.h"
#include "msg_codec.h"
#include "device_manager_log.h"
#include "device_manager_errno.h"
#include "encrypt_utils.h"
#include "ipc_server_adapter.h"
#include "softbus_adapter.h"
#include "softbus_session.h"
#include "hichain_connector.h"
#include "pthread.h"
#include "ipc_server_adapter.h"
#include "dm_device_info.h"
#include "ipc_server_listener_adapter.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
const int32_t SESSION_CANCEL_TIMEOUT = 0;
const int32_t SESSION_MSG_RECEIVE_TIMEOUT = 5;
const int32_t SESSION_WAIT_MEMBER_JOIN_TIMEOUT = 120;
const int32_t CANCEL_PICODE_DISPLAY = 1;
const int32_t DEVICE_ID_HALF = 2;
}
ResponseSession::ResponseSession()
{
mSessionStatus_ = ResponseSessionStatus::SESSION_INIT;
sem_init(&mSem_, 0, 0);
}
int64_t ResponseSession::GetRequestId()
{
return mRequestId_;
}
int32_t ResponseSession::SendResponseMessage(int32_t reply)
{
DMLOG(DM_LOG_INFO, "ResponseSession::SendResponseMessage in, reply:%d", reply);
std::string msg;
if (reply == SESSION_REPLY_ACCEPT) {
msg = MsgCodec::EncodeAcceptRespAuth(reply, mRequestId_, mGroupId_, mGroupName_, mReqDeviceId_);
} else {
msg = MsgCodec::EncodeRefuseRespAuth(reply, mReqDeviceId_);
}
int32_t ret = SoftbusSession::GetInstance().SendMsg(mChannelId_, msg);
if (ret != SUCCESS) {
DMLOG(DM_LOG_INFO, "SendResponseMessage failed ret:%d, reply:%d", ret, reply);
return ret;
}
DMLOG(DM_LOG_INFO, "SendResponseMessage successed, reply:%d", reply);
return SUCCESS;
}
void ResponseSession::OnUserOperate(int32_t action)
{
switch (action) {
case FaAction::USER_OPERATION_TYPE_ALLOW_AUTH: {
OnUserConfirm();
break;
}
case FaAction::USER_OPERATION_TYPE_CANCEL_AUTH: {
OnUserReject(ERROR_USER_REJECT);
break;
}
case FaAction::USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: {
OnUserReject(SESSION_REPLY_AUTH_CONFIRM_TIMEOUT);
break;
}
case FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: {
DMLOG(DM_LOG_ERROR, "cancle pincode display");
Release();
break;
}
default: {
DMLOG(DM_LOG_ERROR, "action %d not support", action);
break;
}
}
}
int32_t ResponseSession::DecodeReqMsg(std::string &message)
{
std::shared_ptr<MsgRequestAuth> authMsg = MsgCodec::DecodeRequestAuth(message, mMsgRequestAuthPtr_);
if (authMsg == nullptr) {
DMLOG(DM_LOG_ERROR, "DecodeRequestAuth error, authMsg(nullptr)");
return FAIL;
}
if (authMsg->GetMsgSlice() == FAIL) {
DMLOG(DM_LOG_ERROR, "DecodeRequestAuth error, GetMsgSlice() FAIL");
return FAIL;
}
mMsgRequestAuthPtr_ = authMsg;
return SUCCESS;
}
bool ResponseSession::IsMyChannelId(long long channelId)
{
if (mSessionStatus_ == ResponseSessionStatus::SESSION_INIT) {
return true;
}
return channelId == mChannelId_ && mChannelId_ > 0;
}
void OnReceiveTimeOut(void *data)
{
DMLOG(DM_LOG_ERROR, "OnReceiveTimeOut TimeOut called");
ResponseSession *respSess = (ResponseSession*)data;
if (respSess == nullptr || respSess->GetStatus() == ResponseSessionStatus::SESSION_INIT) {
DMLOG(DM_LOG_ERROR, "respSess Status is INIT");
return;
}
respSess->Release();
}
void OnMemberJoinTimeOut(void *data)
{
DMLOG(DM_LOG_ERROR, "OnMemberJoinTimeOut TimeOut caled");
ResponseSession *respSess = (ResponseSession*)data;
if (respSess == nullptr || respSess->GetStatus() == ResponseSessionStatus::SESSION_INIT) {
DMLOG(DM_LOG_ERROR, "respSess Status is INIT");
return;
}
respSess->SendResponseMessage(SESSION_REPLY_TIMEOUT);
respSess->CancelDisplay();
respSess->Release();
}
void ResponseSession::OnReceiveMsg(long long channelId, std::string &message)
{
int32_t ret = DecodeReqMsg(message);
if (ret != SUCCESS) {
DMLOG(DM_LOG_ERROR, "DecodeReqMsg failed");
return;
}
if (!mReceiveTimerPtr_) {
std::string mReceiveTimerName = "mReceiveTimer";
mReceiveTimerPtr_ = std::make_shared<DmTimer>(mReceiveTimerName);
}
mReceiveTimerPtr_->Start(SESSION_MSG_RECEIVE_TIMEOUT, OnReceiveTimeOut, this);
if (mMsgRequestAuthPtr_->GetMsgCnt() != mMsgRequestAuthPtr_->GetMsgSlice()) {
return;
}
mReceiveTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT);
mReqDeviceId_ = mMsgRequestAuthPtr_->GetRequestDeviceId();
mChannelId_ = channelId;
mPincode_ = GeneratePincode();
if (StartFaService() != SUCCESS) {
OnUserReject(ERROR_FA_START_FAIL);
return;
}
mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM;
if (!mMemberJoinTimerPtr_) {
std::string mMemberJoinTimerName = "mMemberJoinTimer";
mMemberJoinTimerPtr_ = std::make_shared<DmTimer>(mMemberJoinTimerName);
}
mMemberJoinTimerPtr_->Start(SESSION_WAIT_MEMBER_JOIN_TIMEOUT, OnMemberJoinTimeOut, this);
}
int32_t ResponseSession::GetPinCodeByReqId(int64_t requestId)
{
if (requestId != mRequestId_) {
DMLOG(DM_LOG_ERROR, "ResponseSession:: GetPinCodeByReqId FAIL : requestId(not match)");
return FAIL;
}
return mPincode_;
}
void ResponseSession::BuildAuthenticationInfo(DmAuthParam &authParam)
{
DMLOG(DM_LOG_INFO, "ResponseSession::BuildAuthenticationInfo in");
authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole();
if (mMsgRequestAuthPtr_ == nullptr) {
DMLOG(DM_LOG_ERROR, "ResponseSession::BuildAuthenticationInfo mMsgRequestAuthPtr_ is nullptr");
return;
}
authParam.packageName = mMsgRequestAuthPtr_->mTargetPkg_;
authParam.appName = mMsgRequestAuthPtr_->mAppName_;
authParam.appDescription = mMsgRequestAuthPtr_->mAppDescription_;
authParam.authType = mMsgRequestAuthPtr_->mAuthType_;
authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION
authParam.pincode = mPincode_;
if (mMsgRequestAuthPtr_ != nullptr) {
uint8_t *appIcon = nullptr;
int32_t appIconLen = 0;
uint8_t *appThumbnail = nullptr;
int32_t appThumbnailLen = 0;
mMsgRequestAuthPtr_->GetDecodeAppInfo(mMsgRequestAuthPtr_->mAppIcon_, &appIcon, appIconLen);
mMsgRequestAuthPtr_->GetDecodeAppInfo(mMsgRequestAuthPtr_->mAppThumbnail_, &appThumbnail, appThumbnailLen);
authParam.imageinfo.Reset(appIcon, appIconLen, appThumbnail, appThumbnailLen);
if (appIcon != nullptr) {
free(appIcon);
appIcon = nullptr;
}
if (appThumbnail != nullptr) {
free(appThumbnail);
appThumbnail = nullptr;
}
}
}
int32_t ResponseSession::StartFaService()
{
DMLOG(DM_LOG_INFO, "ResponseSession::StartFaService in");
AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE);
if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) {
DMLOG(DM_LOG_ERROR, "ResponseSession::StartFaService timeout");
return FAIL;
}
return SUCCESS;
}
void ResponseSession::OnGroupCreated(int64_t requestId, const std::string &groupId)
{
DMLOG(DM_LOG_INFO, "ResponseSession OnGroupCreated in requestId= %lld groupId = %s ", requestId, groupId.c_str());
if (requestId != mRequestId_ || groupId.length() == 0) {
DMLOG(DM_LOG_ERROR, "ResponseSession::OnGroupCreated failed, requestId %lld, requestId %lld, groupId %s",
requestId, mRequestId_, groupId.c_str());
SendResponseMessage(SESSION_REPLY_CREAT_GROUP_FAILED);
CancelDisplay();
mSessionStatus_ = ResponseSessionStatus::SESSION_INIT;
return;
}
// save requestId for peer to join, need to be checked in HiChain OnRequest and OnFinish(AddMemberToGroup) callback
mRequestId_ = HichainConnector::GetInstance().GenRequestId();
mGroupId_ = groupId;
int32_t ret = SendResponseMessage(SESSION_REPLY_ACCEPT);
if (ret != SUCCESS) {
CancelDisplay();
mSessionStatus_ = ResponseSessionStatus::SESSION_INIT;
return;
}
DMLOG(DM_LOG_INFO, "Send Accept Resoponse success, wait for peer to AddMemberToGroup");
mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_PIN_CODE;
}
void ResponseSession::OnMemberJoin(int64_t requestId, int32_t status)
{
DMLOG(DM_LOG_INFO, "ResponseSession::OnMemberJoin, result: %d", status);
CancelDisplay();
mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT);
Release();
}
std::string ResponseSession::GenerateGroupName()
{
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
std::string sLocalDeviceID = localDeviceId;
std::string groupName = mMsgRequestAuthPtr_->mTargetPkg_ + mMsgRequestAuthPtr_->mHostPkg_ +
sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF);
return groupName;
}
void ResponseSession::OnUserConfirm()
{
DMLOG(DM_LOG_INFO, "ResponseSession::OnUserConfirm in");
mGroupName_ = GenerateGroupName();
HichainConnector::GetInstance().RegisterConnectorCallback(shared_from_this());
// save requestId for CreateGroup, need to be checked in callback: OnGroupCreated
mRequestId_ = HichainConnector::GetInstance().GenRequestId();
int32_t ret = HichainConnector::GetInstance().CreateGroup(mRequestId_, mGroupName_);
if (ret != SUCCESS) {
CancelDisplay();
mSessionStatus_ = ResponseSessionStatus::SESSION_INIT;
return;
}
mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_GROUP_CREATED;
}
void ResponseSession::OnUserReject(int32_t errorCode)
{
DMLOG(DM_LOG_INFO, "ResponseSession::OnUserReject in, errcode %d", errorCode);
SendResponseMessage(errorCode);
Release();
}
void ResponseSession::Release()
{
DMLOG(DM_LOG_INFO, "ResponseSession::Release in");
mSessionStatus_ = ResponseSessionStatus::SESSION_INIT;
mRequestId_ = -1;
mGroupId_ = "";
mGroupName_ = "";
mReqDeviceId_ = "";
mMsgRequestAuthPtr_ = nullptr;
mChannelId_ = -1;
mPincode_ = -1;
}
void ResponseSession::CancelDisplay()
{
DMLOG(DM_LOG_INFO, "Cancel PinCode Display in");
nlohmann::json jsonObj;
jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY;
std::string paramJson = jsonObj.dump();
std::string pkgName = "com.ohos.devicemanagerui";
IpcServerListenerAdapter::GetInstance().OnFaCall(pkgName, paramJson);
DMLOG(DM_LOG_INFO, "Cancel PinCode Display success");
}
int32_t ResponseSession::GetStatus()
{
return mSessionStatus_;
}
int32_t ResponseSession::GeneratePincode()
{
return EncryptUtils::GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
}
} // namespace DistributedHardware
} // namespace OHOS
|
#ifndef HEAP_PRIORITY_QUEUE
#define HEAP_PRIORITY_QUEUE
#include <utility>
#include <vector>
#include <stdexcept>
#include "../common_heap_utility.hpp"
#include "../max_min_heapify/max_min_heapify.hpp"
namespace CLRS
{
template <typename T>
// return reference or copy?
T heap_maximum(const std::vector<T> &a)
{
if(a.size() == 0)
throw(std::logic_error("this queue is empty"));
return a[0];
}
template <typename T>
T heap_extract_max(std::vector<T> &a)
{
if(a.size() == 0)
throw(std::underflow_error("heap underflow"));
T max = a[0];
a[0] = a.back();
a.pop_back();
CLRS::max_heapify(a, 0);
return max;
}
template <typename T>
void max_heap_increase_key(std::vector<T> &a, std::size_t i, T key)
{
if(key < a[i])
throw(std::logic_error("new key is smaller than current key"));
a[i] = key;
while(i > 0 && a[CLRS::parent(i)] < a[i])
{
T temp = a[CLRS::parent(i)];
a[CLRS::parent(i)] = a[i];
a[i] = temp;
i = CLRS::parent(i);
}
}
template <typename T>
void max_heap_insert(std::vector<T> &a, T key)
{
a.push_back(key);
max_heap_increase_key(a, a.size() - 1, key);
}
// for minimum heap priority queue
template <typename T>
// return reference or copy?
T heap_minimum(const std::vector<T> &a)
{
if(a.size() == 0)
throw(std::logic_error("this queue is empty"));
return a[0];
}
template <typename T>
T heap_extract_min(std::vector<T> &a)
{
if(a.size() == 0)
throw(std::underflow_error("heap underflow"));
T min = a[0];
a[0] = a.back();
a.pop_back();
CLRS::min_heapify(a, 0);
return min;
}
template <typename T>
void min_heap_increase_key(std::vector<T> &a, std::size_t i, T key)
{
if(key > a[i])
throw(std::logic_error("new key is larger than current key"));
a[i] = key;
while(i > 0 && a[CLRS::parent(i)] > a[i])
{
T temp = a[CLRS::parent(i)];
a[CLRS::parent(i)] = a[i];
a[i] = temp;
i = CLRS::parent(i);
}
}
template <typename T>
void min_heap_insert(std::vector<T> &a, T key)
{
a.push_back(key);
min_heap_increase_key(a, a.size() - 1, key);
}
}
#endif
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifndef itkParallelSparseFieldLevelSetImageFilter_hxx
#define itkParallelSparseFieldLevelSetImageFilter_hxx
#include "itkParallelSparseFieldLevelSetImageFilter.h"
#include "itkZeroCrossingImageFilter.h"
#include "itkShiftScaleImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkNeighborhoodAlgorithm.h"
#include <iostream>
#include <fstream>
#include "itkMath.h"
#include "itkPlatformMultiThreader.h"
namespace itk
{
template< typename TNeighborhoodType >
ParallelSparseFieldCityBlockNeighborList< TNeighborhoodType >
::ParallelSparseFieldCityBlockNeighborList()
{
using ImageType = typename NeighborhoodType::ImageType;
typename ImageType::Pointer dummy_image = ImageType::New();
unsigned int i, nCenter;
int d;
OffsetType zero_offset;
for ( i = 0; i < Dimension; ++i )
{
m_Radius[i] = 1;
zero_offset[i] = 0;
}
NeighborhoodType it( m_Radius, dummy_image, dummy_image->GetRequestedRegion() );
nCenter = it.Size() / 2;
m_Size = 2 * Dimension;
m_ArrayIndex.reserve(m_Size);
m_NeighborhoodOffset.reserve(m_Size);
for ( i = 0; i < m_Size; ++i )
{
m_NeighborhoodOffset.push_back(zero_offset);
}
for ( d = Dimension - 1, i = 0; d >= 0; --d, ++i )
{
m_ArrayIndex.push_back( nCenter - it.GetStride(d) );
m_NeighborhoodOffset[i][d] = -1;
}
for ( d = 0; d < static_cast< int >( Dimension ); ++d, ++i )
{
m_ArrayIndex.push_back( nCenter + it.GetStride(d) );
m_NeighborhoodOffset[i][d] = 1;
}
for ( i = 0; i < Dimension; ++i )
{
m_StrideTable[i] = it.GetStride(i);
}
}
template< typename TNeighborhoodType >
void
ParallelSparseFieldCityBlockNeighborList< TNeighborhoodType >
::Print(std::ostream & os) const
{
os << "ParallelSparseFieldCityBlockNeighborList: " << std::endl;
for ( unsigned i = 0; i < this->GetSize(); ++i )
{
os << "m_ArrayIndex[" << i << "]: " << m_ArrayIndex[i] << std::endl
<< "m_NeighborhoodOffset[" << i << "]: " << m_NeighborhoodOffset[i] << std::endl;
}
}
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::ValueType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_ValueOne = NumericTraits< typename ParallelSparseFieldLevelSetImageFilter<
TInputImage, TOutputImage >::ValueType >::OneValue();
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::ValueType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_ValueZero = NumericTraits< typename ParallelSparseFieldLevelSetImageFilter<
TInputImage, TOutputImage >::ValueType >::ZeroValue();
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::StatusType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_StatusNull = NumericTraits< typename ParallelSparseFieldLevelSetImageFilter<
TInputImage, TOutputImage >::StatusType >::NonpositiveMin();
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::StatusType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_StatusChanging = -1;
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::StatusType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_StatusActiveChangingUp = -2;
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::StatusType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_StatusActiveChangingDown = -3;
template< typename TInputImage, typename TOutputImage >
typename ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::StatusType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::m_StatusBoundaryPixel = -4;
template< typename TInputImage, typename TOutputImage >
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ParallelSparseFieldLevelSetImageFilter() :
m_NumberOfLayers(ImageDimension),
m_IsoSurfaceValue(m_ValueZero)
{
this->SetRMSChange( static_cast< double >( m_ValueOne ) );
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
if ( !this->m_IsInitialized )
{
// Clean up any memory from any aborted previous filter executions.
this->DeallocateData();
// Allocate the output image
m_OutputImage = this->GetOutput();
m_OutputImage->SetBufferedRegion( m_OutputImage->GetRequestedRegion() );
m_OutputImage->Allocate();
// Copy the input image to the output image. Algorithms will operate
// directly on the output image
this->CopyInputToOutput();
// Perform any other necessary pre-iteration initialization.
this->Initialize();
this->SetElapsedIterations(0);
//NOTE: Cannot set state to initialized yet since more initialization is
//done in the Iterate method.
}
// Evolve the surface
this->Iterate();
// Clean up
if ( this->GetManualReinitialization() == false )
{
this->DeallocateData();
// Reset the state once execution is completed
this->m_IsInitialized = false;
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::CopyInputToOutput()
{
// This method is the first step in initializing the level-set image, which
// is also the output of the filter. The input is passed through a
// zero crossing filter, which produces zero's at pixels closest to the zero
// level set and one's elsewhere. The actual zero level set values will be
// adjusted in the Initialize() step to more accurately represent the
// position of the zero level set.
// First need to subtract the iso-surface value from the input image.
using ShiftScaleFilterType = ShiftScaleImageFilter< InputImageType, OutputImageType >;
typename ShiftScaleFilterType::Pointer shiftScaleFilter = ShiftScaleFilterType::New();
shiftScaleFilter->SetInput( this->GetInput() );
shiftScaleFilter->SetShift(-m_IsoSurfaceValue);
// keep a handle to the shifted output
m_ShiftedImage = shiftScaleFilter->GetOutput();
typename ZeroCrossingImageFilter< OutputImageType, OutputImageType >::Pointer
zeroCrossingFilter = ZeroCrossingImageFilter< OutputImageType, OutputImageType >::New();
zeroCrossingFilter->SetInput(m_ShiftedImage);
zeroCrossingFilter->GraftOutput(m_OutputImage);
zeroCrossingFilter->SetBackgroundValue(m_ValueOne);
zeroCrossingFilter->SetForegroundValue(m_ValueZero);
zeroCrossingFilter->SetNumberOfWorkUnits(1);
zeroCrossingFilter->Update();
// Here the output is the result of zerocrossings
this->GraftOutput( zeroCrossingFilter->GetOutput() );
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::Initialize()
{
unsigned int i;
// A node pool used during initialization of the level set.
m_LayerNodeStore = LayerNodeStorageType::New();
m_LayerNodeStore->SetGrowthStrategyToExponential();
// Allocate the status image.
m_StatusImage = StatusImageType::New();
m_StatusImage->SetRegions( m_OutputImage->GetRequestedRegion() );
m_StatusImage->Allocate();
// Initialize the status image to contain all m_StatusNull values.
ImageRegionIterator< StatusImageType > statusIt( m_StatusImage,
m_StatusImage->GetRequestedRegion() );
for ( statusIt.GoToBegin(); !statusIt.IsAtEnd(); ++statusIt )
{
statusIt.Set(m_StatusNull);
}
// Initialize the boundary pixels in the status images to
// m_StatusBoundaryPixel values. Uses the face calculator to find all of the
// region faces.
using BFCType = NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< StatusImageType >;
BFCType faceCalculator;
typename BFCType::FaceListType faceList;
typename BFCType::SizeType sz;
typename BFCType::FaceListType::iterator fit;
sz.Fill(1);
faceList = faceCalculator(m_StatusImage, m_StatusImage->GetRequestedRegion(),
sz);
fit = faceList.begin();
for ( ++fit; fit != faceList.end(); ++fit ) // skip the first (nonboundary) region
{
statusIt = ImageRegionIterator< StatusImageType >(m_StatusImage, *fit);
for ( statusIt.GoToBegin(); !statusIt.IsAtEnd(); ++statusIt )
{
statusIt.Set(m_StatusBoundaryPixel);
}
}
// Allocate the layers of the sparse field.
m_Layers.reserve(2 * m_NumberOfLayers + 1);
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; ++i )
{
m_Layers.push_back( LayerType::New() );
}
// always the "Z" dimension
m_SplitAxis = m_OutputImage->GetImageDimension() - 1;
if ( m_OutputImage->GetImageDimension() < 1 )
{
// cannot split
itkDebugMacro ("Unable to choose an axis for workload distribution among threads");
return;
}
typename OutputImageType::SizeType requestedRegionSize =
m_OutputImage->GetRequestedRegion().GetSize();
m_ZSize = requestedRegionSize[m_SplitAxis];
// Histogram of number of pixels in each Z plane for the entire 3D volume
m_GlobalZHistogram = new int[m_ZSize];
for ( i = 0; i < m_ZSize; i++ )
{
m_GlobalZHistogram[i] = 0;
}
// Construct the active layer and initialize the first layers inside and
// outside of the active layer
this->ConstructActiveLayer();
// Construct the rest of the non active set layers using the first two
// layers. Inside layers are odd numbers, outside layers are even numbers.
for ( i = 1; i < m_Layers.size() - 2; ++i )
{
this->ConstructLayer(i, i + 2);
}
// Set the values in the output image for the active layer.
this->InitializeActiveLayerValues();
// Initialize layer values using the active layer as seeds.
this->PropagateAllLayerValues();
// Initialize pixels inside and outside the sparse field layers to positive
// and negative values, respectively. This is not necessary for the
// calculations, but is useful for presenting a more intuitive output to the
// filter. See PostProcessOutput method for more information.
this->InitializeBackgroundPixels();
m_NumOfThreads = std::min( this->GetNumberOfWorkUnits(),
this->GetMultiThreader()->GetMaximumNumberOfThreads() );
this->SetNumberOfWorkUnits( m_NumOfThreads );
// Cumulative frequency of number of pixels in each Z plane for the entire 3D
// volume
m_ZCumulativeFrequency = new int[m_ZSize];
for ( i = 0; i < m_ZSize; i++ )
{
m_ZCumulativeFrequency[i] = 0;
}
// The mapping from a z-value to the thread in whose region the z-value lies
m_MapZToThreadNumber = new unsigned int[m_ZSize];
for ( i = 0; i < m_ZSize; i++ )
{
m_MapZToThreadNumber[i] = 0;
}
// The boundaries defining thread regions
m_Boundary = new unsigned int[m_NumOfThreads];
for ( i = 0; i < m_NumOfThreads; i++ )
{
m_Boundary[i] = 0;
}
// A boolean variable stating if the boundaries had been changed during
// CheckLoadBalance()
m_BoundaryChanged = false;
// Allocate data for each thread.
m_Data = new ThreadData[m_NumOfThreads];
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ConstructActiveLayer()
{
// We find the active layer by searching for 0's in the zero crossing image
// (output image). The first inside and outside layers are also constructed
// by searching the neighbors of the active layer in the (shifted) input
// image.
// Negative neighbors not in the active set are assigned to the inside,
// positive neighbors are assigned to the outside.
NeighborhoodIterator< OutputImageType > shiftedIt( m_NeighborList.GetRadius(),
m_ShiftedImage, m_OutputImage->GetRequestedRegion() );
NeighborhoodIterator< OutputImageType > outputIt ( m_NeighborList.GetRadius(),
m_OutputImage, m_OutputImage->GetRequestedRegion() );
NeighborhoodIterator< StatusImageType > statusIt ( m_NeighborList.GetRadius(),
m_StatusImage, m_OutputImage->GetRequestedRegion() );
IndexType center_index, offset_index;
LayerNodeType *node;
bool bounds_status = true;
ValueType value;
StatusType layer_number;
typename OutputImageType::SizeType regionSize =
m_OutputImage->GetRequestedRegion().GetSize();
typename OutputImageType::IndexType startIndex =
m_OutputImage->GetRequestedRegion().GetIndex();
using StartIndexValueType = IndexValueType;
for ( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
{
bounds_status = true;
if ( Math::ExactlyEquals(outputIt.GetCenterPixel(), m_ValueZero) )
{
// Grab the neighborhood in the status image.
center_index = outputIt.GetIndex();
statusIt.SetLocation(center_index);
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( ( center_index[j] ) <= ( startIndex[j] )
|| ( center_index[j] ) >= startIndex[j]
+ static_cast< StartIndexValueType >( regionSize[j] - 1 ) )
{
bounds_status = false;
break;
}
}
if ( bounds_status == true )
{
// Here record the hisgram information
m_GlobalZHistogram[center_index[m_SplitAxis]]++;
// Borrow a node from the store and set its value.
node = m_LayerNodeStore->Borrow();
node->m_Index = center_index;
// Add the node to the active list and set the status in the status
// image.
m_Layers[0]->PushFront(node);
statusIt.SetCenterPixel(0);
// Grab the neighborhood in the image of shifted input values.
shiftedIt.SetLocation(center_index);
// Search the neighborhood pixels for first inside & outside layer
// members. Construct these lists and set status list values.
for ( unsigned int i = 0; i < m_NeighborList.GetSize(); ++i )
{
offset_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
if ( Math::NotExactlyEquals(outputIt.GetPixel( m_NeighborList.GetArrayIndex(i) ), m_ValueZero)
&& statusIt.GetPixel( m_NeighborList.GetArrayIndex(i) ) == m_StatusNull )
{
value = shiftedIt.GetPixel( m_NeighborList.GetArrayIndex(i) );
if ( value < m_ValueZero ) // Assign to first outside layer.
{
layer_number = 1;
}
else // Assign to first inside layer
{
layer_number = 2;
}
statusIt.SetPixel(m_NeighborList.GetArrayIndex(i), layer_number, bounds_status);
if ( bounds_status == true ) // In bounds
{
node = m_LayerNodeStore->Borrow();
node->m_Index = offset_index;
m_Layers[layer_number]->PushFront(node);
} // else do nothing.
}
}
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ConstructLayer(const StatusType& from, const StatusType& to)
{
LayerNodeType *node;
bool boundary_status;
typename LayerType::ConstIterator fromIt;
NeighborhoodIterator< StatusImageType > statusIt( m_NeighborList.GetRadius(), m_StatusImage,
m_OutputImage->GetRequestedRegion() );
// For all indices in the "from" layer...
for ( fromIt = m_Layers[from]->Begin(); fromIt != m_Layers[from]->End(); ++fromIt )
{
// Search the neighborhood of this index in the status image for
// unassigned indices. Push those indices onto the "to" layer and
// assign them values in the status image. Status pixels outside the
// boundary will be ignored.
statusIt.SetLocation(fromIt->m_Index);
for ( unsigned int i = 0; i < m_NeighborList.GetSize(); ++i )
{
if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex(i) ) == m_StatusNull )
{
statusIt.SetPixel(m_NeighborList.GetArrayIndex(i), to, boundary_status);
if ( boundary_status == true ) // in bounds
{
node = m_LayerNodeStore->Borrow();
node->m_Index = statusIt.GetIndex() + m_NeighborList.GetNeighborhoodOffset(i);
m_Layers[to]->PushFront(node);
}
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::InitializeActiveLayerValues()
{
const ValueType CHANGE_FACTOR = m_ConstantGradientValue / 2.0;
ValueType MIN_NORM = 1.0e-6;
if ( this->GetUseImageSpacing() )
{
SpacePrecisionType minSpacing = NumericTraits< SpacePrecisionType >::max();
for ( unsigned int i = 0; i < ImageDimension; i++ )
{
minSpacing = std::min(minSpacing, this->GetInput()->GetSpacing()[i]);
}
MIN_NORM *= minSpacing;
}
typename LayerType::ConstIterator activeIt;
ConstNeighborhoodIterator< OutputImageType > shiftedIt ( m_NeighborList.GetRadius(), m_ShiftedImage,
m_OutputImage->GetRequestedRegion() );
unsigned int center = shiftedIt.Size() / 2;
unsigned int stride;
const NeighborhoodScalesType neighborhoodScales = this->GetDifferenceFunction()->ComputeNeighborhoodScales();
ValueType dx_forward, dx_backward, length, distance;
// For all indices in the active layer...
for ( activeIt = m_Layers[0]->Begin(); activeIt != m_Layers[0]->End(); ++activeIt )
{
// Interpolate on the (shifted) input image values at this index to
// assign an active layer value in the output image.
shiftedIt.SetLocation(activeIt->m_Index);
length = m_ValueZero;
for ( unsigned int i = 0; i < static_cast< unsigned int >( ImageDimension ); ++i )
{
stride = shiftedIt.GetStride(i);
dx_forward = ( shiftedIt.GetPixel(center + stride) - shiftedIt.GetCenterPixel() ) * neighborhoodScales[i];
dx_backward =
( shiftedIt.GetCenterPixel() - shiftedIt.GetPixel(center - stride) ) * neighborhoodScales[i];
if ( itk::Math::abs(dx_forward) > itk::Math::abs(dx_backward) )
{
length += dx_forward * dx_forward;
}
else
{
length += dx_backward * dx_backward;
}
}
length = std::sqrt(length) + MIN_NORM;
distance = shiftedIt.GetCenterPixel() / length;
m_OutputImage->SetPixel( activeIt->m_Index,
std::min(std::max(-CHANGE_FACTOR, distance), CHANGE_FACTOR) );
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::PropagateAllLayerValues()
{
// Update values in the first inside and first outside layers using the
// active layer as a seed. Inside layers are odd numbers, outside layers are
// even numbers.
this->PropagateLayerValues (0, 1, 3, 1); // first inside
this->PropagateLayerValues (0, 2, 4, 0); // first outside
// Update the rest of the layers.
for ( unsigned int i = 1; i < m_Layers.size() - 2; ++i )
{
this->PropagateLayerValues (i, i + 2, i + 4, ( i + 2 ) % 2);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::PropagateLayerValues(const StatusType& from,
const StatusType& to,
const StatusType& promote,
unsigned int InOrOut)
{
unsigned int i;
ValueType value, value_temp, delta;
bool found_neighbor_flag;
LayerNodeType *node;
StatusType past_end = static_cast< StatusType >( m_Layers.size() ) - 1;
// Are we propagating values inward (more negative) or outward (more
// positive)?
if ( InOrOut == 1 )
{
delta = -m_ConstantGradientValue; // inward
}
else
{
delta = m_ConstantGradientValue;
}
NeighborhoodIterator< OutputImageType > outputIt ( m_NeighborList.GetRadius(), m_OutputImage,
m_OutputImage->GetRequestedRegion() );
NeighborhoodIterator< StatusImageType > statusIt ( m_NeighborList.GetRadius(), m_StatusImage,
m_OutputImage->GetRequestedRegion() );
typename LayerType::Iterator toIt = m_Layers[to]->Begin();
while ( toIt != m_Layers[to]->End() )
{
statusIt.SetLocation(toIt->m_Index);
// Is this index marked for deletion? If the status image has
// been marked with another layer's value, we need to delete this node
// from the current list then skip to the next iteration.
if ( statusIt.GetCenterPixel() != to )
{
node = toIt.GetPointer();
++toIt;
m_Layers[to]->Unlink(node);
m_LayerNodeStore->Return(node);
continue;
}
outputIt.SetLocation(toIt->m_Index);
value = m_ValueZero;
found_neighbor_flag = false;
for ( i = 0; i < m_NeighborList.GetSize(); ++i )
{
// If this neighbor is in the "from" list, compare its absolute value
// to any previous values found in the "from" list. Keep the value
// that will cause the next layer to be closest to the zero level set.
if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex(i) ) == from )
{
value_temp = outputIt.GetPixel( m_NeighborList.GetArrayIndex(i) );
if ( found_neighbor_flag == false )
{
value = value_temp;
}
else
{
if ( itk::Math::abs(value_temp + delta) < itk::Math::abs(value + delta) )
{
// take the value closest to zero
value = value_temp;
}
}
found_neighbor_flag = true;
}
}
if ( found_neighbor_flag == true )
{
// Set the new value using the smallest magnitude
// found in our "from" neighbors.
outputIt.SetCenterPixel(value + delta);
++toIt;
}
else
{
// Did not find any neighbors on the "from" list, then promote this
// node. A "promote" value past the end of my sparse field size
// means delete the node instead. Change the status value in the
// status image accordingly.
node = toIt.GetPointer();
++toIt;
m_Layers[to]->Unlink(node);
if ( promote > past_end )
{
m_LayerNodeStore->Return(node);
statusIt.SetCenterPixel(m_StatusNull);
}
else
{
m_Layers[promote]->PushFront(node);
statusIt.SetCenterPixel(promote);
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::InitializeBackgroundPixels()
{
// Assign background pixels INSIDE the sparse field layers to a new level set
// with value less than the innermost layer. Assign background pixels
// OUTSIDE the sparse field layers to a new level set with value greater than
// the outermost layer.
const auto max_layer = static_cast< ValueType >( m_NumberOfLayers );
const ValueType outside_value = ( max_layer + 1 ) * m_ConstantGradientValue;
const ValueType inside_value = -( max_layer + 1 ) * m_ConstantGradientValue;
ImageRegionConstIterator< StatusImageType > statusIt( m_StatusImage,
this->GetOutput()->GetRequestedRegion() );
ImageRegionIterator< OutputImageType > outputIt( this->GetOutput(),
this->GetOutput()->GetRequestedRegion() );
ImageRegionConstIterator< OutputImageType > shiftedIt( m_ShiftedImage,
this->GetOutput()->GetRequestedRegion() );
for ( outputIt.GoToBegin(), statusIt.GoToBegin(),
shiftedIt.GoToBegin();
!outputIt.IsAtEnd(); ++outputIt, ++statusIt, ++shiftedIt )
{
if ( statusIt.Get() == m_StatusNull || statusIt.Get() == m_StatusBoundaryPixel )
{
if ( shiftedIt.Get() > m_ValueZero )
{
outputIt.Set(outside_value);
}
else
{
outputIt.Set(inside_value);
}
}
}
// deallocate the shifted-image
m_ShiftedImage = nullptr;
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ComputeInitialThreadBoundaries()
{
// NOTE: Properties of the boundary computation algorithm
// 1. Thread-0 always has something to work on.
// 2. If a particular thread numbered i has the m_Boundary = (mZSize -
// 1) then ALL threads numbered > i do NOT have anything to work on.
// Compute the cumulative frequency distribution using the global histogram.
unsigned int i, j;
m_ZCumulativeFrequency[0] = m_GlobalZHistogram[0];
for ( i = 1; i < m_ZSize; i++ )
{
m_ZCumulativeFrequency[i] = m_ZCumulativeFrequency[i - 1] + m_GlobalZHistogram[i];
}
// Now define the regions that each thread will process and the corresponding
// boundaries.
m_Boundary[m_NumOfThreads - 1] = m_ZSize - 1; // special case: the upper
// bound for the last thread
for ( i = 0; i < m_NumOfThreads - 1; i++ )
{
// compute m_Boundary[i]
float cutOff = 1.0 * ( i + 1 ) * m_ZCumulativeFrequency[m_ZSize - 1] / m_NumOfThreads;
// find the position in the cumulative freq dist where this cutoff is met
for ( j = ( i == 0 ? 0 : m_Boundary[i - 1] ); j < m_ZSize; j++ )
{
if ( cutOff > m_ZCumulativeFrequency[j] )
{
continue;
}
else
{
// Optimize a little.
// Go further FORWARD and find the first index (k) in the cumulative
// freq distribution s.t. m_ZCumulativeFrequency[k] !=
// m_ZCumulativeFrequency[j] This is to be done because if we have a
// flat patch in the cumulative freq. dist. then we can choose
// a bound midway in that flat patch .
unsigned int k;
for ( k = 1; j + k < m_ZSize; k++ )
{
if ( m_ZCumulativeFrequency[j + k] != m_ZCumulativeFrequency[j] )
{
break;
}
}
//
m_Boundary[i] = static_cast< unsigned int >( ( j + k / 2 ) );
break;
}
}
}
// Initialize the local histograms using the global one and the boundaries
// Also initialize the mapping from the Z value --> the thread number
// i.e. m_MapZToThreadNumber[]
// Also divide the lists up according to the boundaries
for ( i = 0; i <= m_Boundary[0]; i++ )
{
// this Z belongs to the region associated with thread-0
m_MapZToThreadNumber[i] = 0;
}
for ( unsigned int t = 1; t < m_NumOfThreads; t++ )
{
for ( i = m_Boundary[t - 1] + 1; i <= m_Boundary[t]; i++ )
{
// this Z belongs to the region associated with thread-0
m_MapZToThreadNumber[i] = t;
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedAllocateData(ThreadIdType ThreadId)
{
static constexpr float SAFETY_FACTOR = 4.0;
unsigned int i, j;
m_Data[ThreadId].m_Semaphore[0] = 0;
m_Data[ThreadId].m_Semaphore[1] = 0;
// Allocate the layers for the sparse field.
m_Data[ThreadId].m_Layers.reserve(2 * m_NumberOfLayers + 1);
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; ++i )
{
m_Data[ThreadId].m_Layers.push_back( LayerType::New() );
}
// Throw an exception if we don't have enough layers.
if ( m_Data[ThreadId].m_Layers.size() < 3 )
{
itkExceptionMacro(<< "Not enough layers have been allocated for the sparse"
<< "field. Requires at least one layer.");
}
// Layers used as buffers for transferring pixels during load balancing
m_Data[ThreadId].m_LoadTransferBufferLayers =
new LayerListType[2 * m_NumberOfLayers + 1];
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
m_Data[ThreadId].m_LoadTransferBufferLayers[i].reserve(m_NumOfThreads);
for ( j = 0; j < m_NumOfThreads; j++ )
{
m_Data[ThreadId].m_LoadTransferBufferLayers[i].push_back( LayerType::New() );
}
}
// Every thread allocates a local node pool (improving memory locality)
m_Data[ThreadId].m_LayerNodeStore = LayerNodeStorageType::New();
m_Data[ThreadId].m_LayerNodeStore->SetGrowthStrategyToExponential();
// The SAFETY_FACTOR simple ensures that the number of nodes created
// is larger than those required to start with for each thread.
auto nodeNum = static_cast< unsigned int >( SAFETY_FACTOR * m_Layers[0]->Size()
* ( 2 * m_NumberOfLayers + 1 ) / m_NumOfThreads );
m_Data[ThreadId].m_LayerNodeStore->Reserve(nodeNum);
m_Data[ThreadId].m_RMSChange = m_ValueZero;
// UpLists and Downlists
for ( i = 0; i < 2; ++i )
{
m_Data[ThreadId].UpList[i] = LayerType::New();
m_Data[ThreadId].DownList[i] = LayerType::New();
}
// Used during the time when status lists are being processed (in
// ThreadedApplyUpdate() )
// for the Uplists
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0] =
new LayerPointerType *[m_NumberOfLayers + 1];
// for the Downlists
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1] =
new LayerPointerType *[m_NumberOfLayers + 1];
for ( i = 0; i < static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i] =
new LayerPointerType[m_NumOfThreads];
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i] =
new LayerPointerType[m_NumOfThreads];
}
for ( i = 0; i < static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
for ( j = 0; j < m_NumOfThreads; j++ )
{
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i][j] =
LayerType::New();
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i][j] =
LayerType::New();
}
}
// Local histogram for every thread (used during Iterate() )
m_Data[ThreadId].m_ZHistogram = new int[m_ZSize];
for ( i = 0; i < m_ZSize; i++ )
{
m_Data[ThreadId].m_ZHistogram[i] = 0;
}
// Every thread must have its own copy of the the GlobalData struct.
m_Data[ThreadId].globalData =
this->GetDifferenceFunction()->GetGlobalDataPointer();
//
m_Data[ThreadId].m_SemaphoreArrayNumber = 0;
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedInitializeData(ThreadIdType ThreadId,
const ThreadRegionType & ThreadRegion)
{
// divide the lists based on the boundaries
LayerNodeType *nodePtr, *nodeTempPtr;
for ( unsigned int i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
typename LayerType::Iterator layerIt = m_Layers[i]->Begin();
typename LayerType::Iterator layerEnd = m_Layers[i]->End();
while ( layerIt != layerEnd )
{
nodePtr = layerIt.GetPointer();
++layerIt;
unsigned int k = this->GetThreadNumber(nodePtr->m_Index[m_SplitAxis]);
if ( k != ThreadId )
{
continue; // some other thread's node => ignore
}
// Borrow a node from the specific thread's layer so that MEMORY LOCALITY
// is maintained.
// NOTE : We already pre-allocated more than enough
// nodes for each thread implying no new nodes are created here.
nodeTempPtr = m_Data[ThreadId].m_LayerNodeStore->Borrow ();
nodeTempPtr->m_Index = nodePtr->m_Index;
// push the node on the approproate layer
m_Data[ThreadId].m_Layers[i]->PushFront(nodeTempPtr);
// for the active layer (layer-0) build the histogram for each thread
if ( i == 0 )
{
// this Z histogram value should be given to thread-0
m_Data[ThreadId].m_ZHistogram[( nodePtr->m_Index )[m_SplitAxis]] =
m_Data[ThreadId].m_ZHistogram[( nodePtr->m_Index )[m_SplitAxis]] + 1;
}
}
}
// Copy from the current status/output images to the new ones and let each
// thread do the copy of its own region.
// This will make each thread be the FIRST to write to "it's" data in the new
// images and hence the memory will get allocated
// in the corresponding thread's memory-node.
ImageRegionConstIterator< StatusImageType > statusIt(m_StatusImage, ThreadRegion);
ImageRegionIterator< StatusImageType > statusItNew (m_StatusImageTemp, ThreadRegion);
ImageRegionConstIterator< OutputImageType > outputIt(m_OutputImage, ThreadRegion);
ImageRegionIterator< OutputImageType > outputItNew(m_OutputImageTemp, ThreadRegion);
for ( outputIt.GoToBegin(), statusIt.GoToBegin(),
outputItNew.GoToBegin(), statusItNew.GoToBegin();
!outputIt.IsAtEnd(); ++outputIt, ++statusIt, ++outputItNew, ++statusItNew )
{
statusItNew.Set ( statusIt.Get() );
outputItNew.Set ( outputIt.Get() );
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::DeallocateData()
{
unsigned int i;
// Delete data structures used for load distribution and balancing.
delete[] m_GlobalZHistogram;
m_GlobalZHistogram = nullptr;
delete[] m_ZCumulativeFrequency;
m_ZCumulativeFrequency = nullptr;
delete[] m_MapZToThreadNumber;
m_MapZToThreadNumber = nullptr;
delete[] m_Boundary;
m_Boundary = nullptr;
// Deallocate the status image.
m_StatusImage = nullptr;
// Remove the barrier from the system.
// m_Barrier->Remove ();
// Delete initial nodes, the node pool, the layers.
if ( !m_Layers.empty() )
{
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
// return all the nodes in layer i to the main node pool
LayerNodeType * nodePtr = nullptr;
LayerPointerType layerPtr = m_Layers[i];
while ( !layerPtr->Empty() )
{
nodePtr = layerPtr->Front();
layerPtr->PopFront();
m_LayerNodeStore->Return (nodePtr);
}
}
}
if ( m_LayerNodeStore )
{
m_LayerNodeStore->Clear();
m_Layers.clear();
}
if ( m_Data != nullptr )
{
// Deallocate the thread local data structures.
for ( ThreadIdType ThreadId = 0; ThreadId < m_NumOfThreads; ThreadId++ )
{
delete[] m_Data[ThreadId].m_ZHistogram;
if ( m_Data[ThreadId].globalData != nullptr )
{
this->GetDifferenceFunction()->ReleaseGlobalDataPointer (m_Data[ThreadId].globalData);
m_Data[ThreadId].globalData = nullptr;
}
// 1. delete nodes on the thread layers
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
// return all the nodes in layer i to thread-i's node pool
LayerNodeType * nodePtr;
LayerPointerType layerPtr = m_Data[ThreadId].m_Layers[i];
while ( !layerPtr->Empty() )
{
nodePtr = layerPtr->Front();
layerPtr->PopFront();
m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
}
}
m_Data[ThreadId].m_Layers.clear();
// 2. cleanup the LoadTransferBufferLayers: empty all and return the nodes
// to the pool
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
for ( ThreadIdType tid = 0; tid < m_NumOfThreads; tid++ )
{
if ( tid == ThreadId )
{
// a thread does NOT pass nodes to istelf
continue;
}
LayerNodeType * nodePtr;
LayerPointerType layerPtr = m_Data[ThreadId].m_LoadTransferBufferLayers[i][tid];
while ( !layerPtr->Empty() )
{
nodePtr = layerPtr->Front();
layerPtr->PopFront();
m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
}
}
m_Data[ThreadId].m_LoadTransferBufferLayers[i].clear();
}
delete[] m_Data[ThreadId].m_LoadTransferBufferLayers;
// 3. clear up the nodes in the last layer of
// m_InterNeighborNodeTransferBufferLayers (if any)
for ( i = 0; i < m_NumOfThreads; i++ )
{
LayerNodeType *nodePtr;
for ( unsigned int InOrOut = 0; InOrOut < 2; InOrOut++ )
{
LayerPointerType layerPtr =
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][m_NumberOfLayers][i];
while ( !layerPtr->Empty() )
{
nodePtr = layerPtr->Front();
layerPtr->PopFront();
m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
}
}
}
// check if all last layers are empty and then delete them
for ( i = 0; i < static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
delete[] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0][i];
delete[] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1][i];
}
delete[] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[0];
delete[] m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[1];
// 4. check if all the uplists and downlists are empty
// 5. delete all nodes in the node pool
m_Data[ThreadId].m_LayerNodeStore->Clear();
}
delete[] m_Data;
} // if m_data != 0
m_Data = nullptr;
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedInitializeIteration( ThreadIdType itkNotUsed(ThreadId) )
{
// If child classes need an entry point to the start of every iteration step
// they can override this method.
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::Iterate()
{
m_TimeStep = NumericTraits< TimeStepType >::ZeroValue();
MultiThreaderBase* mt = this->GetMultiThreader();
mt->SetNumberOfWorkUnits( m_NumOfThreads );
// Initialize the list of time step values that will be generated by the
// various threads. There is one distinct slot for each possible thread,
// so this data structure is thread-safe.
m_TimeStepList.resize( m_NumOfThreads );
m_ValidTimeStepList.resize( m_NumOfThreads, true );
typename TOutputImage::RegionType reqRegion = m_OutputImage->GetRequestedRegion();
// Controls how often we check for balance of the load among the threads and
// perform load balancing (if needed) by redistributing the load.
constexpr unsigned int LOAD_BALANCE_ITERATION_FREQUENCY = 30;
if ( !this->m_IsInitialized )
{
this->ComputeInitialThreadBoundaries ();
// Create the temporary status image
this->m_StatusImageTemp = StatusImageType::New();
this->m_StatusImageTemp->SetRegions( reqRegion );
this->m_StatusImageTemp->Allocate();
// Create the temporary output image
this->m_OutputImageTemp = OutputImageType::New();
this->m_OutputImageTemp->CopyInformation( this->m_OutputImage );
this->m_OutputImageTemp->SetRegions( reqRegion );
this->m_OutputImageTemp->Allocate();
// Data allocation and initialization performed in parallel
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->ThreadedAllocateData( threadId );
this->GetThreadRegionSplitByBoundary( threadId, this->m_Data[threadId].ThreadRegion );
this->ThreadedInitializeData( threadId, this->m_Data[threadId].ThreadRegion );
}, nullptr );
this->m_StatusImage = nullptr;
this->m_StatusImage = this->m_StatusImageTemp;
this->m_StatusImageTemp = nullptr;
this->m_OutputImage = nullptr;
this->m_OutputImage = this->m_OutputImageTemp;
this->m_OutputImageTemp = nullptr;
this->GraftOutput(this->m_OutputImage);
this->m_IsInitialized = true;
}
unsigned int iter = this->GetElapsedIterations();
while ( !( this->Halt() ) )
{
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->ThreadedInitializeIteration( threadId );
this->m_Data[threadId].TimeStep = this->ThreadedCalculateChange( threadId );
}, nullptr );
// Calculate the timestep (no need to do this when there is just 1 thread)
if ( this->m_NumOfThreads == 1 )
{
if ( iter != 0 )
{
// Update the RMS difference here
this->SetRMSChange( static_cast< double >( this->m_Data[0].m_RMSChange ) );
unsigned int count = this->m_Data[0].m_Count;
if ( count != 0 )
{
this->SetRMSChange( static_cast< double >(
std::sqrt( ( static_cast< float >( this->GetRMSChange() ) ) / count) ) );
}
}
// this is done by the thread0
this->InvokeEvent( IterationEvent() );
this->InvokeEvent( ProgressEvent () );
this->SetElapsedIterations(++iter);
// (works for the 1-thread case else redefined below)
m_TimeStep = this->m_Data[0].TimeStep;
}
else
{
if ( iter != 0 )
{
// Update the RMS difference here
unsigned int count = 0;
this->SetRMSChange( static_cast< double >( m_ValueZero ) );
for ( unsigned i = 0; i < this->m_NumOfThreads; i++ )
{
this->SetRMSChange(this->GetRMSChange() + this->m_Data[i].m_RMSChange);
count += this->m_Data[i].m_Count;
}
if ( count != 0 )
{
this->SetRMSChange( static_cast< double >(
std::sqrt( ( static_cast< float >( this->m_RMSChange ) ) / count ) ) );
}
}
// Should we stop iterating ? (in case there are too few pixels to
// process for every thread)
this->m_Stop = true;
for ( unsigned i = 0; i < this->m_NumOfThreads; i++ )
{
if ( this->m_Data[i].m_Layers[0]->Size() > 10 )
{
this->m_Stop = false;
break;
}
}
this->InvokeEvent ( IterationEvent() );
this->InvokeEvent ( ProgressEvent () );
this->SetElapsedIterations (++iter);
for ( unsigned i = 0; i < this->m_NumOfThreads; i++ )
{
m_TimeStepList[i] = this->m_Data[i].TimeStep;
}
m_TimeStep = this->ResolveTimeStep(m_TimeStepList, m_ValidTimeStepList );
}
// The active layer is too small => stop iterating
if ( this->m_Stop == true )
{
return;
}
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->ThreadedApplyUpdate(m_TimeStep, threadId);
// We only need to wait for neighbors because ThreadedCalculateChange
// requires information only from the neighbors.
this->SignalNeighborsAndWait( threadId );
}, nullptr );
if ( this->GetElapsedIterations() % LOAD_BALANCE_ITERATION_FREQUENCY == 0 )
{
this->CheckLoadBalance();
if ( this->m_BoundaryChanged == true )
{
// the situation at this point in time:
// the OPTIMAL boundaries (that divide work equally) have changed but ...
// the thread data lags behind the boundaries (it is still following the old
// boundaries) the m_ZHistogram[], however, reflects the latest optimal
// boundaries
// The task:
// 1. Every thread checks for pixels with itself that should NOT be with
// itself anymore (because of the changed boundaries).
// These pixels are now put in extra "buckets" for other threads to grab
// 2. WaitForAll ().
// 3. Every thread grabs those pixels, from every other thread, that come
// within its boundaries (from the extra buckets).
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->ThreadedLoadBalance1( threadId );
}, nullptr );
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->ThreadedLoadBalance2( threadId );
}, nullptr );
}
}
}
// post-process output
mt->ParallelizeArray( 0, m_NumOfThreads,
[this]( SizeValueType threadId )
{
this->GetThreadRegionSplitUniformly( threadId, this->m_Data[threadId].ThreadRegion );
this->ThreadedPostProcessOutput( this->m_Data[threadId].ThreadRegion );
}, nullptr );
}
template< typename TInputImage, typename TOutputImage >
typename
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >::TimeStepType
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedCalculateChange(ThreadIdType ThreadId)
{
typename FiniteDifferenceFunctionType::Pointer df = this->GetDifferenceFunction();
typename FiniteDifferenceFunctionType::FloatOffsetType offset;
ValueType norm_grad_phi_squared, dx_forward, dx_backward;
ValueType centerValue, forwardValue, backwardValue;
ValueType MIN_NORM = 1.0e-6;
if ( this->GetUseImageSpacing() )
{
SpacePrecisionType minSpacing = NumericTraits< SpacePrecisionType >::max();
for ( unsigned int i = 0; i < ImageDimension; i++ )
{
minSpacing = std::min(minSpacing, this->GetInput()->GetSpacing()[i]);
}
MIN_NORM *= minSpacing;
}
ConstNeighborhoodIterator< OutputImageType > outputIt ( df->GetRadius(), m_OutputImage,
m_OutputImage->GetRequestedRegion() );
if ( m_BoundsCheckingActive == false )
{
outputIt.NeedToUseBoundaryConditionOff();
}
unsigned int i, center = outputIt.Size() / 2;
this->GetDifferenceFunction()->ComputeNeighborhoodScales();
// Calculates the update values for the active layer indices in this
// iteration. Iterates through the active layer index list, applying
// the level set function to the output image (level set image) at each
// index.
typename LayerType::Iterator layerIt = m_Data[ThreadId].m_Layers[0]->Begin();
typename LayerType::Iterator layerEnd = m_Data[ThreadId].m_Layers[0]->End();
for (; layerIt != layerEnd; ++layerIt )
{
outputIt.SetLocation(layerIt->m_Index);
// Calculate the offset to the surface from the center of this
// neighborhood. This is used by some level set functions in sampling a
// speed, advection, or curvature term.
if ( this->m_InterpolateSurfaceLocation
&& Math::NotExactlyEquals(( centerValue = outputIt.GetCenterPixel() ), NumericTraits< ValueType >::ZeroValue()) )
{
// Surface is at the zero crossing, so distance to surface is:
// phi(x) / norm(grad(phi)), where phi(x) is the center of the
// neighborhood. The location is therefore
// (i,j,k) - ( phi(x) * grad(phi(x)) ) / norm(grad(phi))^2
norm_grad_phi_squared = 0.0;
for ( i = 0; i < static_cast< unsigned int >( ImageDimension ); ++i )
{
forwardValue = outputIt.GetPixel( center + m_NeighborList.GetStride(i) );
backwardValue = outputIt.GetPixel( center - m_NeighborList.GetStride(i) );
if ( forwardValue * backwardValue >= 0 )
{
// 1. both neighbors have the same sign OR at least one of them is
// ZERO
dx_forward = forwardValue - centerValue;
dx_backward = centerValue - backwardValue;
// take the one-sided derivative with the larger magnitude
if ( itk::Math::abs(dx_forward) > itk::Math::abs(dx_backward) )
{
offset[i] = dx_forward;
}
else
{
offset[i] = dx_backward;
}
}
else
{
// 2. neighbors have opposite sign
// take the one-sided derivative using the neighbor that has the
// opposite sign w.r.t. oneself
if ( centerValue * forwardValue < 0 )
{
offset[i] = forwardValue - centerValue;
}
else
{
offset[i] = centerValue - backwardValue;
}
}
norm_grad_phi_squared += offset[i] * offset[i];
}
for ( i = 0; i < static_cast< unsigned int >( ImageDimension ); ++i )
{
offset[i] = ( offset[i] * outputIt.GetCenterPixel() )
/ ( norm_grad_phi_squared + MIN_NORM );
}
layerIt->m_Value = df->ComputeUpdate (outputIt, (void *)m_Data[ThreadId].globalData, offset);
}
else // Don't do interpolation
{
layerIt->m_Value = df->ComputeUpdate (outputIt, (void *)m_Data[ThreadId].globalData);
}
}
TimeStepType timeStep = df->ComputeGlobalTimeStep ( (void *)m_Data[ThreadId].globalData );
return timeStep;
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedApplyUpdate(const TimeStepType& dt, ThreadIdType ThreadId)
{
this->ThreadedUpdateActiveLayerValues(dt,
m_Data[ThreadId].UpList[0],
m_Data[ThreadId].DownList[0],
ThreadId);
// We need to update histogram information (because some pixels are LEAVING
// layer-0 (the active layer)
this->SignalNeighborsAndWait(ThreadId);
// Process status lists and update value for first inside/outside layers
this->ThreadedProcessStatusList(0, 1, 2, 1, 1, 0, ThreadId);
this->ThreadedProcessStatusList(0, 1, 1, 2, 0, 0, ThreadId);
this->SignalNeighborsAndWait(ThreadId);
// Update first layer value, process first layer
this->ThreadedProcessFirstLayerStatusLists(1, 0, 3, 1, 1, ThreadId);
this->ThreadedProcessFirstLayerStatusLists(1, 0, 4, 0, 1, ThreadId);
// We need to update histogram information (because some pixels are ENTERING
// layer-0
this->SignalNeighborsAndWait(ThreadId);
StatusType up_to = 1, up_search = 5;
StatusType down_to = 2, down_search = 6;
unsigned char j = 0, k = 1;
// The 3D case: this loop is executed at least once
while ( down_search < 2 * m_NumberOfLayers + 1 )
{
this->ThreadedProcessStatusList(j, k, up_to, up_search, 1,
( up_search - 1 ) / 2, ThreadId);
this->ThreadedProcessStatusList(j, k, down_to, down_search, 0,
( up_search - 1 ) / 2, ThreadId);
this->SignalNeighborsAndWait(ThreadId);
up_to += 2;
down_to += 2;
up_search += 2;
down_search += 2;
// Swap the lists so we can re-use the empty one.
j = k;
k = 1 - j;
}
// now up_search = 2 * m_NumberOfLayers + 1 (= 7 if m_NumberOfLayers = 3)
// now down_search = 2 * m_NumberOfLayers + 2 (= 8 if m_NumberOfLayers = 3)
// Process the outermost inside/outside layers in the sparse field
this->ThreadedProcessStatusList(j, k, up_to, m_StatusNull, 1,
( up_search - 1 ) / 2, ThreadId);
this->ThreadedProcessStatusList(j, k, down_to, m_StatusNull, 0,
( up_search - 1 ) / 2, ThreadId);
this->SignalNeighborsAndWait(ThreadId);
this->ThreadedProcessOutsideList(k, ( 2 * m_NumberOfLayers + 1 ) - 2, 1,
( up_search + 1 ) / 2, ThreadId);
this->ThreadedProcessOutsideList(k, ( 2 * m_NumberOfLayers + 1 ) - 1, 0,
( up_search + 1 ) / 2, ThreadId);
if ( m_OutputImage->GetImageDimension() < 3 )
{
this->SignalNeighborsAndWait(ThreadId);
}
// A synchronize is NOT required here because in 3D case we have at least 7
// layers, thus ThreadedProcessOutsideList() works on layers 5 & 6 while
// ThreadedPropagateLayerValues() works on 0, 1, 2, 3, 4 only. => There can
// NOT be any dependencies amoing different threads.
// Finally, we update all of the layer VALUES (excluding the active layer,
// which has already been updated)
this->ThreadedPropagateLayerValues(0, 1, 3, 1, ThreadId); // first inside
this->ThreadedPropagateLayerValues(0, 2, 4, 0, ThreadId); // first outside
this->SignalNeighborsAndWait (ThreadId);
// Update the rest of the layer values
unsigned int N = ( 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1 ) - 2;
for ( unsigned int i = 1; i < N; i += 2 )
{
j = i + 1;
this->ThreadedPropagateLayerValues(i, i + 2, i + 4, 1, ThreadId);
this->ThreadedPropagateLayerValues(j, j + 2, j + 4, 0, ThreadId);
this->SignalNeighborsAndWait (ThreadId);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedUpdateActiveLayerValues(const TimeStepType& dt, LayerType *UpList,
LayerType *DownList, ThreadIdType ThreadId)
{
// This method scales the update buffer values by the time step and adds
// them to the active layer pixels. New values at an index which fall
// outside of the active layer range trigger that index to be placed on the
// "up" or "down" status list. The neighbors of any such index are then
// assigned new values if they are determined to be part of the active list
// for the next iteration (i.e. their values will be raised or lowered into
// the active range).
ValueType LOWER_ACTIVE_THRESHOLD = -( m_ConstantGradientValue / 2.0 );
ValueType UPPER_ACTIVE_THRESHOLD = m_ConstantGradientValue / 2.0;
LayerNodeType *release_node;
bool flag;
IndexType centerIndex;
PixelType centerValue;
typename TOutputImage::SizeValueType counter = 0;
float new_value;
float rms_change_accumulator = m_ValueZero;
unsigned int Neighbor_Size = m_NeighborList.GetSize();
typename LayerType::Iterator layerIt =
m_Data[ThreadId].m_Layers[0]->Begin();
typename LayerType::Iterator layerEnd =
m_Data[ThreadId].m_Layers[0]->End();
while ( layerIt != layerEnd )
{
centerIndex = layerIt->m_Index;
centerValue = m_OutputImage->GetPixel(centerIndex);
new_value = this->ThreadedCalculateUpdateValue(ThreadId, centerIndex, dt,
centerValue, layerIt->m_Value);
// If this index needs to be moved to another layer, then search its
// neighborhood for indices that need to be pulled up/down into the
// active layer. Set those new active layer values appropriately,
// checking first to make sure they have not been set by a more
// influential neighbor.
// ...But first make sure any neighbors in the active layer are not
// moving to a layer in the opposite direction. This step is necessary
// to avoid the creation of holes in the active layer. The fix is simply
// to not change this value and leave the index in the active set.
if ( new_value > UPPER_ACTIVE_THRESHOLD )
{
// This index will move UP into a positive (outside) layer
// First check for active layer neighbors moving in the opposite
// direction
flag = false;
for ( unsigned int i = 0; i < Neighbor_Size; ++i )
{
if ( m_StatusImage->GetPixel( centerIndex + m_NeighborList.GetNeighborhoodOffset(i) )
== m_StatusActiveChangingDown )
{
flag = true;
break;
}
}
if ( flag == true )
{
++layerIt;
continue;
}
rms_change_accumulator += itk::Math::sqr( static_cast< float >( new_value - centerValue ) );
// update the value of the pixel
m_OutputImage->SetPixel (centerIndex, new_value);
// Now remove this index from the active list.
release_node = layerIt.GetPointer();
++layerIt;
m_Data[ThreadId].m_Layers[0]->Unlink(release_node);
m_Data[ThreadId].m_ZHistogram[release_node->m_Index[m_SplitAxis]] =
m_Data[ThreadId].m_ZHistogram[release_node->m_Index[m_SplitAxis]] - 1;
// add the release_node to status up list
UpList->PushFront(release_node);
//
m_StatusImage->SetPixel(centerIndex, m_StatusActiveChangingUp);
}
else if ( new_value < LOWER_ACTIVE_THRESHOLD )
{
// This index will move DOWN into a negative (inside) layer.
// First check for active layer neighbors moving in the opposite direction
flag = false;
for ( unsigned int i = 0; i < Neighbor_Size; ++i )
{
if ( m_StatusImage->GetPixel( centerIndex + m_NeighborList.GetNeighborhoodOffset(i) )
== m_StatusActiveChangingUp )
{
flag = true;
break;
}
}
if ( flag == true )
{
++layerIt;
continue;
}
rms_change_accumulator += itk::Math::sqr( static_cast< float >( new_value - centerValue ) );
// update the value of the pixel
m_OutputImage->SetPixel(centerIndex, new_value);
// Now remove this index from the active list.
release_node = layerIt.GetPointer();
++layerIt;
m_Data[ThreadId].m_Layers[0]->Unlink(release_node);
m_Data[ThreadId].m_ZHistogram[release_node->m_Index[m_SplitAxis]] =
m_Data[ThreadId].m_ZHistogram[release_node->m_Index[m_SplitAxis]] - 1;
// now add release_node to status down list
DownList->PushFront(release_node);
m_StatusImage->SetPixel(centerIndex, m_StatusActiveChangingDown);
}
else
{
rms_change_accumulator += itk::Math::sqr( static_cast< float >( new_value - centerValue ) );
// update the value of the pixel
m_OutputImage->SetPixel(centerIndex, new_value);
++layerIt;
}
++counter;
}
// Determine the average change during this iteration
if ( counter == 0 )
{
m_Data[ThreadId].m_RMSChange = m_ValueZero;
}
else
{
m_Data[ThreadId].m_RMSChange = rms_change_accumulator;
}
m_Data[ThreadId].m_Count = counter;
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::CopyInsertList(ThreadIdType ThreadId, LayerPointerType FromListPtr,
LayerPointerType ToListPtr)
{
typename LayerType::Iterator layerIt = FromListPtr->Begin();
typename LayerType::Iterator layerEnd = FromListPtr->End();
LayerNodeType *nodePtr;
LayerNodeType *nodeTempPtr;
while ( layerIt != layerEnd )
{
// copy the node
nodePtr = layerIt.GetPointer();
++layerIt;
nodeTempPtr = m_Data[ThreadId].m_LayerNodeStore->Borrow();
nodeTempPtr->m_Index = nodePtr->m_Index;
// insert
ToListPtr->PushFront (nodeTempPtr);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ClearList(ThreadIdType ThreadId, LayerPointerType ListPtr)
{
LayerNodeType *nodePtr;
while ( !ListPtr->Empty() )
{
nodePtr = ListPtr->Front();
// remove node from layer
ListPtr->PopFront();
// return node to node-pool
m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::CopyInsertInterNeighborNodeTransferBufferLayers(
ThreadIdType ThreadId, LayerPointerType List,
unsigned int InOrOut, unsigned int BufferLayerNumber)
{
if ( ThreadId != 0 )
{
CopyInsertList(ThreadId,
m_Data[this->GetThreadNumber(m_Boundary[ThreadId
- 1])].m_InterNeighborNodeTransferBufferLayers[InOrOut][
BufferLayerNumber][ThreadId],
List);
}
if ( m_Boundary[ThreadId] != m_ZSize - 1 )
{
CopyInsertList(ThreadId,
m_Data[this->GetThreadNumber (m_Boundary[ThreadId]
+ 1)].m_InterNeighborNodeTransferBufferLayers[InOrOut][
BufferLayerNumber][ThreadId],
List);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ClearInterNeighborNodeTransferBufferLayers(
ThreadIdType ThreadId, unsigned int InOrOut,
unsigned int BufferLayerNumber)
{
for ( unsigned int i = 0; i < m_NumOfThreads; i++ )
{
ClearList(ThreadId, m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][i]);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedProcessFirstLayerStatusLists(
unsigned int InputLayerNumber, unsigned int OutputLayerNumber,
const StatusType& SearchForStatus, unsigned int InOrOut,
unsigned int BufferLayerNumber, ThreadIdType ThreadId)
{
LayerNodeType *nodePtr;
StatusType from, neighbor_status;
ValueType value, value_temp, delta;
bool found_neighbor_flag;
IndexType center_index, n_index;
unsigned int neighbor_Size = m_NeighborList.GetSize();
LayerPointerType InputList, OutputList;
//InOrOut == 1, inside, more negative, uplist
//InOrOut == 0, outside
if ( InOrOut == 1 )
{
delta = -m_ConstantGradientValue;
from = 2;
InputList = m_Data[ThreadId].UpList[InputLayerNumber];
OutputList = m_Data[ThreadId].UpList[OutputLayerNumber];
}
else
{
delta = m_ConstantGradientValue;
from = 1;
InputList = m_Data[ThreadId].DownList[InputLayerNumber];
OutputList = m_Data[ThreadId].DownList[OutputLayerNumber];
}
// 1. nothing to clear
// 2. make a copy of the node on the
// m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber -
// 1][i]
// for all neighbors i ... and insert it in one's own InputList
CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, InputList, InOrOut,
BufferLayerNumber - 1);
typename LayerType::Iterator layerIt = InputList->Begin();
typename LayerType::Iterator layerEnd = InputList->End();
while ( layerIt != layerEnd )
{
nodePtr = layerIt.GetPointer();
++layerIt;
center_index = nodePtr->m_Index;
// remove node from InputList
InputList->Unlink(nodePtr);
// check if this is not a duplicate pixel in the InputList
// In the case when the thread boundaries differ by just 1 pixel some
// nodes may get added twice in the InputLists Even if the boundaries are
// more than 1 pixel wide the *_shape_* of the layer may allow this to
// happen. Solution: If a pixel comes multiple times than we would find
// that the Status image would already be reflecting the new status after
// the pixel was encountered the first time
if ( m_StatusImage->GetPixel(center_index) == 0 )
{
// duplicate node => return it to the node pool
m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
continue;
}
// set status to zero
m_StatusImage->SetPixel(center_index, 0);
// add node to the layer-0
m_Data[ThreadId].m_Layers[0]->PushFront(nodePtr);
m_Data[ThreadId].m_ZHistogram[nodePtr->m_Index[m_SplitAxis]] =
m_Data[ThreadId].m_ZHistogram[nodePtr->m_Index[m_SplitAxis]] + 1;
value = m_OutputImage->GetPixel(center_index);
found_neighbor_flag = false;
for ( unsigned int i = 0; i < neighbor_Size; ++i )
{
n_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
neighbor_status = m_StatusImage->GetPixel(n_index);
// Have we bumped up against the boundary? If so, turn on bounds
// checking.
if ( neighbor_status == m_StatusBoundaryPixel )
{
m_BoundsCheckingActive = true;
}
if ( neighbor_status == from )
{
value_temp = m_OutputImage->GetPixel(n_index);
if ( found_neighbor_flag == false )
{
value = value_temp;
}
else
{
if ( itk::Math::abs(value_temp + delta) < itk::Math::abs(value + delta) )
{
// take the value closest to zero
value = value_temp;
}
}
found_neighbor_flag = true;
}
if ( neighbor_status == SearchForStatus )
{
// mark this pixel so we MAY NOT add it twice
// This STILL DOES NOT GUARANTEE RACE CONDITIONS BETWEEN THREADS. This
// is handled at the next stage
m_StatusImage->SetPixel(n_index, m_StatusChanging);
unsigned int tmpId = this->GetThreadNumber(n_index[m_SplitAxis]);
nodePtr = m_Data[ThreadId].m_LayerNodeStore->Borrow();
nodePtr->m_Index = n_index;
if ( tmpId != ThreadId )
{
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][tmpId]->PushFront(
nodePtr);
}
else
{
OutputList->PushFront(nodePtr);
}
}
}
m_OutputImage->SetPixel(center_index, value + delta);
// This function can be overridden in the derived classes to process pixels
// entering the active layer.
this->ThreadedProcessPixelEnteringActiveLayer (center_index, value + delta, ThreadId);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedProcessPixelEnteringActiveLayer( const IndexType& itkNotUsed(index),
const ValueType& itkNotUsed(value),
ThreadIdType itkNotUsed(ThreadId) )
{
// This function can be overridden in the derived classes to process pixels
// entering the active layer.
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedProcessStatusList(
unsigned int InputLayerNumber, unsigned int OutputLayerNumber,
const StatusType& ChangeToStatus, const StatusType& SearchForStatus,
unsigned int InOrOut, unsigned int BufferLayerNumber,
ThreadIdType ThreadId)
{
unsigned int i;
LayerNodeType *nodePtr;
StatusType neighbor_status;
IndexType center_index, n_index;
LayerPointerType InputList, OutputList;
// Push each index in the input list into its appropriate status layer
// (ChangeToStatus) and update the status image value at that index.
// Also examine the neighbors of the index to determine which need to go onto
// the output list (search for SearchForStatus).
if ( InOrOut == 1 )
{
InputList = m_Data[ThreadId].UpList[InputLayerNumber];
OutputList = m_Data[ThreadId].UpList[OutputLayerNumber];
}
else
{
InputList = m_Data[ThreadId].DownList[InputLayerNumber];
OutputList = m_Data[ThreadId].DownList[OutputLayerNumber];
}
// 1. clear one's own
// m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber - 2][i]
// for all threads i.
if ( BufferLayerNumber >= 2 )
{
ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut,
BufferLayerNumber - 2);
}
// SPECIAL CASE: clear one's own
// m_InterNeighborNodeTransferBufferLayers[InOrOut][m_NumberOfLayers][i] for
// all threads i
if ( BufferLayerNumber == 0 )
{
ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut, m_NumberOfLayers);
}
// obtain the pixels (from last iteration) that were given to you from other
// (neighboring) threads 2. make a copy of the node on the
// m_InterNeighborNodeTransferBufferLayers[InOrOut][LastLayer - 1][i] for all
// thread neighbors i ... ... and insert it in one's own InputList
if ( BufferLayerNumber > 0 )
{
CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, InputList,
InOrOut, BufferLayerNumber - 1);
}
unsigned int neighbor_size = m_NeighborList.GetSize();
while ( !InputList->Empty() )
{
nodePtr = InputList->Front();
center_index = nodePtr->m_Index;
InputList->PopFront();
// Check if this is not a duplicate pixel in the InputList.
// Solution: If a pixel comes multiple times than we would find that the
// Status image would already be reflecting
// the new status after the pixel was encountered the first time
if ( ( BufferLayerNumber != 0 )
&& ( m_StatusImage->GetPixel(center_index) == ChangeToStatus ) )
{
// duplicate node => return it to the node pool
m_Data[ThreadId].m_LayerNodeStore->Return (nodePtr);
continue;
}
// add to layer
m_Data[ThreadId].m_Layers[ChangeToStatus]->PushFront (nodePtr);
// change the status
m_StatusImage->SetPixel(center_index, ChangeToStatus);
for ( i = 0; i < neighbor_size; ++i )
{
n_index = center_index + m_NeighborList.GetNeighborhoodOffset(i);
neighbor_status = m_StatusImage->GetPixel(n_index);
// Have we bumped up against the boundary? If so, turn on bounds
// checking.
if ( neighbor_status == m_StatusBoundaryPixel )
{
m_BoundsCheckingActive = true;
}
if ( neighbor_status == SearchForStatus )
{
// mark this pixel so we MAY NOT add it twice
// This STILL DOES NOT AVOID RACE CONDITIONS BETWEEN THREADS (This is
// handled at the next stage)
m_StatusImage->SetPixel(n_index, m_StatusChanging);
unsigned int tmpId = this->GetThreadNumber (n_index[m_SplitAxis]);
nodePtr = m_Data[ThreadId].m_LayerNodeStore->Borrow();
nodePtr->m_Index = n_index;
if ( tmpId != ThreadId )
{
m_Data[ThreadId].m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber][tmpId]->PushFront(
nodePtr);
}
else
{
OutputList->PushFront(nodePtr);
}
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedProcessOutsideList(
unsigned int InputLayerNumber, const StatusType& ChangeToStatus,
unsigned int InOrOut, unsigned int BufferLayerNumber,
ThreadIdType ThreadId)
{
LayerPointerType OutsideList;
if ( InOrOut == 1 )
{
OutsideList = m_Data[ThreadId].UpList[InputLayerNumber];
}
else
{
OutsideList = m_Data[ThreadId].DownList[InputLayerNumber];
}
// obtain the pixels (from last iteration of ThreadedProcessStatusList() )
// that were given to you from other (neighboring) threads
// 1. clear one's own
// m_InterNeighborNodeTransferBufferLayers[InOrOut][BufferLayerNumber -
// 2][i]
// for all threads i.
ClearInterNeighborNodeTransferBufferLayers(ThreadId, InOrOut, BufferLayerNumber - 2);
// 2. make a copy of the node on the
// m_InterNeighborNodeTransferBufferLayers[InOrOut][LastLayer - 1][i] for
// all thread neighbors i ... ... and insert it in one's own InoutList
CopyInsertInterNeighborNodeTransferBufferLayers(ThreadId, OutsideList, InOrOut,
BufferLayerNumber - 1);
// Push each index in the input list into its appropriate status layer
// (ChangeToStatus) and ... ... update the status image value at that index
LayerNodeType *nodePtr;
while ( !OutsideList->Empty() )
{
nodePtr = OutsideList->Front();
OutsideList->PopFront();
m_StatusImage->SetPixel(nodePtr->m_Index, ChangeToStatus);
m_Data[ThreadId].m_Layers[ChangeToStatus]->PushFront (nodePtr);
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedPropagateLayerValues(
const StatusType& from, const StatusType& to,
const StatusType& promote, unsigned int InOrOut,
ThreadIdType ThreadId)
{
ValueType value, value_temp, delta;
bool found_neighbor_flag;
typename LayerType::Iterator toIt;
typename LayerType::Iterator toEnd;
LayerNodeType *nodePtr;
StatusType past_end = static_cast< StatusType >( m_Layers.size() ) - 1;
// Are we propagating values inward (more negative) or outward (more
// positive)?
if ( InOrOut == 1 )
{
delta = -m_ConstantGradientValue;
}
else
{
delta = m_ConstantGradientValue;
}
unsigned int Neighbor_Size = m_NeighborList.GetSize();
toIt = m_Data[ThreadId].m_Layers[to]->Begin();
toEnd = m_Data[ThreadId].m_Layers[to]->End();
IndexType centerIndex, nIndex;
StatusType centerStatus, nStatus;
while ( toIt != toEnd )
{
centerIndex = toIt->m_Index;
centerStatus = m_StatusImage->GetPixel(centerIndex);
if ( centerStatus != to )
{
// delete nodes NOT deleted earlier
nodePtr = toIt.GetPointer();
++toIt;
// remove the node from the layer
m_Data[ThreadId].m_Layers[to]->Unlink(nodePtr);
m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
continue;
}
value = m_ValueZero;
found_neighbor_flag = false;
for ( unsigned int i = 0; i < Neighbor_Size; ++i )
{
nIndex = centerIndex + m_NeighborList.GetNeighborhoodOffset(i);
nStatus = m_StatusImage->GetPixel(nIndex);
// If this neighbor is in the "from" list, compare its absolute value
// to any previous values found in the "from" list. Keep only the
// value with the smallest magnitude.
if ( nStatus == from )
{
value_temp = m_OutputImage->GetPixel(nIndex);
if ( found_neighbor_flag == false )
{
value = value_temp;
}
else
{
if ( itk::Math::abs(value_temp + delta) < itk::Math::abs(value + delta) )
{
// take the value closest to zero
value = value_temp;
}
}
found_neighbor_flag = true;
}
}
if ( found_neighbor_flag == true )
{
// Set the new value using the smallest magnitude found in our "from"
// neighbors
m_OutputImage->SetPixel (centerIndex, value + delta);
++toIt;
}
else
{
// Did not find any neighbors on the "from" list, then promote this
// node. A "promote" value past the end of my sparse field size
// means delete the node instead. Change the status value in the
// status image accordingly.
nodePtr = toIt.GetPointer();
++toIt;
m_Data[ThreadId].m_Layers[to]->Unlink(nodePtr);
if ( promote > past_end )
{
m_Data[ThreadId].m_LayerNodeStore->Return(nodePtr);
m_StatusImage->SetPixel(centerIndex, m_StatusNull);
}
else
{
m_Data[ThreadId].m_Layers[promote]->PushFront(nodePtr);
m_StatusImage->SetPixel(centerIndex, promote);
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::CheckLoadBalance()
{
unsigned int i, j;
// This parameter defines a degree of unbalancedness of the load among
// threads.
constexpr float MAX_PIXEL_DIFFERENCE_PERCENT = 0.025;
m_BoundaryChanged = false;
// work load division based on the nodes on the active layer (layer-0)
using NodeCounterType = IndexValueType;
NodeCounterType min = NumericTraits< NodeCounterType >::max();
NodeCounterType max = 0;
NodeCounterType total = 0; // the total nodes in the active layer of the surface
for ( i = 0; i < m_NumOfThreads; i++ )
{
NodeCounterType count = m_Data[i].m_Layers[0]->Size();
total += count;
if ( min > count ) { min = count; }
if ( max < count ) { max = count; }
}
if ( max - min < MAX_PIXEL_DIFFERENCE_PERCENT * total / m_NumOfThreads )
{
// if the difference between max and min is NOT even x% of the average
// nodes in the thread layers then no need to change the boundaries next
return;
}
// Change the boundaries --------------------------
// compute the global histogram from the individual histograms
for ( i = 0; i < m_NumOfThreads; i++ )
{
for ( j = ( i == 0 ? 0 : m_Boundary[i - 1] + 1 ); j <= m_Boundary[i]; j++ )
{
m_GlobalZHistogram[j] = m_Data[i].m_ZHistogram[j];
}
}
// compute the cumulative frequency distribution using the histogram
m_ZCumulativeFrequency[0] = m_GlobalZHistogram[0];
for ( i = 1; i < m_ZSize; i++ )
{
m_ZCumulativeFrequency[i] = m_ZCumulativeFrequency[i - 1] + m_GlobalZHistogram[i];
}
// now define the boundaries
m_Boundary[m_NumOfThreads - 1] = m_ZSize - 1; // special case: the last bound
for ( i = 0; i < m_NumOfThreads - 1; i++ )
{
// compute m_Boundary[i]
float cutOff = 1.0f * ( i + 1 ) * m_ZCumulativeFrequency[m_ZSize - 1] / m_NumOfThreads;
// find the position in the cumulative freq dist where this cutoff is met
for ( j = ( i == 0 ? 0 : m_Boundary[i - 1] ); j < m_ZSize; j++ )
{
if ( cutOff > m_ZCumulativeFrequency[j] )
{
continue;
}
else
{
// do some optimization !
// go further FORWARD and find the first index (k) in the cumulative
// freq distribution s.t. m_ZCumulativeFrequency[k] !=
// m_ZCumulativeFrequency[j]. This is to be done because if we have a
// flat patch in the cum freq dist then ... . we can choose a bound
// midway in that flat patch
unsigned int k;
for ( k = 1; j + k < m_ZSize; k++ )
{
if ( m_ZCumulativeFrequency[j + k] != m_ZCumulativeFrequency[j] )
{
break;
}
}
// if ALL new boundaries same as the original then NO NEED TO DO
// ThreadedLoadBalance() next !!!
auto newBoundary = static_cast< unsigned int >( ( j + ( j + k ) ) / 2 );
if ( newBoundary != m_Boundary[i] )
{
//
m_BoundaryChanged = true;
m_Boundary[i] = newBoundary;
}
break;
}
}
}
if ( m_BoundaryChanged == false )
{
return;
}
// Reset the individual histograms to reflect the new distrbution
// Also reset the mapping from the Z value --> the thread number i.e.
// m_MapZToThreadNumber[]
for ( i = 0; i < m_NumOfThreads; i++ )
{
if ( i != 0 )
{
for ( j = 0; j <= m_Boundary[i - 1]; j++ )
{
m_Data[i].m_ZHistogram[j] = 0;
}
}
for ( j = ( i == 0 ? 0 : m_Boundary[i - 1] + 1 ); j <= m_Boundary[i]; j++ )
{
// this Z histogram value should be given to thread-i
m_Data[i].m_ZHistogram[j] = m_GlobalZHistogram[j];
// this Z belongs to the region associated with thread-i
m_MapZToThreadNumber[j] = i;
}
for ( j = m_Boundary[i] + 1; j < m_ZSize; j++ )
{
m_Data[i].m_ZHistogram[j] = 0;
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedLoadBalance1(ThreadIdType ThreadId)
{
unsigned int i;
// cleanup the layers first
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
for ( ThreadIdType tid = 0; tid < m_NumOfThreads; tid++ )
{
if ( tid == ThreadId )
{
// a thread does NOT pass nodes to istelf
continue;
}
ClearList(ThreadId, m_Data[ThreadId].m_LoadTransferBufferLayers[i][tid]);
}
}
LayerNodeType *nodePtr;
// for all layers
for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
typename LayerType::Iterator layerIt = m_Data[ThreadId].m_Layers[i]->Begin();
typename LayerType::Iterator layerEnd = m_Data[ThreadId].m_Layers[i]->End();
while ( layerIt != layerEnd )
{
nodePtr = layerIt.GetPointer();
++layerIt;
// use the latest (just updated in CheckLoadBalance) boundaries to
// determine to which thread region does the pixel now belong
ThreadIdType tmpId = this->GetThreadNumber(nodePtr->m_Index[m_SplitAxis]);
if ( tmpId != ThreadId ) // this pixel no longer belongs to this thread
{
// remove from the layer
m_Data[ThreadId].m_Layers[i]->Unlink(nodePtr);
// insert temporarily into the special-layers TO BE LATER taken by the
// other thread
// NOTE: What is pushed is a node belonging to the LayerNodeStore of
// ThreadId. This is deleted later (during the start of the next
// SpecialIteration). What is taken by the other thread is NOT this
// node BUT a copy of it.
m_Data[ThreadId].m_LoadTransferBufferLayers[i][tmpId]->PushFront(nodePtr);
}
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedLoadBalance2(ThreadIdType ThreadId)
{
for ( unsigned i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ )
{
// check all other threads
for ( ThreadIdType tid = 0; tid < m_NumOfThreads; tid++ )
{
if ( tid == ThreadId )
{
continue; // exclude oneself
}
CopyInsertList(ThreadId, m_Data[tid].m_LoadTransferBufferLayers[i][ThreadId],
m_Data[ThreadId].m_Layers[i]);
}
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::GetThreadRegionSplitByBoundary(ThreadIdType ThreadId, ThreadRegionType & ThreadRegion)
{
// Initialize the ThreadRegion to the output's requested region
ThreadRegion = m_OutputImage->GetRequestedRegion();
// compute lower bound on the index
typename TOutputImage::IndexType threadRegionIndex = ThreadRegion.GetIndex();
if ( ThreadId != 0 )
{
if ( m_Boundary[ThreadId - 1] < m_Boundary[m_NumOfThreads - 1] )
{
threadRegionIndex[m_SplitAxis] += m_Boundary[ThreadId - 1] + 1;
}
else
{
threadRegionIndex[m_SplitAxis] += m_Boundary[ThreadId - 1];
}
}
ThreadRegion.SetIndex (threadRegionIndex);
// compute the size of the region
typename TOutputImage::SizeType threadRegionSize = ThreadRegion.GetSize();
threadRegionSize[m_SplitAxis] = ( ThreadId == 0
? ( m_Boundary[0] + 1 )
: m_Boundary[ThreadId] - m_Boundary[ThreadId - 1] );
ThreadRegion.SetSize(threadRegionSize);
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::GetThreadRegionSplitUniformly(
ThreadIdType ThreadId, ThreadRegionType & ThreadRegion)
{
// Initialize the ThreadRegion to the output's requested region
ThreadRegion = m_OutputImage->GetRequestedRegion();
typename TOutputImage::IndexType threadRegionIndex = ThreadRegion.GetIndex();
threadRegionIndex[m_SplitAxis] +=
static_cast< unsigned int >( 1.0 * ThreadId * m_ZSize / m_NumOfThreads );
ThreadRegion.SetIndex(threadRegionIndex);
typename TOutputImage::SizeType threadRegionSize = ThreadRegion.GetSize();
// compute lower bound on the index and the size of the region
if ( ThreadId < m_NumOfThreads - 1 ) // this is NOT the last thread
{
threadRegionSize[m_SplitAxis] = static_cast< unsigned int >( 1.0 * ( ThreadId + 1 ) * m_ZSize / m_NumOfThreads )
- static_cast< unsigned int >( 1.0 * ThreadId * m_ZSize / m_NumOfThreads );
}
else
{
threadRegionSize[m_SplitAxis] = m_ZSize
- static_cast< unsigned int >( 1.0 * ThreadId * m_ZSize / m_NumOfThreads );
}
ThreadRegion.SetSize(threadRegionSize);
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::ThreadedPostProcessOutput(const ThreadRegionType & regionToProcess)
{
// Assign background pixels INSIDE the sparse field layers to a new level set
// with value less than the innermost layer. Assign background pixels
// OUTSIDE the sparse field layers to a new level set with value greater than
// the outermost layer.
const auto max_layer = static_cast< ValueType >( m_NumberOfLayers );
const ValueType outside_value = ( max_layer + 1 ) * m_ConstantGradientValue;
const ValueType inside_value = -( max_layer + 1 ) * m_ConstantGradientValue;
ImageRegionConstIterator< StatusImageType > statusIt(m_StatusImage, regionToProcess);
ImageRegionIterator< OutputImageType > outputIt(m_OutputImage, regionToProcess);
for ( outputIt.GoToBegin(), statusIt.GoToBegin();
!outputIt.IsAtEnd(); ++outputIt, ++statusIt )
{
if ( statusIt.Get() == m_StatusNull || statusIt.Get() == m_StatusBoundaryPixel )
{
if ( outputIt.Get() > m_ValueZero )
{
outputIt.Set (outside_value);
}
else
{
outputIt.Set (inside_value);
}
}
}
}
template< typename TInputImage, typename TOutputImage >
unsigned int
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::GetThreadNumber(unsigned int splitAxisValue)
{
return ( m_MapZToThreadNumber[splitAxisValue] );
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::SignalNeighborsAndWait(ThreadIdType ThreadId)
{
// This is the case when a thread has no pixels to process
// This case is analogous to NOT using that thread at all
// Hence this thread does not need to signal / wait for any other neighbor
// thread during the iteration
if ( ThreadId != 0 )
{
if ( m_Boundary[ThreadId - 1] == m_Boundary[ThreadId] )
{
m_Data[ThreadId].m_SemaphoreArrayNumber = 1 - m_Data[ThreadId].m_SemaphoreArrayNumber;
return;
}
}
ThreadIdType lastThreadId = m_NumOfThreads - 1;
if ( lastThreadId == 0 )
{
return; // only 1 thread => no need to wait
}
// signal neighbors that work is done
if ( ThreadId != 0 ) // not the first thread
{
this->SignalNeighbor( m_Data[ThreadId].m_SemaphoreArrayNumber,
this->GetThreadNumber (m_Boundary[ThreadId - 1]) );
}
if ( m_Boundary[ThreadId] != m_ZSize - 1 ) // not the last thread
{
this->SignalNeighbor ( m_Data[ThreadId].m_SemaphoreArrayNumber,
this->GetThreadNumber (m_Boundary[ThreadId] + 1) );
}
// wait for signal from neighbors signifying that their work is done
if ( ( ThreadId == 0 ) || ( m_Boundary[ThreadId] == m_ZSize - 1 ) )
{
// do it just once for the first and the last threads because they share
// just 1 boundary (just 1 neighbor)
this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
m_Data[ThreadId].m_SemaphoreArrayNumber = 1 - m_Data[ThreadId].m_SemaphoreArrayNumber;
}
else
{
// do twice because share 2 boundaries with neighbors
this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
this->WaitForNeighbor (m_Data[ThreadId].m_SemaphoreArrayNumber, ThreadId);
m_Data[ThreadId].m_SemaphoreArrayNumber = 1 - m_Data[ThreadId].m_SemaphoreArrayNumber;
}
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::SignalNeighbor(
unsigned int SemaphoreArrayNumber,
ThreadIdType ThreadId)
{
ThreadData &td = m_Data[ThreadId];
td.m_Lock[SemaphoreArrayNumber].lock();
++td.m_Semaphore[SemaphoreArrayNumber];
td.m_Condition[SemaphoreArrayNumber].notify_one();
td.m_Lock[SemaphoreArrayNumber].unlock();
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::WaitForNeighbor(unsigned int SemaphoreArrayNumber, ThreadIdType ThreadId)
{
ThreadData &td = m_Data[ThreadId];
std::unique_lock< std::mutex > mutexHolder( td.m_Lock[SemaphoreArrayNumber] );
if ( td.m_Semaphore[SemaphoreArrayNumber] == 0 )
{
td.m_Condition[SemaphoreArrayNumber].wait( mutexHolder, [&td, SemaphoreArrayNumber]
{ return (td.m_Semaphore[SemaphoreArrayNumber] != 0); } );
}
--td.m_Semaphore[SemaphoreArrayNumber];
}
template< typename TInputImage, typename TOutputImage >
void
ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
unsigned int i;
os << indent << "m_NumberOfLayers: " << NumericTraits< StatusType >::PrintType( this->GetNumberOfLayers() )
<< std::endl;
os << indent << "m_IsoSurfaceValue: " << this->GetIsoSurfaceValue() << std::endl;
os << indent << "m_LayerNodeStore: " << m_LayerNodeStore;
ThreadIdType ThreadId;
for ( ThreadId = 0; ThreadId < m_NumOfThreads; ThreadId++ )
{
os << indent << "ThreadId: " << ThreadId << std::endl;
if ( m_Data != nullptr )
{
for ( i = 0; i < m_Data[ThreadId].m_Layers.size(); i++ )
{
os << indent << "m_Layers[" << i << "]: size="
<< m_Data[ThreadId].m_Layers[i]->Size() << std::endl;
os << indent << m_Data[ThreadId].m_Layers[i];
}
}
}
}
} // end namespace itk
#endif
|
#pragma once
#include <handlegraph/types.hpp>
#include <handlegraph/util.hpp>
#include <handlegraph/path_handle_graph.hpp>
namespace odgi {
namespace algorithms {
using namespace handlegraph;
bool nodes_are_perfect_path_neighbors(const PathHandleGraph& graph, handle_t left_handle, handle_t right_handle);
}
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "QEnumWidget.h"
#include "BaseVariableWidget.h"
#include "Utils.h"
#include "AttributeItem.h"
#include <Util/Variable.h>
#include <QTimer>
#include "AttributeView.h"
#include "IEditorParticleUtils.h"
QEnumWidget::QEnumWidget(CAttributeItem* parent)
: CBaseVariableWidget(parent)
, QComboBox(parent)
, m_isShown(false)
, m_lineEditPressed(false)
{
setFocusPolicy(Qt::StrongFocus);
installEventFilter(parent);
QStringList list;
IVarEnumList* enumList = m_var->GetEnumList();
if (enumList)
{
for (uint i = 0; !enumList->GetItemName(i).isNull(); i++)
{
list.push_back(enumList->GetItemName(i));
}
}
else
{
list.push_back("INVALID_ENUM_LIST");
}
addItems(list);
setEditable(true);
installEventFilter(this);
//This sub control (especially the alignment) is un-stylable via QSS global stylesheets, so we have to style it through lineEdit
lineEdit()->setReadOnly(true);
lineEdit()->setStyleSheet("*{background: transparent; border: 0px none red;}");
lineEdit()->setAlignment(Qt::AlignRight);
lineEdit()->installEventFilter(this);
for (int i = 0; i < count(); i++)
{
setItemData(i, Qt::AlignRight, Qt::TextAlignmentRole);
}
QString selection;
m_var->Get(selection);
int selectedIdx = findText(QString(selection));
if (selectedIdx != -1)
{
setCurrentIndex(selectedIdx);
}
// connect to particle variable
connect(this, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::activated), this, &QEnumWidget::onUserChange);
m_tooltip = new QToolTipWidget(this);
}
QEnumWidget::~QEnumWidget()
{
}
void QEnumWidget::onVarChanged(IVariable* var)
{
SelfCallFence(m_ignoreSetCallback);
QString selection;
var->Get(selection);
int selectedIdx = findText(QString(selection));
if (selectedIdx != -1)
{
QSignalBlocker blocker(this);
setCurrentIndex(selectedIdx);
//change style sheet for line edit when selection changed
if (!qobject_cast<QStandardItemModel *>(model())->item(selectedIdx)->isEnabled())
{
lineEdit()->setStyleSheet("QLineEdit {background: #ff585858; border: 0px none red; color: #ff808080;}");
}
else
{
lineEdit()->setStyleSheet("*{background: transparent; border: 0px none red;}");
}
}
m_parent->UILogicUpdateCallback();
}
bool QEnumWidget::event(QEvent* e)
{
switch (e->type())
{
case QEvent::ToolTip:
{
QHelpEvent* event = (QHelpEvent*)e;
GetIEditor()->GetParticleUtils()->ToolTip_BuildFromConfig(m_tooltip, m_parent->getAttributeView()->GetVariablePath(m_var), "ComboBox", QString(m_var->GetDisplayValue()));
m_tooltip->TryDisplay(event->globalPos(), this, QToolTipWidget::ArrowDirection::ARROW_RIGHT);
return true;
break;
}
case QEvent::Leave:
{
if (m_tooltip)
{
m_tooltip->close();
}
QCoreApplication::instance()->removeEventFilter(this); //Release filter (Only if we have a tooltip?)
break;
}
default:
break;
}
return QComboBox::event(e);
}
bool QEnumWidget::eventFilter(QObject* obj, QEvent* event)
{
if (isEnabled())
{
//handle the mouse press/release if the mouse is click on the lineEdit
if (event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::MouseButtonPress)
{
bool isClickLineEdit = false;
QMouseEvent* mouseEvt = static_cast<QMouseEvent*>(event);
QRect rect = lineEdit()->geometry();
QPoint scnPos = QPoint(static_cast<int>(mouseEvt->screenPos().x()), static_cast<int>(mouseEvt->screenPos().y()));
QPoint mousePos = lineEdit()->mapFromGlobal(scnPos);
if (mouseEvt->button() == Qt::LeftButton && rect.contains(mousePos))
{
isClickLineEdit = true;
}
if (mouseEvt->button() == Qt::LeftButton && event->type() == QEvent::MouseButtonRelease)
{
m_lineEditPressed = false;
}
if (isClickLineEdit)
{
//Note: when the popup menu is not showing, the lineEdit object recieves the mouse button press event. Otherwise the ComboBoxPrivateContainer
// will recieve the press event instead of lineEdit.
if (event->type() == QEvent::MouseButtonPress)
{
if (!m_lineEditPressed)
{
//Use m_lineEditPressed to make sure the press event only be handled once.
//This is because if we call hidePopup for ComboBoxPrivateContainer's mouse press event,
//the LineEdit will receive the mouse press event in the same frame which always open popup menu after close it.
m_lineEditPressed = true;
if (!IsPopupShowing())
{
showPopup();
}
else
{ //hide popup when popup is showing
hidePopup();
}
}
}
//Disable press and release handle for children objects.
return true;
}
}
else if (event->type() == QEvent::Wheel)
{
// We used to clear the focus in onUserChange(), but the wheel behavior was still is odd (you can only
// scroll one space up/down and then focus is cleared). So we just prevent all wheel events.
return true;
}
}
return QComboBox::eventFilter(obj, event);
}
bool QEnumWidget::IsPopupShowing()
{
//Note: this function won't return true in the same frame after called showPopup.
QStyleOptionComboBox opt;
initStyleOption(&opt);
return (opt.state & QStyle::State_On);
}
void QEnumWidget::onUserChange(const QString& text)
{
//if the option wasn't changed, return
QString str = m_var->GetDisplayValue();
if (text.compare(str, Qt::CaseInsensitive) == 0)
{
//nothing needs to happen
}
//only apply change if the the change is accepted
else if (!m_parent->getAttributeView()->ValidateUserChangeEnum(m_var, text))
{
//reset selection from m_var
QString selection;
m_var->Get(selection);
int selectedIdx = findText(QString(selection));
if (selectedIdx != -1)
{
QSignalBlocker blocker(this);
setCurrentIndex(selectedIdx);
}
}
else if (!m_parent->getAttributeView()->HandleUserChangedEnum(m_var, text))
{
m_var->SetDisplayValue(text.toUtf8().data());
emit m_parent->SignalEnumChanged();
emit m_parent->SignalUndoPoint();
}
}
void QEnumWidget::showPopup()
{
QComboBox::showPopup();
//we need add event filter to QComboBoxPrivateContainer so we can block the mouse left button release on lineEdit when popup menu is showing
//the instance only was created after the popup menu first shown. Since there is no way to find out which QObject is QComboBoxPrivateContainer,
//we add event filter to all direct children (actually four) here.
if (!m_isShown)
{
m_isShown = true;
QObjectList objs = children();
for (int i = 0; i< objs.size(); i++)
{
QObject* obj = objs[i];
obj->installEventFilter(this);
}
}
}
void QEnumWidget::SetItemEnable(int itemIdx, bool enable)
{
qobject_cast<QStandardItemModel *>(model())->item(itemIdx)->setEnabled(enable);
}
|
#include <memory>
#include <string>
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/config/core/v3/config_source.pb.h"
#include "envoy/extensions/transport_sockets/tls/v3/cert.pb.h"
#include "envoy/service/discovery/v3/discovery.pb.h"
#include "envoy/service/secret/v3/sds.pb.h"
#include "common/config/api_version.h"
#include "common/event/dispatcher_impl.h"
#include "common/http/utility.h"
#include "common/network/connection_impl.h"
#include "common/network/utility.h"
#include "extensions/transport_sockets/tls/context_config_impl.h"
#include "extensions/transport_sockets/tls/context_manager_impl.h"
#include "extensions/transport_sockets/tls/ssl_socket.h"
#include "test/common/grpc/grpc_client_integration.h"
#include "test/config/integration/certs/clientcert_hash.h"
#include "test/integration/http_integration.h"
#include "test/integration/server.h"
#include "test/integration/ssl_utility.h"
#include "test/mocks/secret/mocks.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/resources.h"
#include "test/test_common/test_time_system.h"
#include "test/test_common/utility.h"
#include "absl/strings/match.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integration.h"
#include "utility.h"
namespace Envoy {
namespace Ssl {
// Hack to force linking of the service: https://github.com/google/protobuf/issues/4221.
const envoy::service::secret::v3::SdsDummy _sds_dummy;
// Sds integration base class with following support:
// * functions to create sds upstream, and send sds response
// * functions to create secret protobuf.
class SdsDynamicIntegrationBaseTest : public Grpc::GrpcClientIntegrationParamTest,
public HttpIntegrationTest {
public:
SdsDynamicIntegrationBaseTest()
: HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion()),
server_cert_("server_cert"), validation_secret_("validation_secret"),
client_cert_("client_cert") {}
protected:
void createSdsStream(FakeUpstream&) {
createXdsConnection();
AssertionResult result2 = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);
RELEASE_ASSERT(result2, result2.message());
xds_stream_->startGrpcStream();
}
void setUpSdsConfig(envoy::extensions::transport_sockets::tls::v3::SdsSecretConfig* secret_config,
const std::string& secret_name) {
secret_config->set_name(secret_name);
auto* config_source = secret_config->mutable_sds_config();
config_source->set_resource_api_version(envoy::config::core::v3::ApiVersion::V3);
auto* api_config_source = config_source->mutable_api_config_source();
api_config_source->set_api_type(envoy::config::core::v3::ApiConfigSource::GRPC);
api_config_source->set_transport_api_version(envoy::config::core::v3::V3);
auto* grpc_service = api_config_source->add_grpc_services();
setGrpcService(*grpc_service, "sds_cluster", fake_upstreams_.back()->localAddress());
}
envoy::extensions::transport_sockets::tls::v3::Secret getServerSecret() {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(server_cert_);
auto* tls_certificate = secret.mutable_tls_certificate();
tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/servercert.pem"));
tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/serverkey.pem"));
return secret;
}
envoy::extensions::transport_sockets::tls::v3::Secret getCvcSecret() {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(validation_secret_);
auto* validation_context = secret.mutable_validation_context();
validation_context->mutable_trusted_ca()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/cacert.pem"));
validation_context->add_verify_certificate_hash(TEST_CLIENT_CERT_HASH);
return secret;
}
envoy::extensions::transport_sockets::tls::v3::Secret getCvcSecretWithOnlyTrustedCa() {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(validation_secret_);
auto* validation_context = secret.mutable_validation_context();
validation_context->mutable_trusted_ca()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/cacert.pem"));
return secret;
}
envoy::extensions::transport_sockets::tls::v3::Secret getClientSecret() {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(client_cert_);
auto* tls_certificate = secret.mutable_tls_certificate();
tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientcert.pem"));
tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientkey.pem"));
return secret;
}
envoy::extensions::transport_sockets::tls::v3::Secret
getWrongSecret(const std::string& secret_name) {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(secret_name);
secret.mutable_tls_certificate();
return secret;
}
void sendSdsResponse(const envoy::extensions::transport_sockets::tls::v3::Secret& secret) {
envoy::service::discovery::v3::DiscoveryResponse discovery_response;
discovery_response.set_version_info("1");
discovery_response.set_type_url(Config::TypeUrl::get().Secret);
discovery_response.add_resources()->PackFrom(secret);
xds_stream_->sendGrpcMessage(discovery_response);
}
void PrintServerCounters() {
std::cerr << "all counters" << std::endl;
for (const auto& c : test_server_->counters()) {
std::cerr << "counter: " << c->name() << ", value: " << c->value() << std::endl;
}
}
const std::string server_cert_;
const std::string validation_secret_;
const std::string client_cert_;
bool v3_resource_api_{false};
};
// Downstream SDS integration test: static Listener with ssl cert from SDS
class SdsDynamicDownstreamIntegrationTest : public SdsDynamicIntegrationBaseTest {
public:
void initialize() override {
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;
auto* common_tls_context = tls_context.mutable_common_tls_context();
auto* transport_socket = bootstrap.mutable_static_resources()
->mutable_listeners(0)
->mutable_filter_chains(0)
->mutable_transport_socket();
common_tls_context->add_alpn_protocols(Http::Utility::AlpnNames::get().Http11);
auto* validation_context = common_tls_context->mutable_validation_context();
validation_context->mutable_trusted_ca()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/cacert.pem"));
validation_context->add_verify_certificate_hash(TEST_CLIENT_CERT_HASH);
// Modify the listener ssl cert to use SDS from sds_cluster
auto* secret_config = common_tls_context->add_tls_certificate_sds_secret_configs();
setUpSdsConfig(secret_config, "server_cert");
transport_socket->set_name("envoy.transport_sockets.tls");
transport_socket->mutable_typed_config()->PackFrom(tls_context);
// Add a static sds cluster
auto* sds_cluster = bootstrap.mutable_static_resources()->add_clusters();
sds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
sds_cluster->set_name("sds_cluster");
ConfigHelper::setHttp2(*sds_cluster);
});
HttpIntegrationTest::initialize();
client_ssl_ctx_ = createClientSslTransportSocketFactory({}, context_manager_, *api_);
}
void createUpstreams() override {
create_xds_upstream_ = true;
HttpIntegrationTest::createUpstreams();
}
void TearDown() override {
cleanUpXdsConnection();
client_ssl_ctx_.reset();
}
Network::ClientConnectionPtr makeSslClientConnection() {
Network::Address::InstanceConstSharedPtr address = getSslAddress(version_, lookupPort("http"));
return dispatcher_->createClientConnection(address, Network::Address::InstanceConstSharedPtr(),
client_ssl_ctx_->createTransportSocket(nullptr),
nullptr);
}
protected:
Network::TransportSocketFactoryPtr client_ssl_ctx_;
};
INSTANTIATE_TEST_SUITE_P(IpVersionsClientType, SdsDynamicDownstreamIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
class SdsDynamicKeyRotationIntegrationTest : public SdsDynamicDownstreamIntegrationTest {
protected:
envoy::extensions::transport_sockets::tls::v3::Secret getCurrentServerSecret() {
envoy::extensions::transport_sockets::tls::v3::Secret secret;
secret.set_name(server_cert_);
auto* tls_certificate = secret.mutable_tls_certificate();
tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::temporaryPath("root/current/servercert.pem"));
tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::temporaryPath("root/current/serverkey.pem"));
auto* watched_directory = tls_certificate->mutable_watched_directory();
watched_directory->set_path(TestEnvironment::temporaryPath("root"));
return secret;
}
};
// We don't care about multiple gRPC types here, Envoy gRPC is fine, the
// interest is on the filesystem.
INSTANTIATE_TEST_SUITE_P(
IpVersionsClientType, SdsDynamicKeyRotationIntegrationTest,
testing::Combine(testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
testing::Values(Grpc::ClientType::EnvoyGrpc)));
// Validate that a basic key-cert rotation works via symlink rename.
TEST_P(SdsDynamicKeyRotationIntegrationTest, BasicRotation) {
v3_resource_api_ = true;
TestEnvironment::exec(
{TestEnvironment::runfilesPath("test/integration/sds_dynamic_key_rotation_setup.sh")});
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCurrentServerSecret());
};
initialize();
// Initial update from filesystem.
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1);
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
// First request with server{cert,key}.pem.
testRouterHeaderOnlyRequestAndResponse(&creator);
cleanupUpstreamAndDownstream();
// Rotate.
TestEnvironment::renameFile(TestEnvironment::temporaryPath("root/new"),
TestEnvironment::temporaryPath("root/current"));
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 2);
// The rotation is not a SDS attempt, so no change to these stats.
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.server_cert.update_rejected")->value());
// First request with server_ecdsa{cert,key}.pem.
testRouterHeaderOnlyRequestAndResponse(&creator);
}
// Validate that rotating to a directory with missing certs is handled.
TEST_P(SdsDynamicKeyRotationIntegrationTest, EmptyRotation) {
v3_resource_api_ = true;
TestEnvironment::exec(
{TestEnvironment::runfilesPath("test/integration/sds_dynamic_key_rotation_setup.sh")});
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCurrentServerSecret());
};
initialize();
// Initial update from filesystem.
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1);
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
// First request with server{cert,key}.pem.
testRouterHeaderOnlyRequestAndResponse(&creator);
cleanupUpstreamAndDownstream();
// Rotate to an empty directory, this should fail.
TestEnvironment::renameFile(TestEnvironment::temporaryPath("root/empty"),
TestEnvironment::temporaryPath("root/current"));
test_server_->waitForCounterEq("sds.server_cert.key_rotation_failed", 1);
EXPECT_EQ(1,
test_server_
->counter(listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"))
->value());
// The rotation is not a SDS attempt, so no change to these stats.
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.server_cert.update_rejected")->value());
// Requests continue to work with key/cert pair.
testRouterHeaderOnlyRequestAndResponse(&creator);
}
// A test that SDS server send a good server secret for a static listener.
// The first ssl request should be OK.
TEST_P(SdsDynamicDownstreamIntegrationTest, BasicSuccess) {
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getServerSecret());
};
initialize();
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.server_cert.update_rejected")->value());
}
// A test that SDS server send a bad secret for a static listener,
// The first ssl request should fail at connecting.
// then SDS send a good server secret, the second request should be OK.
TEST_P(SdsDynamicDownstreamIntegrationTest, WrongSecretFirst) {
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getWrongSecret(server_cert_));
};
initialize();
codec_client_ = makeRawHttpConnection(makeSslClientConnection(), absl::nullopt);
// the connection state is not connected.
EXPECT_FALSE(codec_client_->connected());
codec_client_->connection()->close(Network::ConnectionCloseType::NoFlush);
// Failure
EXPECT_EQ(0, test_server_->counter("sds.server_cert.update_success")->value());
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_rejected")->value());
sendSdsResponse(getServerSecret());
// Wait for ssl_context_updated_by_sds counter.
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1);
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_success")->value());
EXPECT_EQ(1, test_server_->counter("sds.server_cert.update_rejected")->value());
}
class SdsDynamicDownstreamCertValidationContextTest : public SdsDynamicDownstreamIntegrationTest {
public:
SdsDynamicDownstreamCertValidationContextTest() = default;
void initialize() override {
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
auto* transport_socket = bootstrap.mutable_static_resources()
->mutable_listeners(0)
->mutable_filter_chains(0)
->mutable_transport_socket();
envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;
auto* common_tls_context = tls_context.mutable_common_tls_context();
common_tls_context->add_alpn_protocols(Http::Utility::AlpnNames::get().Http11);
auto* tls_certificate = common_tls_context->add_tls_certificates();
tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/servercert.pem"));
tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/serverkey.pem"));
setUpSdsValidationContext(common_tls_context);
transport_socket->set_name("envoy.transport_sockets.tls");
transport_socket->mutable_typed_config()->PackFrom(tls_context);
// Add a static sds cluster
auto* sds_cluster = bootstrap.mutable_static_resources()->add_clusters();
sds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
sds_cluster->set_name("sds_cluster");
ConfigHelper::setHttp2(*sds_cluster);
envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext upstream_tls_context;
if (share_validation_secret_) {
// Configure static cluster with SDS config referencing "validation_secret",
// which is going to be processed before LDS resources.
ASSERT(use_lds_);
setUpSdsValidationContext(upstream_tls_context.mutable_common_tls_context());
}
// Enable SSL/TLS with a client certificate in the first cluster.
auto* upstream_tls_certificate =
upstream_tls_context.mutable_common_tls_context()->add_tls_certificates();
upstream_tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientcert.pem"));
upstream_tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientkey.pem"));
auto* upstream_transport_socket =
bootstrap.mutable_static_resources()->mutable_clusters(0)->mutable_transport_socket();
upstream_transport_socket->set_name("envoy.transport_sockets.tls");
upstream_transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
});
HttpIntegrationTest::initialize();
registerTestServerPorts({"http"});
client_ssl_ctx_ = createClientSslTransportSocketFactory({}, context_manager_, *api_);
}
void setUpSdsValidationContext(
envoy::extensions::transport_sockets::tls::v3::CommonTlsContext* common_tls_context) {
if (use_combined_validation_context_) {
// Modify the listener context validation type to use combined certificate validation
// context.
auto* combined_config = common_tls_context->mutable_combined_validation_context();
auto* default_validation_context = combined_config->mutable_default_validation_context();
default_validation_context->add_verify_certificate_hash(TEST_CLIENT_CERT_HASH);
auto* secret_config = combined_config->mutable_validation_context_sds_secret_config();
setUpSdsConfig(secret_config, validation_secret_);
} else {
// Modify the listener context validation type to use dynamic certificate validation
// context.
auto* secret_config = common_tls_context->mutable_validation_context_sds_secret_config();
setUpSdsConfig(secret_config, validation_secret_);
}
}
void createUpstreams() override {
// Fake upstream with SSL/TLS for the first cluster.
addFakeUpstream(createUpstreamSslContext(), FakeHttpConnection::Type::HTTP1);
create_xds_upstream_ = true;
}
Network::TransportSocketFactoryPtr createUpstreamSslContext() {
envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;
auto* common_tls_context = tls_context.mutable_common_tls_context();
auto* tls_certificate = common_tls_context->add_tls_certificates();
tls_certificate->mutable_certificate_chain()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientcert.pem"));
tls_certificate->mutable_private_key()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/clientkey.pem"));
auto cfg = std::make_unique<Extensions::TransportSockets::Tls::ServerContextConfigImpl>(
tls_context, factory_context_);
static Stats::Scope* upstream_stats_store = new Stats::TestIsolatedStoreImpl();
return std::make_unique<Extensions::TransportSockets::Tls::ServerSslSocketFactory>(
std::move(cfg), context_manager_, *upstream_stats_store, std::vector<std::string>{});
}
void TearDown() override {
cleanUpXdsConnection();
client_ssl_ctx_.reset();
cleanupUpstreamAndDownstream();
codec_client_.reset();
}
void enableCombinedValidationContext(bool enable) { use_combined_validation_context_ = enable; }
void shareValidationSecret(bool share) { share_validation_secret_ = share; }
private:
bool use_combined_validation_context_{false};
bool share_validation_secret_{false};
};
INSTANTIATE_TEST_SUITE_P(IpVersionsClientType, SdsDynamicDownstreamCertValidationContextTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
// A test that SDS server send a good certificate validation context for a static listener.
// The first ssl request should be OK.
TEST_P(SdsDynamicDownstreamCertValidationContextTest, BasicSuccess) {
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCvcSecret());
};
initialize();
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.validation_secret.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.validation_secret.update_rejected")->value());
}
// A test that SDS server sends a certificate validation context for a static listener.
// Listener combines default certificate validation context and the dynamic one.
// The first ssl request should be OK.
TEST_P(SdsDynamicDownstreamCertValidationContextTest, CombinedCertValidationContextSuccess) {
enableCombinedValidationContext(true);
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCvcSecretWithOnlyTrustedCa());
};
initialize();
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.validation_secret.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.validation_secret.update_rejected")->value());
}
// A test that verifies that both: static cluster and LDS listener are updated when using
// the same verification secret (standalone validation context) from the SDS server.
TEST_P(SdsDynamicDownstreamCertValidationContextTest, BasicWithSharedSecret) {
shareValidationSecret(true);
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCvcSecret());
};
initialize();
// Wait for "ssl_context_updated_by_sds" counters to indicate that both resources
// depending on the verification_secret were updated.
test_server_->waitForCounterGe(
"cluster.cluster_0.client_ssl_socket_factory.ssl_context_update_by_sds", 1);
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1);
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.validation_secret.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.validation_secret.update_rejected")->value());
}
// A test that verifies that both: static cluster and LDS listener are updated when using
// the same verification secret (combined validation context) from the SDS server.
TEST_P(SdsDynamicDownstreamCertValidationContextTest, CombinedValidationContextWithSharedSecret) {
enableCombinedValidationContext(true);
shareValidationSecret(true);
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getCvcSecretWithOnlyTrustedCa());
};
initialize();
// Wait for "ssl_context_updated_by_sds" counters to indicate that both resources
// depending on the verification_secret were updated.
test_server_->waitForCounterGe(
"cluster.cluster_0.client_ssl_socket_factory.ssl_context_update_by_sds", 1);
test_server_->waitForCounterGe(
listenerStatPrefix("server_ssl_socket_factory.ssl_context_update_by_sds"), 1);
ConnectionCreationFunction creator = [&]() -> Network::ClientConnectionPtr {
return makeSslClientConnection();
};
testRouterHeaderOnlyRequestAndResponse(&creator);
// Success
EXPECT_EQ(1, test_server_->counter("sds.validation_secret.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.validation_secret.update_rejected")->value());
}
// Upstream SDS integration test: a static cluster has ssl cert from SDS.
class SdsDynamicUpstreamIntegrationTest : public SdsDynamicIntegrationBaseTest {
public:
void initialize() override {
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
// add sds cluster first.
auto* sds_cluster = bootstrap.mutable_static_resources()->add_clusters();
sds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
sds_cluster->set_name("sds_cluster");
ConfigHelper::setHttp2(*sds_cluster);
// change the first cluster with ssl and sds.
auto* transport_socket =
bootstrap.mutable_static_resources()->mutable_clusters(0)->mutable_transport_socket();
envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext tls_context;
auto* secret_config =
tls_context.mutable_common_tls_context()->add_tls_certificate_sds_secret_configs();
setUpSdsConfig(secret_config, "client_cert");
transport_socket->set_name("envoy.transport_sockets.tls");
transport_socket->mutable_typed_config()->PackFrom(tls_context);
});
HttpIntegrationTest::initialize();
registerTestServerPorts({"http"});
}
void TearDown() override {
cleanUpXdsConnection();
cleanupUpstreamAndDownstream();
codec_client_.reset();
test_server_.reset();
fake_upstreams_.clear();
}
void createUpstreams() override {
// This is for backend with ssl
addFakeUpstream(createUpstreamSslContext(context_manager_, *api_),
FakeHttpConnection::Type::HTTP1);
create_xds_upstream_ = true;
}
};
INSTANTIATE_TEST_SUITE_P(IpVersions, SdsDynamicUpstreamIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
// To test a static cluster with sds. SDS send a good client secret first.
// The first request should work.
TEST_P(SdsDynamicUpstreamIntegrationTest, BasicSuccess) {
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getClientSecret());
};
initialize();
// There is a race condition here; there are two static clusters:
// backend cluster_0 with sds and sds_cluster. cluster_0 is created first, its init_manager
// is called so it issues a sds call, but fail since sds_cluster is not added yet.
// so cluster_0 is initialized with an empty secret. initialize() will not wait and will return.
// the testing request will be called, even though in the pre_worker_function, a good sds is
// send, the cluster will be updated with good secret, the testing request may fail if it is
// before context is updated. Hence, need to wait for context_update counter.
test_server_->waitForCounterGe(
"cluster.cluster_0.client_ssl_socket_factory.ssl_context_update_by_sds", 1);
testRouterHeaderOnlyRequestAndResponse();
// Success
EXPECT_EQ(1, test_server_->counter("sds.client_cert.update_success")->value());
EXPECT_EQ(0, test_server_->counter("sds.client_cert.update_rejected")->value());
}
// To test a static cluster with sds. SDS send a bad client secret first.
// The first request should fail with 503, then SDS sends a good client secret,
// the second request should work.
TEST_P(SdsDynamicUpstreamIntegrationTest, WrongSecretFirst) {
on_server_init_function_ = [this]() {
createSdsStream(*(fake_upstreams_[1]));
sendSdsResponse(getWrongSecret(client_cert_));
};
initialize();
// Make a simple request, should get 503
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "GET", "/test/long/url", "", downstream_protocol_, version_);
ASSERT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().getStatusValue());
// To flush out the reset connection from the first request in upstream.
FakeRawConnectionPtr fake_upstream_connection;
ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection));
ASSERT_TRUE(fake_upstream_connection->waitForDisconnect());
// Failure
EXPECT_EQ(0, test_server_->counter("sds.client_cert.update_success")->value());
EXPECT_EQ(1, test_server_->counter("sds.client_cert.update_rejected")->value());
sendSdsResponse(getClientSecret());
test_server_->waitForCounterGe(
"cluster.cluster_0.client_ssl_socket_factory.ssl_context_update_by_sds", 1);
testRouterHeaderOnlyRequestAndResponse();
// Success
EXPECT_EQ(1, test_server_->counter("sds.client_cert.update_success")->value());
EXPECT_EQ(1, test_server_->counter("sds.client_cert.update_rejected")->value());
}
// Test CDS with SDS. A cluster provided by CDS raises new SDS request for upstream cert.
class SdsCdsIntegrationTest : public SdsDynamicIntegrationBaseTest {
public:
void initialize() override {
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
// Create the dynamic cluster. This cluster will be using sds.
dynamic_cluster_ = bootstrap.mutable_static_resources()->clusters(0);
dynamic_cluster_.set_name("dynamic");
dynamic_cluster_.mutable_connect_timeout()->MergeFrom(
ProtobufUtil::TimeUtil::MillisecondsToDuration(500000));
auto* transport_socket = dynamic_cluster_.mutable_transport_socket();
envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext tls_context;
auto* secret_config =
tls_context.mutable_common_tls_context()->add_tls_certificate_sds_secret_configs();
setUpSdsConfig(secret_config, "client_cert");
transport_socket->set_name("envoy.transport_sockets.tls");
transport_socket->mutable_typed_config()->PackFrom(tls_context);
// Add cds cluster first.
auto* cds_cluster = bootstrap.mutable_static_resources()->add_clusters();
cds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
cds_cluster->set_name("cds_cluster");
ConfigHelper::setHttp2(*cds_cluster);
// Then add sds cluster.
auto* sds_cluster = bootstrap.mutable_static_resources()->add_clusters();
sds_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
sds_cluster->set_name("sds_cluster");
ConfigHelper::setHttp2(*sds_cluster);
const std::string cds_yaml = R"EOF(
resource_api_version: V3
api_config_source:
api_type: GRPC
transport_api_version: V3
grpc_services:
envoy_grpc:
cluster_name: cds_cluster
set_node_on_first_message_only: true
)EOF";
auto* cds = bootstrap.mutable_dynamic_resources()->mutable_cds_config();
TestUtility::loadFromYaml(cds_yaml, *cds);
});
HttpIntegrationTest::initialize();
}
void TearDown() override {
{
AssertionResult result = sds_connection_->close();
RELEASE_ASSERT(result, result.message());
result = sds_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
sds_connection_.reset();
}
cleanUpXdsConnection();
cleanupUpstreamAndDownstream();
codec_client_.reset();
test_server_.reset();
fake_upstreams_.clear();
}
void createUpstreams() override {
// Static cluster.
addFakeUpstream(FakeHttpConnection::Type::HTTP1);
// Cds Cluster.
addFakeUpstream(FakeHttpConnection::Type::HTTP2);
// Sds Cluster.
addFakeUpstream(FakeHttpConnection::Type::HTTP2);
}
void sendCdsResponse() {
EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "", {}, {}, {}, true));
sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(
Config::TypeUrl::get().Cluster, {dynamic_cluster_}, {dynamic_cluster_}, {}, "55");
}
void sendSdsResponse2(const envoy::extensions::transport_sockets::tls::v3::Secret& secret,
FakeStream& sds_stream) {
envoy::service::discovery::v3::DiscoveryResponse discovery_response;
discovery_response.set_version_info("1");
discovery_response.set_type_url(Config::TypeUrl::get().Secret);
discovery_response.add_resources()->PackFrom(secret);
sds_stream.sendGrpcMessage(discovery_response);
}
envoy::config::cluster::v3::Cluster dynamic_cluster_;
FakeHttpConnectionPtr sds_connection_;
FakeStreamPtr sds_stream_;
};
INSTANTIATE_TEST_SUITE_P(IpVersions, SdsCdsIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS);
TEST_P(SdsCdsIntegrationTest, BasicSuccess) {
on_server_init_function_ = [this]() {
{
// CDS.
AssertionResult result =
fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, xds_connection_);
RELEASE_ASSERT(result, result.message());
result = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);
RELEASE_ASSERT(result, result.message());
xds_stream_->startGrpcStream();
sendCdsResponse();
}
{
// SDS.
AssertionResult result =
fake_upstreams_[2]->waitForHttpConnection(*dispatcher_, sds_connection_);
RELEASE_ASSERT(result, result.message());
result = sds_connection_->waitForNewStream(*dispatcher_, sds_stream_);
RELEASE_ASSERT(result, result.message());
sds_stream_->startGrpcStream();
sendSdsResponse2(getClientSecret(), *sds_stream_);
}
};
initialize();
test_server_->waitForCounterGe(
"cluster.dynamic.client_ssl_socket_factory.ssl_context_update_by_sds", 1);
// The 4 clusters are CDS,SDS,static and dynamic cluster.
test_server_->waitForGaugeGe("cluster_manager.active_clusters", 4);
sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(Config::TypeUrl::get().Cluster, {}, {},
{}, "42");
// Successfully removed the dynamic cluster.
test_server_->waitForGaugeEq("cluster_manager.active_clusters", 3);
}
} // namespace Ssl
} // namespace Envoy
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: Valve.VR.EVRTrackedCameraFrameType
#include "Valve/VR/EVRTrackedCameraFrameType.hpp"
// Including type: Valve.VR.TrackedDevicePose_t
#include "Valve/VR/TrackedDevicePose_t.hpp"
// Completed includes
// Type namespace: Valve.VR
namespace Valve::VR {
// Size: 0x62
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: Valve.VR.CameraVideoStreamFrameHeader_t
// [TokenAttribute] Offset: FFFFFFFF
struct CameraVideoStreamFrameHeader_t/*, public System::ValueType*/ {
public:
// public Valve.VR.EVRTrackedCameraFrameType eFrameType
// Size: 0x4
// Offset: 0x0
Valve::VR::EVRTrackedCameraFrameType eFrameType;
// Field size check
static_assert(sizeof(Valve::VR::EVRTrackedCameraFrameType) == 0x4);
// public System.UInt32 nWidth
// Size: 0x4
// Offset: 0x4
uint nWidth;
// Field size check
static_assert(sizeof(uint) == 0x4);
// public System.UInt32 nHeight
// Size: 0x4
// Offset: 0x8
uint nHeight;
// Field size check
static_assert(sizeof(uint) == 0x4);
// public System.UInt32 nBytesPerPixel
// Size: 0x4
// Offset: 0xC
uint nBytesPerPixel;
// Field size check
static_assert(sizeof(uint) == 0x4);
// public System.UInt32 nFrameSequence
// Size: 0x4
// Offset: 0x10
uint nFrameSequence;
// Field size check
static_assert(sizeof(uint) == 0x4);
// public Valve.VR.TrackedDevicePose_t standingTrackedDevicePose
// Size: 0x4E
// Offset: 0x14
Valve::VR::TrackedDevicePose_t standingTrackedDevicePose;
// Field size check
static_assert(sizeof(Valve::VR::TrackedDevicePose_t) == 0x4E);
// Creating value type constructor for type: CameraVideoStreamFrameHeader_t
constexpr CameraVideoStreamFrameHeader_t(Valve::VR::EVRTrackedCameraFrameType eFrameType_ = {}, uint nWidth_ = {}, uint nHeight_ = {}, uint nBytesPerPixel_ = {}, uint nFrameSequence_ = {}, Valve::VR::TrackedDevicePose_t standingTrackedDevicePose_ = {}) noexcept : eFrameType{eFrameType_}, nWidth{nWidth_}, nHeight{nHeight_}, nBytesPerPixel{nBytesPerPixel_}, nFrameSequence{nFrameSequence_}, standingTrackedDevicePose{standingTrackedDevicePose_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get instance field: public Valve.VR.EVRTrackedCameraFrameType eFrameType
Valve::VR::EVRTrackedCameraFrameType _get_eFrameType();
// Set instance field: public Valve.VR.EVRTrackedCameraFrameType eFrameType
void _set_eFrameType(Valve::VR::EVRTrackedCameraFrameType value);
// Get instance field: public System.UInt32 nWidth
uint _get_nWidth();
// Set instance field: public System.UInt32 nWidth
void _set_nWidth(uint value);
// Get instance field: public System.UInt32 nHeight
uint _get_nHeight();
// Set instance field: public System.UInt32 nHeight
void _set_nHeight(uint value);
// Get instance field: public System.UInt32 nBytesPerPixel
uint _get_nBytesPerPixel();
// Set instance field: public System.UInt32 nBytesPerPixel
void _set_nBytesPerPixel(uint value);
// Get instance field: public System.UInt32 nFrameSequence
uint _get_nFrameSequence();
// Set instance field: public System.UInt32 nFrameSequence
void _set_nFrameSequence(uint value);
// Get instance field: public Valve.VR.TrackedDevicePose_t standingTrackedDevicePose
Valve::VR::TrackedDevicePose_t _get_standingTrackedDevicePose();
// Set instance field: public Valve.VR.TrackedDevicePose_t standingTrackedDevicePose
void _set_standingTrackedDevicePose(Valve::VR::TrackedDevicePose_t value);
}; // Valve.VR.CameraVideoStreamFrameHeader_t
#pragma pack(pop)
static check_size<sizeof(CameraVideoStreamFrameHeader_t), 20 + sizeof(Valve::VR::TrackedDevicePose_t)> __Valve_VR_CameraVideoStreamFrameHeader_tSizeCheck;
static_assert(sizeof(CameraVideoStreamFrameHeader_t) == 0x62);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(Valve::VR::CameraVideoStreamFrameHeader_t, "Valve.VR", "CameraVideoStreamFrameHeader_t");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
// Lab1.cpp
// Lab 2 example, textured quad
#include "App1.h"
float angle = 0.0f;
float rotateAmount;
App1::App1()
{
mesh = nullptr;
textureShader = nullptr;
}
void App1::init(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight, Input *in, bool VSYNC, bool FULL_SCREEN)
{
// Call super/parent init function (required!)
BaseApplication::init(hinstance, hwnd, screenWidth, screenHeight, in, VSYNC, FULL_SCREEN);
textureMgr->loadTexture(L"bunny", L"res/bunny.png");
textureMgr->loadTexture(L"brick", L"res/brick1.dds");
// Create Mesh object and shader object
mesh = new TexturedQuad(renderer->getDevice(), renderer->getDeviceContext());
textureShader = new TextureShader(renderer->getDevice(), hwnd);
}
App1::~App1()
{
// Run base application deconstructor
BaseApplication::~BaseApplication();
// Release the Direct3D object.
if (mesh)
{
delete mesh;
mesh = 0;
}
if (textureShader)
{
delete textureShader;
textureShader = 0;
}
}
bool App1::frame()
{
bool result;
result = BaseApplication::frame();
if (!result)
{
return false;
}
// Render the graphics.
result = render();
if (!result)
{
return false;
}
angle = angle + 0.001;
return true;
}
bool App1::render()
{
XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
// Clear the scene. (default blue colour)
renderer->beginScene(0.39f, 0.58f, 0.92f, 1.0f);
// Generate the view matrix based on the camera's position.
camera->update();
// Get the world, view, projection, and ortho matrices from the camera and Direct3D objects.
worldMatrix = renderer->getWorldMatrix();
viewMatrix = camera->getViewMatrix();
projectionMatrix = renderer->getProjectionMatrix();
// Send geometry data, set shader parameters, render object with shader
mesh->sendData(renderer->getDeviceContext());
textureShader->setShaderParameters(renderer->getDeviceContext(), worldMatrix = XMMatrixRotationRollPitchYaw(0.0,0.0,angle), viewMatrix, projectionMatrix, textureMgr->getTexture(L"bunny"), textureMgr->getTexture(L"brick"));
textureShader->render(renderer->getDeviceContext(), mesh->getIndexCount());
//mesh->sendData(renderer->getDeviceContext());
//textureShader->setShaderParameters(renderer->getDeviceContext(), worldMatrix = XMMatrixMultiply(XMMatrixRotationRollPitchYaw(0.0, 0.0, rotateAmount),XMMatrixTranslation(2.0,0.0,0.0)), viewMatrix, projectionMatrix, textureMgr->getTexture(L"brick"));
//textureShader->render(renderer->getDeviceContext(), mesh->getIndexCount());
// Render GUI
gui();
// Swap the buffers
renderer->endScene();
return true;
}
void App1::gui()
{
// Force turn off unnecessary shader stages.
renderer->getDeviceContext()->GSSetShader(NULL, NULL, 0);
renderer->getDeviceContext()->HSSetShader(NULL, NULL, 0);
renderer->getDeviceContext()->DSSetShader(NULL, NULL, 0);
// Build UI
ImGui::Text("FPS: %.2f", timer->getFPS());
ImGui::Checkbox("Wireframe mode", &wireframeToggle);
ImGui::SliderFloat("float", &rotateAmount, 0.0f, 6.0f);
// Render UI
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
|
/*
All modification made by Cambricon Corporation: © 2018-2019 Cambricon Corporation
All rights reserved.
All other contributions:
Copyright (c) 2014--2019, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_CAFFE_LAYERS_NORMALIZE_LAYER_HPP_
#define INCLUDE_CAFFE_LAYERS_NORMALIZE_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Normalizes the input to have L_p norm of 1 with scale learnable.
*
* TODO(weiliu89): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class NormalizeLayer : public Layer<Dtype> {
public:
explicit NormalizeLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Normalize"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
Blob<Dtype> norm_;
Blob<Dtype> sum_channel_multiplier_, sum_spatial_multiplier_;
Blob<Dtype> buffer_, buffer_channel_, buffer_spatial_;
bool across_spatial_;
bool channel_shared_;
Dtype eps_;
};
} // namespace caffe
#endif // INCLUDE_CAFFE_LAYERS_NORMALIZE_LAYER_HPP_
|
/*
* Copyright (c) 2011-2014, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AutoLog.h"
using std::string;
CAutoLog::CAutoLog(const CElement* pElement, const string& strContext, bool bLogOn)
: _pElement(pElement), _strContext(strContext), _bLogOn(bLogOn)
{
if (_bLogOn) {
// Log
_pElement->doLog(false, _strContext + " {");
// Nest
_pElement->nestLog();
}
}
CAutoLog::~CAutoLog()
{
if (_bLogOn) {
// Unnest
_pElement->unnestLog();
// Log
_pElement->doLog(false, "} " + _strContext);
}
}
|
//===-- StackFrameList.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/StackFrameList.h"
#include "lldb/Breakpoint/Breakpoint.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/SourceManager.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Symbol/Block.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/Unwind.h"
#include "lldb/Utility/Log.h"
#include "llvm/ADT/SmallPtrSet.h"
#include <memory>
//#define DEBUG_STACK_FRAMES 1
using namespace lldb;
using namespace lldb_private;
// StackFrameList constructor
StackFrameList::StackFrameList(Thread &thread,
const lldb::StackFrameListSP &prev_frames_sp,
bool show_inline_frames)
: m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(),
m_selected_frame_idx(0), m_concrete_frames_fetched(0),
m_current_inlined_depth(UINT32_MAX),
m_current_inlined_pc(LLDB_INVALID_ADDRESS),
m_show_inlined_frames(show_inline_frames) {
if (prev_frames_sp) {
m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
}
}
StackFrameList::~StackFrameList() {
// Call clear since this takes a lock and clears the stack frame list in case
// another thread is currently using this stack frame list
Clear();
}
void StackFrameList::CalculateCurrentInlinedDepth() {
uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
if (cur_inlined_depth == UINT32_MAX) {
ResetCurrentInlinedDepth();
}
}
uint32_t StackFrameList::GetCurrentInlinedDepth() {
if (m_show_inlined_frames && m_current_inlined_pc != LLDB_INVALID_ADDRESS) {
lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
if (cur_pc != m_current_inlined_pc) {
m_current_inlined_pc = LLDB_INVALID_ADDRESS;
m_current_inlined_depth = UINT32_MAX;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log && log->GetVerbose())
LLDB_LOGF(
log,
"GetCurrentInlinedDepth: invalidating current inlined depth.\n");
}
return m_current_inlined_depth;
} else {
return UINT32_MAX;
}
}
void StackFrameList::ResetCurrentInlinedDepth() {
if (!m_show_inlined_frames)
return;
std::lock_guard<std::recursive_mutex> guard(m_mutex);
GetFramesUpTo(0);
if (m_frames.empty())
return;
if (!m_frames[0]->IsInlined()) {
m_current_inlined_depth = UINT32_MAX;
m_current_inlined_pc = LLDB_INVALID_ADDRESS;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log && log->GetVerbose())
LLDB_LOGF(
log,
"ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
return;
}
// We only need to do something special about inlined blocks when we are
// at the beginning of an inlined function:
// FIXME: We probably also have to do something special if the PC is at
// the END of an inlined function, which coincides with the end of either
// its containing function or another inlined function.
Block *block_ptr = m_frames[0]->GetFrameBlock();
if (!block_ptr)
return;
Address pc_as_address;
lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();
pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget()));
AddressRange containing_range;
if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) ||
pc_as_address != containing_range.GetBaseAddress())
return;
// If we got here because of a breakpoint hit, then set the inlined depth
// depending on where the breakpoint was set. If we got here because of a
// crash, then set the inlined depth to the deepest most block. Otherwise,
// we stopped here naturally as the result of a step, so set ourselves in the
// containing frame of the whole set of nested inlines, so the user can then
// "virtually" step into the frames one by one, or next over the whole mess.
// Note: We don't have to handle being somewhere in the middle of the stack
// here, since ResetCurrentInlinedDepth doesn't get called if there is a
// valid inlined depth set.
StopInfoSP stop_info_sp = m_thread.GetStopInfo();
if (!stop_info_sp)
return;
switch (stop_info_sp->GetStopReason()) {
case eStopReasonWatchpoint:
case eStopReasonException:
case eStopReasonExec:
case eStopReasonFork:
case eStopReasonVFork:
case eStopReasonVForkDone:
case eStopReasonSignal:
// In all these cases we want to stop in the deepest frame.
m_current_inlined_pc = curr_pc;
m_current_inlined_depth = 0;
break;
case eStopReasonBreakpoint: {
// FIXME: Figure out what this break point is doing, and set the inline
// depth appropriately. Be careful to take into account breakpoints that
// implement step over prologue, since that should do the default
// calculation. For now, if the breakpoints corresponding to this hit are
// all internal, I set the stop location to the top of the inlined stack,
// since that will make things like stepping over prologues work right.
// But if there are any non-internal breakpoints I do to the bottom of the
// stack, since that was the old behavior.
uint32_t bp_site_id = stop_info_sp->GetValue();
BreakpointSiteSP bp_site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id));
bool all_internal = true;
if (bp_site_sp) {
uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
for (uint32_t i = 0; i < num_owners; i++) {
Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
if (!bp_ref.IsInternal()) {
all_internal = false;
}
}
}
if (!all_internal) {
m_current_inlined_pc = curr_pc;
m_current_inlined_depth = 0;
break;
}
}
LLVM_FALLTHROUGH;
default: {
// Otherwise, we should set ourselves at the container of the inlining, so
// that the user can descend into them. So first we check whether we have
// more than one inlined block sharing this PC:
int num_inlined_functions = 0;
for (Block *container_ptr = block_ptr->GetInlinedParent();
container_ptr != nullptr;
container_ptr = container_ptr->GetInlinedParent()) {
if (!container_ptr->GetRangeContainingAddress(pc_as_address,
containing_range))
break;
if (pc_as_address != containing_range.GetBaseAddress())
break;
num_inlined_functions++;
}
m_current_inlined_pc = curr_pc;
m_current_inlined_depth = num_inlined_functions + 1;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log && log->GetVerbose())
LLDB_LOGF(log,
"ResetCurrentInlinedDepth: setting inlined "
"depth: %d 0x%" PRIx64 ".\n",
m_current_inlined_depth, curr_pc);
break;
}
}
}
bool StackFrameList::DecrementCurrentInlinedDepth() {
if (m_show_inlined_frames) {
uint32_t current_inlined_depth = GetCurrentInlinedDepth();
if (current_inlined_depth != UINT32_MAX) {
if (current_inlined_depth > 0) {
m_current_inlined_depth--;
return true;
}
}
}
return false;
}
void StackFrameList::SetCurrentInlinedDepth(uint32_t new_depth) {
m_current_inlined_depth = new_depth;
if (new_depth == UINT32_MAX)
m_current_inlined_pc = LLDB_INVALID_ADDRESS;
else
m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
}
void StackFrameList::GetOnlyConcreteFramesUpTo(uint32_t end_idx,
Unwind &unwinder) {
assert(m_thread.IsValid() && "Expected valid thread");
assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
if (end_idx < m_concrete_frames_fetched)
return;
uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);
if (num_frames <= end_idx + 1) {
// Done unwinding.
m_concrete_frames_fetched = UINT32_MAX;
}
// Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
// which can lazily query the unwinder to create frames.
m_frames.resize(num_frames);
}
/// A sequence of calls that comprise some portion of a backtrace. Each frame
/// is represented as a pair of a callee (Function *) and an address within the
/// callee.
struct CallDescriptor {
Function *func;
CallEdge::AddrType address_type = CallEdge::AddrType::Call;
addr_t address = LLDB_INVALID_ADDRESS;
};
using CallSequence = std::vector<CallDescriptor>;
/// Find the unique path through the call graph from \p begin (with return PC
/// \p return_pc) to \p end. On success this path is stored into \p path, and
/// on failure \p path is unchanged.
static void FindInterveningFrames(Function &begin, Function &end,
ExecutionContext &exe_ctx, Target &target,
addr_t return_pc, CallSequence &path,
ModuleList &images, Log *log) {
LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
begin.GetDisplayName(), end.GetDisplayName(), return_pc);
// Find a non-tail calling edge with the correct return PC.
if (log)
for (const auto &edge : begin.GetCallEdges())
LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
edge->GetReturnPCAddress(begin, target));
CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
if (!first_edge) {
LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
begin.GetDisplayName(), return_pc);
return;
}
// The first callee may not be resolved, or there may be nothing to fill in.
Function *first_callee = first_edge->GetCallee(images, exe_ctx);
if (!first_callee) {
LLDB_LOG(log, "Could not resolve callee");
return;
}
if (first_callee == &end) {
LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
end.GetDisplayName(), return_pc);
return;
}
// Run DFS on the tail-calling edges out of the first callee to find \p end.
// Fully explore the set of functions reachable from the first edge via tail
// calls in order to detect ambiguous executions.
struct DFS {
CallSequence active_path = {};
CallSequence solution_path = {};
llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
bool ambiguous = false;
Function *end;
ModuleList &images;
Target ⌖
ExecutionContext &context;
DFS(Function *end, ModuleList &images, Target &target,
ExecutionContext &context)
: end(end), images(images), target(target), context(context) {}
void search(CallEdge &first_edge, Function &first_callee,
CallSequence &path) {
dfs(first_edge, first_callee);
if (!ambiguous)
path = std::move(solution_path);
}
void dfs(CallEdge ¤t_edge, Function &callee) {
// Found a path to the target function.
if (&callee == end) {
if (solution_path.empty())
solution_path = active_path;
else
ambiguous = true;
return;
}
// Terminate the search if tail recursion is found, or more generally if
// there's more than one way to reach a target. This errs on the side of
// caution: it conservatively stops searching when some solutions are
// still possible to save time in the average case.
if (!visited_nodes.insert(&callee).second) {
ambiguous = true;
return;
}
// Search the calls made from this callee.
active_path.push_back(CallDescriptor{&callee});
for (const auto &edge : callee.GetTailCallingEdges()) {
Function *next_callee = edge->GetCallee(images, context);
if (!next_callee)
continue;
std::tie(active_path.back().address_type, active_path.back().address) =
edge->GetCallerAddress(callee, target);
dfs(*edge, *next_callee);
if (ambiguous)
return;
}
active_path.pop_back();
}
};
DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);
}
/// Given that \p next_frame will be appended to the frame list, synthesize
/// tail call frames between the current end of the list and \p next_frame.
/// If any frames are added, adjust the frame index of \p next_frame.
///
/// --------------
/// | ... | <- Completed frames.
/// --------------
/// | prev_frame |
/// --------------
/// | ... | <- Artificial frames inserted here.
/// --------------
/// | next_frame |
/// --------------
/// | ... | <- Not-yet-visited frames.
/// --------------
void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) {
// Cannot synthesize tail call frames when the stack is empty (there is no
// "previous" frame).
if (m_frames.empty())
return;
TargetSP target_sp = next_frame.CalculateTarget();
if (!target_sp)
return;
lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
if (!next_reg_ctx_sp)
return;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
StackFrame &prev_frame = *m_frames.back().get();
// Find the functions prev_frame and next_frame are stopped in. The function
// objects are needed to search the lazy call graph for intervening frames.
Function *prev_func =
prev_frame.GetSymbolContext(eSymbolContextFunction).function;
if (!prev_func) {
LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
return;
}
Function *next_func =
next_frame.GetSymbolContext(eSymbolContextFunction).function;
if (!next_func) {
LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
return;
}
// Try to find the unique sequence of (tail) calls which led from next_frame
// to prev_frame.
CallSequence path;
addr_t return_pc = next_reg_ctx_sp->GetPC();
Target &target = *target_sp.get();
ModuleList &images = next_frame.CalculateTarget()->GetImages();
ExecutionContext exe_ctx(target_sp, /*get_process=*/true);
exe_ctx.SetFramePtr(&next_frame);
FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,
path, images, log);
// Push synthetic tail call frames.
for (auto calleeInfo : llvm::reverse(path)) {
Function *callee = calleeInfo.func;
uint32_t frame_idx = m_frames.size();
uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
addr_t cfa = LLDB_INVALID_ADDRESS;
bool cfa_is_valid = false;
addr_t pc = calleeInfo.address;
// If the callee address refers to the call instruction, we do not want to
// subtract 1 from this value.
const bool behaves_like_zeroth_frame =
calleeInfo.address_type == CallEdge::AddrType::Call;
SymbolContext sc;
callee->CalculateSymbolContext(&sc);
auto synth_frame = std::make_shared<StackFrame>(
m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
cfa_is_valid, pc, StackFrame::Kind::Artificial,
behaves_like_zeroth_frame, &sc);
m_frames.push_back(synth_frame);
LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);
}
// If any frames were created, adjust next_frame's index.
if (!path.empty())
next_frame.SetFrameIndex(m_frames.size());
}
void StackFrameList::GetFramesUpTo(uint32_t end_idx) {
// Do not fetch frames for an invalid thread.
if (!m_thread.IsValid())
return;
// We've already gotten more frames than asked for, or we've already finished
// unwinding, return.
if (m_frames.size() > end_idx || GetAllFramesFetched())
return;
Unwind &unwinder = m_thread.GetUnwinder();
if (!m_show_inlined_frames) {
GetOnlyConcreteFramesUpTo(end_idx, unwinder);
return;
}
#if defined(DEBUG_STACK_FRAMES)
StreamFile s(stdout, false);
#endif
// If we are hiding some frames from the outside world, we need to add
// those onto the total count of frames to fetch. However, we don't need
// to do that if end_idx is 0 since in that case we always get the first
// concrete frame and all the inlined frames below it... And of course, if
// end_idx is UINT32_MAX that means get all, so just do that...
uint32_t inlined_depth = 0;
if (end_idx > 0 && end_idx != UINT32_MAX) {
inlined_depth = GetCurrentInlinedDepth();
if (inlined_depth != UINT32_MAX) {
if (end_idx > 0)
end_idx += inlined_depth;
}
}
StackFrameSP unwind_frame_sp;
do {
uint32_t idx = m_concrete_frames_fetched++;
lldb::addr_t pc = LLDB_INVALID_ADDRESS;
lldb::addr_t cfa = LLDB_INVALID_ADDRESS;
bool behaves_like_zeroth_frame = (idx == 0);
if (idx == 0) {
// We might have already created frame zero, only create it if we need
// to.
if (m_frames.empty()) {
RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
if (reg_ctx_sp) {
const bool success = unwinder.GetFrameInfoAtIndex(
idx, cfa, pc, behaves_like_zeroth_frame);
// There shouldn't be any way not to get the frame info for frame
// 0. But if the unwinder can't make one, lets make one by hand
// with the SP as the CFA and see if that gets any further.
if (!success) {
cfa = reg_ctx_sp->GetSP();
pc = reg_ctx_sp->GetPC();
}
unwind_frame_sp = std::make_shared<StackFrame>(
m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
cfa, pc, behaves_like_zeroth_frame, nullptr);
m_frames.push_back(unwind_frame_sp);
}
} else {
unwind_frame_sp = m_frames.front();
cfa = unwind_frame_sp->m_id.GetCallFrameAddress();
}
} else {
const bool success =
unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);
if (!success) {
// We've gotten to the end of the stack.
SetAllFramesFetched();
break;
}
const bool cfa_is_valid = true;
unwind_frame_sp = std::make_shared<StackFrame>(
m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
// Create synthetic tail call frames between the previous frame and the
// newly-found frame. The new frame's index may change after this call,
// although its concrete index will stay the same.
SynthesizeTailCallFrames(*unwind_frame_sp.get());
m_frames.push_back(unwind_frame_sp);
}
assert(unwind_frame_sp);
SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
eSymbolContextBlock | eSymbolContextFunction);
Block *unwind_block = unwind_sc.block;
TargetSP target_sp = m_thread.CalculateTarget();
if (unwind_block) {
Address curr_frame_address(
unwind_frame_sp->GetFrameCodeAddressForSymbolication());
SymbolContext next_frame_sc;
Address next_frame_address;
while (unwind_sc.GetParentOfInlinedScope(
curr_frame_address, next_frame_sc, next_frame_address)) {
next_frame_sc.line_entry.ApplyFileMappings(target_sp);
behaves_like_zeroth_frame = false;
StackFrameSP frame_sp(new StackFrame(
m_thread.shared_from_this(), m_frames.size(), idx,
unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
behaves_like_zeroth_frame, &next_frame_sc));
m_frames.push_back(frame_sp);
unwind_sc = next_frame_sc;
curr_frame_address = next_frame_address;
}
}
} while (m_frames.size() - 1 < end_idx);
// Don't try to merge till you've calculated all the frames in this stack.
if (GetAllFramesFetched() && m_prev_frames_sp) {
StackFrameList *prev_frames = m_prev_frames_sp.get();
StackFrameList *curr_frames = this;
#if defined(DEBUG_STACK_FRAMES)
s.PutCString("\nprev_frames:\n");
prev_frames->Dump(&s);
s.PutCString("\ncurr_frames:\n");
curr_frames->Dump(&s);
s.EOL();
#endif
size_t curr_frame_num, prev_frame_num;
for (curr_frame_num = curr_frames->m_frames.size(),
prev_frame_num = prev_frames->m_frames.size();
curr_frame_num > 0 && prev_frame_num > 0;
--curr_frame_num, --prev_frame_num) {
const size_t curr_frame_idx = curr_frame_num - 1;
const size_t prev_frame_idx = prev_frame_num - 1;
StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
#if defined(DEBUG_STACK_FRAMES)
s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
if (curr_frame_sp)
curr_frame_sp->Dump(&s, true, false);
else
s.PutCString("NULL");
s.Printf("\nPrev frame #%u ", prev_frame_idx);
if (prev_frame_sp)
prev_frame_sp->Dump(&s, true, false);
else
s.PutCString("NULL");
#endif
StackFrame *curr_frame = curr_frame_sp.get();
StackFrame *prev_frame = prev_frame_sp.get();
if (curr_frame == nullptr || prev_frame == nullptr)
break;
// Check the stack ID to make sure they are equal.
if (curr_frame->GetStackID() != prev_frame->GetStackID())
break;
prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
// Now copy the fixed up previous frame into the current frames so the
// pointer doesn't change.
m_frames[curr_frame_idx] = prev_frame_sp;
#if defined(DEBUG_STACK_FRAMES)
s.Printf("\n Copying previous frame to current frame");
#endif
}
// We are done with the old stack frame list, we can release it now.
m_prev_frames_sp.reset();
}
#if defined(DEBUG_STACK_FRAMES)
s.PutCString("\n\nNew frames:\n");
Dump(&s);
s.EOL();
#endif
}
uint32_t StackFrameList::GetNumFrames(bool can_create) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (can_create)
GetFramesUpTo(UINT32_MAX);
return GetVisibleStackFrameIndex(m_frames.size());
}
void StackFrameList::Dump(Stream *s) {
if (s == nullptr)
return;
std::lock_guard<std::recursive_mutex> guard(m_mutex);
const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
for (pos = begin; pos != end; ++pos) {
StackFrame *frame = (*pos).get();
s->Printf("%p: ", static_cast<void *>(frame));
if (frame) {
frame->GetStackID().Dump(s);
frame->DumpUsingSettingsFormat(s);
} else
s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
s->EOL();
}
s->EOL();
}
StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) {
StackFrameSP frame_sp;
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t original_idx = idx;
uint32_t inlined_depth = GetCurrentInlinedDepth();
if (inlined_depth != UINT32_MAX)
idx += inlined_depth;
if (idx < m_frames.size())
frame_sp = m_frames[idx];
if (frame_sp)
return frame_sp;
// GetFramesUpTo will fill m_frames with as many frames as you asked for, if
// there are that many. If there weren't then you asked for too many frames.
GetFramesUpTo(idx);
if (idx < m_frames.size()) {
if (m_show_inlined_frames) {
// When inline frames are enabled we actually create all the frames in
// GetFramesUpTo.
frame_sp = m_frames[idx];
} else {
addr_t pc, cfa;
bool behaves_like_zeroth_frame = (idx == 0);
if (m_thread.GetUnwinder().GetFrameInfoAtIndex(
idx, cfa, pc, behaves_like_zeroth_frame)) {
const bool cfa_is_valid = true;
frame_sp = std::make_shared<StackFrame>(
m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,
StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
Function *function =
frame_sp->GetSymbolContext(eSymbolContextFunction).function;
if (function) {
// When we aren't showing inline functions we always use the top
// most function block as the scope.
frame_sp->SetSymbolContextScope(&function->GetBlock(false));
} else {
// Set the symbol scope from the symbol regardless if it is nullptr
// or valid.
frame_sp->SetSymbolContextScope(
frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);
}
SetFrameAtIndex(idx, frame_sp);
}
}
} else if (original_idx == 0) {
// There should ALWAYS be a frame at index 0. If something went wrong with
// the CurrentInlinedDepth such that there weren't as many frames as we
// thought taking that into account, then reset the current inlined depth
// and return the real zeroth frame.
if (m_frames.empty()) {
// Why do we have a thread with zero frames, that should not ever
// happen...
assert(!m_thread.IsValid() && "A valid thread has no frames.");
} else {
ResetCurrentInlinedDepth();
frame_sp = m_frames[original_idx];
}
}
return frame_sp;
}
StackFrameSP
StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
// First try assuming the unwind index is the same as the frame index. The
// unwind index is always greater than or equal to the frame index, so it is
// a good place to start. If we have inlined frames we might have 5 concrete
// frames (frame unwind indexes go from 0-4), but we might have 15 frames
// after we make all the inlined frames. Most of the time the unwind frame
// index (or the concrete frame index) is the same as the frame index.
uint32_t frame_idx = unwind_idx;
StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
while (frame_sp) {
if (frame_sp->GetFrameIndex() == unwind_idx)
break;
frame_sp = GetFrameAtIndex(++frame_idx);
}
return frame_sp;
}
StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {
StackFrameSP frame_sp;
if (stack_id.IsValid()) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t frame_idx = 0;
// Do a search in case the stack frame is already in our cache.
collection::const_iterator begin = m_frames.begin();
collection::const_iterator end = m_frames.end();
if (begin != end) {
collection::const_iterator pos =
std::find_if(begin, end, [&](StackFrameSP frame_sp) {
return frame_sp->GetStackID() == stack_id;
});
if (pos != end)
return *pos;
}
do {
frame_sp = GetFrameAtIndex(frame_idx);
if (frame_sp && frame_sp->GetStackID() == stack_id)
break;
frame_idx++;
} while (frame_sp);
}
return frame_sp;
}
bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
if (idx >= m_frames.size())
m_frames.resize(idx + 1);
// Make sure allocation succeeded by checking bounds again
if (idx < m_frames.size()) {
m_frames[idx] = frame_sp;
return true;
}
return false; // resize failed, out of memory?
}
uint32_t StackFrameList::GetSelectedFrameIndex() const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_selected_frame_idx;
}
uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
const_iterator pos;
const_iterator begin = m_frames.begin();
const_iterator end = m_frames.end();
m_selected_frame_idx = 0;
for (pos = begin; pos != end; ++pos) {
if (pos->get() == frame) {
m_selected_frame_idx = std::distance(begin, pos);
uint32_t inlined_depth = GetCurrentInlinedDepth();
if (inlined_depth != UINT32_MAX)
m_selected_frame_idx -= inlined_depth;
break;
}
}
SetDefaultFileAndLineToSelectedFrame();
return m_selected_frame_idx;
}
bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
StackFrameSP frame_sp(GetFrameAtIndex(idx));
if (frame_sp) {
SetSelectedFrame(frame_sp.get());
return true;
} else
return false;
}
void StackFrameList::SetDefaultFileAndLineToSelectedFrame() {
if (m_thread.GetID() ==
m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex()));
if (frame_sp) {
SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
if (sc.line_entry.file)
m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
sc.line_entry.file, sc.line_entry.line);
}
}
}
// The thread has been run, reset the number stack frames to zero so we can
// determine how many frames we have lazily.
void StackFrameList::Clear() {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
m_frames.clear();
m_concrete_frames_fetched = 0;
}
lldb::StackFrameSP
StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
const_iterator pos;
const_iterator begin = m_frames.begin();
const_iterator end = m_frames.end();
lldb::StackFrameSP ret_sp;
for (pos = begin; pos != end; ++pos) {
if (pos->get() == stack_frame_ptr) {
ret_sp = (*pos);
break;
}
}
return ret_sp;
}
size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
uint32_t num_frames, bool show_frame_info,
uint32_t num_frames_with_source,
bool show_unique,
const char *selected_frame_marker) {
size_t num_frames_displayed = 0;
if (num_frames == 0)
return 0;
StackFrameSP frame_sp;
uint32_t frame_idx = 0;
uint32_t last_frame;
// Don't let the last frame wrap around...
if (num_frames == UINT32_MAX)
last_frame = UINT32_MAX;
else
last_frame = first_frame + num_frames;
StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame();
const char *unselected_marker = nullptr;
std::string buffer;
if (selected_frame_marker) {
size_t len = strlen(selected_frame_marker);
buffer.insert(buffer.begin(), len, ' ');
unselected_marker = buffer.c_str();
}
const char *marker = nullptr;
for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
frame_sp = GetFrameAtIndex(frame_idx);
if (!frame_sp)
break;
if (selected_frame_marker != nullptr) {
if (frame_sp == selected_frame_sp)
marker = selected_frame_marker;
else
marker = unselected_marker;
}
if (!frame_sp->GetStatus(strm, show_frame_info,
num_frames_with_source > (first_frame - frame_idx),
show_unique, marker))
break;
++num_frames_displayed;
}
strm.IndentLess();
return num_frames_displayed;
}
|
#pragma once
#include <utility>
template<class F, class X>
struct fold_wrapper
{
F f;
X state;
template<typename FoldWrapper>
constexpr auto operator>>=(FoldWrapper &&fw)
{
auto result = f(state, std::forward<FoldWrapper>(fw).state);
return fold_wrapper<F, decltype(result)>{ f, result };
}
};
template<class F, class... Xs>
constexpr auto fold_left(const F &f, Xs &&...xs)
{
auto result = (... >>= fold_wrapper<F, Xs>{ f, std::forward<Xs>(xs) });
return result.state;
}
|
#include <click/config.h>
#include <click/glue.hh>
#include <click/args.hh>
#include <click/ipflowid.hh>
#include <click/routervisitor.hh>
#include <click/error.hh>
#include "flowipmanager_cuckoopp_imp_lazy.hh"
#include <rte_hash.h>
#include <click/dpdk_glue.hh>
#include <rte_ethdev.h>
extern "C" {
#include <cuckoopp/rte_hash_lazy_bloom.h>
}
CLICK_DECLS
int
FlowIPManager_CuckooPPIMP_lazy::alloc(int core)
{
struct rte_hash_hvariant_parameters hash_params = {0};
char buf[64];
sprintf(buf, "%i-%s", core, name().c_str());
hash_params.name = buf;
hash_params.entries = _table_size;
_lazy_timeout = _timeout_ms / _recycle_interval_ms;
_tables[core].hash = rte_hash_lazy_bloom_create(&hash_params);
if(unlikely(_tables[core].hash == nullptr))
{
VPRINT(0,"Could not init flow table %d!", core);
return 1;
}
if(!_timer)
_timer = new Timer(this);
if(_timer && !_timer->initialized())
{
_timer->initialize(this, true);
VPRINT(0,"Updating recycle epoch every %d ms", _recycle_interval_ms);
_timer->schedule_after_msec(_recycle_interval_ms);
}
#if IMP_COUNTERS
if(_lazytables == 0)
{
VPRINT(1,"Initialized lazy counters table");
_lazytables = CLICK_ALIGNED_NEW(lazytable, _tables_count);
CLICK_ASSERT_ALIGNED(_lazytables);
}
#endif
return 0;
}
int
FlowIPManager_CuckooPPIMP_lazy::find(IPFlow5ID &f, int core)
{
auto& tab = _tables[core];
auto *table = reinterpret_cast<rte_hash_hvariant *>(tab.hash);
hash_key_t key = {0};
key.a = ((uint64_t) f.saddr().addr() << 32) | ((uint64_t)f.daddr().addr());
key.b = ((uint64_t) f.proto() << 32) | ((uint64_t)f.sport() << 16) | ((uint64_t)f.dport());
hash_data_t data = {0};
int ret = rte_hash_lazy_bloom_lookup_data(table, key, &data, _recent);
return ret >= 0 ? data.a: 0;
}
int
FlowIPManager_CuckooPPIMP_lazy::insert(IPFlow5ID &f, int flowid, int core)
{
auto& tab = _tables[core];
auto *table = reinterpret_cast<rte_hash_hvariant *> (tab.hash);
hash_key_t key = {0};
key.a = ((uint64_t) f.saddr().addr() << 32) | ((uint64_t)f.daddr().addr());
key.b = ((uint64_t) f.proto() << 32) | ((uint64_t)f.sport() << 16) | ((uint64_t)f.dport());
hash_data_t data = {0};
data.a = flowid;
int ret = rte_hash_lazy_bloom_add_key_data(table, key, data, _recent + _lazy_timeout, _recent);
//TODO: how to recognize insert from recycling??
//TODO: LAZY counters
return ret >= 0? flowid : 0;
}
void FlowIPManager_CuckooPPIMP_lazy::run_timer(Timer *t)
{
_recent = click_jiffies() / _recycle_interval_ms;
_timer->schedule_after_msec(_recycle_interval_ms);
}
CLICK_ENDDECLS
ELEMENT_REQUIRES(flow)
EXPORT_ELEMENT(FlowIPManager_CuckooPPIMP_lazy)
ELEMENT_MT_SAFE(FlowIPManager_CuckooPPIMP_lazy)
|
// (C) Copyright John Maddock 2007.
// Use, modification and distribution are subject to 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)
//
// This file is machine generated, do not edit by hand
// Polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_RAT_EVAL_19_HPP
#define BOOST_MATH_TOOLS_RAT_EVAL_19_HPP
namespace boost{ namespace math{ namespace tools{ namespace detail{
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<0>*)
{
return static_cast<V>(0);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<1>*)
{
return static_cast<V>(a[0]) / static_cast<V>(b[0]);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<2>*)
{
return static_cast<V>((a[1] * x + a[0]) / (b[1] * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<3>*)
{
return static_cast<V>(((a[2] * x + a[1]) * x + a[0]) / ((b[2] * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<4>*)
{
return static_cast<V>((((a[3] * x + a[2]) * x + a[1]) * x + a[0]) / (((b[3] * x + b[2]) * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<5>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[4] * x2 + a[2];
t[1] = a[3] * x2 + a[1];
t[2] = b[4] * x2 + b[2];
t[3] = b[3] * x2 + b[1];
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[4]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<6>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[5] * x2 + a[3];
t[1] = a[4] * x2 + a[2];
t[2] = b[5] * x2 + b[3];
t[3] = b[4] * x2 + b[2];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<7>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[6] * x2 + a[4];
t[1] = a[5] * x2 + a[3];
t[2] = b[6] * x2 + b[4];
t[3] = b[5] * x2 + b[3];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[6]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<8>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[7] * x2 + a[5];
t[1] = a[6] * x2 + a[4];
t[2] = b[7] * x2 + b[5];
t[3] = b[6] * x2 + b[4];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<9>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[8] * x2 + a[6];
t[1] = a[7] * x2 + a[5];
t[2] = b[8] * x2 + b[6];
t[3] = b[7] * x2 + b[5];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[8]);
t[2] += static_cast<V>(b[8]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<10>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[9] * x2 + a[7];
t[1] = a[8] * x2 + a[6];
t[2] = b[9] * x2 + b[7];
t[3] = b[8] * x2 + b[6];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<11>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[10] * x2 + a[8];
t[1] = a[9] * x2 + a[7];
t[2] = b[10] * x2 + b[8];
t[3] = b[9] * x2 + b[7];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[5]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[10]);
t[2] += static_cast<V>(b[10]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<12>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[11] * x2 + a[9];
t[1] = a[10] * x2 + a[8];
t[2] = b[11] * x2 + b[9];
t[3] = b[10] * x2 + b[8];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[7]);
t[1] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[7]);
t[3] += static_cast<V>(b[6]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<13>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[12] * x2 + a[10];
t[1] = a[11] * x2 + a[9];
t[2] = b[12] * x2 + b[10];
t[3] = b[11] * x2 + b[9];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[7]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[5]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[12]);
t[2] += static_cast<V>(b[12]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<14>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[13] * x2 + a[11];
t[1] = a[12] * x2 + a[10];
t[2] = b[13] * x2 + b[11];
t[3] = b[12] * x2 + b[10];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[9]);
t[1] += static_cast<V>(a[8]);
t[2] += static_cast<V>(b[9]);
t[3] += static_cast<V>(b[8]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[7]);
t[1] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[7]);
t[3] += static_cast<V>(b[6]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<15>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[14] * x2 + a[12];
t[1] = a[13] * x2 + a[11];
t[2] = b[14] * x2 + b[12];
t[3] = b[13] * x2 + b[11];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[9]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[7]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[5]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[14]);
t[2] += static_cast<V>(b[14]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<16>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[15] * x2 + a[13];
t[1] = a[14] * x2 + a[12];
t[2] = b[15] * x2 + b[13];
t[3] = b[14] * x2 + b[12];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[11]);
t[1] += static_cast<V>(a[10]);
t[2] += static_cast<V>(b[11]);
t[3] += static_cast<V>(b[10]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[9]);
t[1] += static_cast<V>(a[8]);
t[2] += static_cast<V>(b[9]);
t[3] += static_cast<V>(b[8]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[7]);
t[1] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[7]);
t[3] += static_cast<V>(b[6]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[14]);
t[1] += static_cast<V>(a[15]);
t[2] += static_cast<V>(b[14]);
t[3] += static_cast<V>(b[15]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<17>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[16] * x2 + a[14];
t[1] = a[15] * x2 + a[13];
t[2] = b[16] * x2 + b[14];
t[3] = b[15] * x2 + b[13];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[11]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[9]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[7]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[5]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[14]);
t[1] += static_cast<V>(a[15]);
t[2] += static_cast<V>(b[14]);
t[3] += static_cast<V>(b[15]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[16]);
t[2] += static_cast<V>(b[16]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<18>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[17] * x2 + a[15];
t[1] = a[16] * x2 + a[14];
t[2] = b[17] * x2 + b[15];
t[3] = b[16] * x2 + b[14];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[13]);
t[1] += static_cast<V>(a[12]);
t[2] += static_cast<V>(b[13]);
t[3] += static_cast<V>(b[12]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[11]);
t[1] += static_cast<V>(a[10]);
t[2] += static_cast<V>(b[11]);
t[3] += static_cast<V>(b[10]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[9]);
t[1] += static_cast<V>(a[8]);
t[2] += static_cast<V>(b[9]);
t[3] += static_cast<V>(b[8]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[7]);
t[1] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[7]);
t[3] += static_cast<V>(b[6]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[14]);
t[1] += static_cast<V>(a[15]);
t[2] += static_cast<V>(b[14]);
t[3] += static_cast<V>(b[15]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[16]);
t[1] += static_cast<V>(a[17]);
t[2] += static_cast<V>(b[16]);
t[3] += static_cast<V>(b[17]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<19>*)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[18] * x2 + a[16];
t[1] = a[17] * x2 + a[15];
t[2] = b[18] * x2 + b[16];
t[3] = b[17] * x2 + b[15];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[14]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[14]);
t[3] += static_cast<V>(b[13]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[11]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[9]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[7]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[5]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[10]);
t[1] += static_cast<V>(a[11]);
t[2] += static_cast<V>(b[10]);
t[3] += static_cast<V>(b[11]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[12]);
t[1] += static_cast<V>(a[13]);
t[2] += static_cast<V>(b[12]);
t[3] += static_cast<V>(b[13]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[14]);
t[1] += static_cast<V>(a[15]);
t[2] += static_cast<V>(b[14]);
t[3] += static_cast<V>(b[15]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[16]);
t[1] += static_cast<V>(a[17]);
t[2] += static_cast<V>(b[16]);
t[3] += static_cast<V>(b[17]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[18]);
t[2] += static_cast<V>(b[18]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
}}}} // namespaces
#endif // include guard
|
//
// Copyright (c) 2019-2020 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "miru_core_common.h"
#include "D3D12MemAlloc.h"
#ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
#include <dxgi.h>
#if D3D12MA_DXGI_1_4
#include <dxgi1_4.h>
#endif
#endif
#include <combaseapi.h>
#include <mutex>
#include <atomic>
#include <algorithm>
#include <utility>
#include <cstdlib>
#include <malloc.h> // for _aligned_malloc, _aligned_free
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Configuration Begin
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#ifndef D3D12MA_ASSERT
#include <cassert>
#define D3D12MA_ASSERT(cond) assert(cond)
#endif
// Assert that will be called very often, like inside data structures e.g. operator[].
// Making it non-empty can make program slow.
#ifndef D3D12MA_HEAVY_ASSERT
#ifdef _DEBUG
#define D3D12MA_HEAVY_ASSERT(expr) //D3D12MA_ASSERT(expr)
#else
#define D3D12MA_HEAVY_ASSERT(expr)
#endif
#endif
#ifndef D3D12MA_DEBUG_ALIGNMENT
/*
Minimum alignment of all allocations, in bytes.
Set to more than 1 for debugging purposes only. Must be power of two.
*/
#define D3D12MA_DEBUG_ALIGNMENT (1)
#endif
#ifndef D3D12MA_DEBUG_MARGIN
// Minimum margin before and after every allocation, in bytes.
// Set nonzero for debugging purposes only.
#define D3D12MA_DEBUG_MARGIN (0)
#endif
#ifndef D3D12MA_DEBUG_GLOBAL_MUTEX
/*
Set this to 1 for debugging purposes only, to enable single mutex protecting all
entry calls to the library. Can be useful for debugging multithreading issues.
*/
#define D3D12MA_DEBUG_GLOBAL_MUTEX (0)
#endif
#ifndef D3D12MA_DEFAULT_BLOCK_SIZE
/// Default size of a block allocated as single ID3D12Heap.
#define D3D12MA_DEFAULT_BLOCK_SIZE (256ull * 1024 * 1024)
#endif
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Configuration End
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace D3D12MA
{
////////////////////////////////////////////////////////////////////////////////
// Private globals - CPU memory allocation
static void* DefaultAllocate(size_t Size, size_t Alignment, void* /*pUserData*/)
{
return _aligned_malloc(Size, Alignment);
}
static void DefaultFree(void* pMemory, void* /*pUserData*/)
{
return _aligned_free(pMemory);
}
static void* Malloc(const ALLOCATION_CALLBACKS& allocs, size_t size, size_t alignment)
{
void* const result = (*allocs.pAllocate)(size, alignment, allocs.pUserData);
D3D12MA_ASSERT(result);
return result;
}
static void Free(const ALLOCATION_CALLBACKS& allocs, void* memory)
{
(*allocs.pFree)(memory, allocs.pUserData);
}
template<typename T>
static T* Allocate(const ALLOCATION_CALLBACKS& allocs)
{
return (T*)Malloc(allocs, sizeof(T), __alignof(T));
}
template<typename T>
static T* AllocateArray(const ALLOCATION_CALLBACKS& allocs, size_t count)
{
return (T*)Malloc(allocs, sizeof(T) * count, __alignof(T));
}
#define D3D12MA_NEW(allocs, type) new(D3D12MA::Allocate<type>(allocs))(type)
#define D3D12MA_NEW_ARRAY(allocs, type, count) new(D3D12MA::AllocateArray<type>((allocs), (count)))(type)
template<typename T>
void D3D12MA_DELETE(const ALLOCATION_CALLBACKS& allocs, T* memory)
{
if(memory)
{
memory->~T();
Free(allocs, memory);
}
}
template<typename T>
void D3D12MA_DELETE_ARRAY(const ALLOCATION_CALLBACKS& allocs, T* memory, size_t count)
{
if(memory)
{
for(size_t i = count; i--; )
{
memory[i].~T();
}
Free(allocs, memory);
}
}
static void SetupAllocationCallbacks(ALLOCATION_CALLBACKS& outAllocs, const ALLOCATION_CALLBACKS* allocationCallbacks)
{
if(allocationCallbacks)
{
outAllocs = *allocationCallbacks;
D3D12MA_ASSERT(outAllocs.pAllocate != NULL && outAllocs.pFree != NULL);
}
else
{
outAllocs.pAllocate = &DefaultAllocate;
outAllocs.pFree = &DefaultFree;
outAllocs.pUserData = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////
// Private globals - basic facilities
#define SAFE_RELEASE(ptr) do { if(ptr) { (ptr)->Release(); (ptr) = NULL; } } while(false)
#define D3D12MA_VALIDATE(cond) do { if(!(cond)) { \
D3D12MA_ASSERT(0 && "Validation failed: " #cond); \
return false; \
} } while(false)
const UINT NEW_BLOCK_SIZE_SHIFT_MAX = 3;
template<typename T>
static inline T D3D12MA_MIN(const T& a, const T& b)
{
return a <= b ? a : b;
}
template<typename T>
static inline T D3D12MA_MAX(const T& a, const T& b)
{
return a <= b ? b : a;
}
template<typename T>
static inline void D3D12MA_SWAP(T& a, T& b)
{
T tmp = a; a = b; b = tmp;
}
#ifndef D3D12MA_MUTEX
class Mutex
{
public:
void Lock() { m_Mutex.lock(); }
void Unlock() { m_Mutex.unlock(); }
private:
std::mutex m_Mutex;
};
#define D3D12MA_MUTEX Mutex
#endif
#if !defined(_WIN32) || !defined(WINVER) || WINVER < 0x0600
#error Required at least WinAPI version supporting: client = Windows Vista, server = Windows Server 2008.
#endif
#ifndef D3D12MA_RW_MUTEX
class RWMutex
{
public:
RWMutex() { InitializeSRWLock(&m_Lock); }
void LockRead() { AcquireSRWLockShared(&m_Lock); }
void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }
void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }
void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }
private:
SRWLOCK m_Lock;
};
#define D3D12MA_RW_MUTEX RWMutex
#endif
/*
If providing your own implementation, you need to implement a subset of std::atomic.
*/
#ifndef D3D12MA_ATOMIC_UINT32
#define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>
#endif
#ifndef D3D12MA_ATOMIC_UINT64
#define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>
#endif
/*
Returns true if given number is a power of two.
T must be unsigned integer number or signed integer but always nonnegative.
For 0 returns true.
*/
template <typename T>
inline bool IsPow2(T x)
{
return (x & (x-1)) == 0;
}
// Aligns given value up to nearest multiply of align value. For example: AlignUp(11, 8) = 16.
// Use types like UINT, uint64_t as T.
template <typename T>
static inline T AlignUp(T val, T alignment)
{
D3D12MA_HEAVY_ASSERT(IsPow2(alignment));
return (val + alignment - 1) & ~(alignment - 1);
}
// Aligns given value down to nearest multiply of align value. For example: AlignUp(11, 8) = 8.
// Use types like UINT, uint64_t as T.
template <typename T>
static inline T AlignDown(T val, T alignment)
{
D3D12MA_HEAVY_ASSERT(IsPow2(alignment));
return val & ~(alignment - 1);
}
// Division with mathematical rounding to nearest number.
template <typename T>
static inline T RoundDiv(T x, T y)
{
return (x + (y / (T)2)) / y;
}
template <typename T>
static inline T DivideRoudingUp(T x, T y)
{
return (x + y - 1) / y;
}
// Returns smallest power of 2 greater or equal to v.
static inline UINT NextPow2(UINT v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
static inline uint64_t NextPow2(uint64_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
// Returns largest power of 2 less or equal to v.
static inline UINT PrevPow2(UINT v)
{
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v = v ^ (v >> 1);
return v;
}
static inline uint64_t PrevPow2(uint64_t v)
{
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v = v ^ (v >> 1);
return v;
}
static inline bool StrIsEmpty(const char* pStr)
{
return pStr == NULL || *pStr == '\0';
}
// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
struct MutexLock
{
public:
MutexLock(D3D12MA_MUTEX& mutex, bool useMutex = true) :
m_pMutex(useMutex ? &mutex : NULL)
{
if(m_pMutex)
{
m_pMutex->Lock();
}
}
~MutexLock()
{
if(m_pMutex)
{
m_pMutex->Unlock();
}
}
private:
D3D12MA_MUTEX* m_pMutex;
D3D12MA_CLASS_NO_COPY(MutexLock)
};
// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading.
struct MutexLockRead
{
public:
MutexLockRead(D3D12MA_RW_MUTEX& mutex, bool useMutex) :
m_pMutex(useMutex ? &mutex : NULL)
{
if(m_pMutex)
{
m_pMutex->LockRead();
}
}
~MutexLockRead()
{
if(m_pMutex)
{
m_pMutex->UnlockRead();
}
}
private:
D3D12MA_RW_MUTEX* m_pMutex;
D3D12MA_CLASS_NO_COPY(MutexLockRead)
};
// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.
struct MutexLockWrite
{
public:
MutexLockWrite(D3D12MA_RW_MUTEX& mutex, bool useMutex) :
m_pMutex(useMutex ? &mutex : NULL)
{
if(m_pMutex)
{
m_pMutex->LockWrite();
}
}
~MutexLockWrite()
{
if(m_pMutex)
{
m_pMutex->UnlockWrite();
}
}
private:
D3D12MA_RW_MUTEX* m_pMutex;
D3D12MA_CLASS_NO_COPY(MutexLockWrite)
};
#if D3D12MA_DEBUG_GLOBAL_MUTEX
static D3D12MA_MUTEX g_DebugGlobalMutex;
#define D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK MutexLock debugGlobalMutexLock(g_DebugGlobalMutex, true);
#else
#define D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
#endif
// Minimum size of a free suballocation to register it in the free suballocation collection.
static const UINT64 MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;
/*
Performs binary search and returns iterator to first element that is greater or
equal to `key`, according to comparison `cmp`.
Cmp should return true if first argument is less than second argument.
Returned value is the found element, if present in the collection or place where
new element with value (key) should be inserted.
*/
template <typename CmpLess, typename IterT, typename KeyT>
static IterT BinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, const CmpLess& cmp)
{
size_t down = 0, up = (end - beg);
while(down < up)
{
const size_t mid = (down + up) / 2;
if(cmp(*(beg+mid), key))
{
down = mid + 1;
}
else
{
up = mid;
}
}
return beg + down;
}
/*
Performs binary search and returns iterator to an element that is equal to `key`,
according to comparison `cmp`.
Cmp should return true if first argument is less than second argument.
Returned value is the found element, if present in the collection or end if not
found.
*/
template<typename CmpLess, typename IterT, typename KeyT>
IterT BinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)
{
IterT it = BinaryFindFirstNotLess<CmpLess, IterT, KeyT>(beg, end, value, cmp);
if(it == end ||
(!cmp(*it, value) && !cmp(value, *it)))
{
return it;
}
return end;
}
struct PointerLess
{
bool operator()(const void* lhs, const void* rhs) const
{
return lhs < rhs;
}
};
static UINT HeapTypeToIndex(D3D12_HEAP_TYPE type)
{
switch(type)
{
case D3D12_HEAP_TYPE_DEFAULT: return 0;
case D3D12_HEAP_TYPE_UPLOAD: return 1;
case D3D12_HEAP_TYPE_READBACK: return 2;
default: D3D12MA_ASSERT(0); return UINT_MAX;
}
}
static const WCHAR* const HeapTypeNames[] = {
L"DEFAULT",
L"UPLOAD",
L"READBACK",
};
// Stat helper functions
static void AddStatInfo(StatInfo& dst, const StatInfo& src)
{
dst.BlockCount += src.BlockCount;
dst.AllocationCount += src.AllocationCount;
dst.UnusedRangeCount += src.UnusedRangeCount;
dst.UsedBytes += src.UsedBytes;
dst.UnusedBytes += src.UnusedBytes;
dst.AllocationSizeMin = D3D12MA_MIN(dst.AllocationSizeMin, src.AllocationSizeMin);
dst.AllocationSizeMax = D3D12MA_MAX(dst.AllocationSizeMax, src.AllocationSizeMax);
dst.UnusedRangeSizeMin = D3D12MA_MIN(dst.UnusedRangeSizeMin, src.UnusedRangeSizeMin);
dst.UnusedRangeSizeMax = D3D12MA_MAX(dst.UnusedRangeSizeMax, src.UnusedRangeSizeMax);
}
static void PostProcessStatInfo(StatInfo& statInfo)
{
statInfo.AllocationSizeAvg = statInfo.AllocationCount ?
statInfo.UsedBytes / statInfo.AllocationCount : 0;
statInfo.UnusedRangeSizeAvg = statInfo.UnusedRangeCount ?
statInfo.UnusedBytes / statInfo.UnusedRangeCount : 0;
}
static UINT64 HeapFlagsToAlignment(D3D12_HEAP_FLAGS flags)
{
/*
Documentation of D3D12_HEAP_DESC structure says:
- D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT defined as 64KB.
- D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT defined as 4MB. An
application must decide whether the heap will contain multi-sample
anti-aliasing (MSAA), in which case, the application must choose [this flag].
https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ns-d3d12-d3d12_heap_desc
*/
const D3D12_HEAP_FLAGS denyAllTexturesFlags =
D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES;
const bool canContainAnyTextures =
(flags & denyAllTexturesFlags) != denyAllTexturesFlags;
return canContainAnyTextures ?
D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
}
static bool IsFormatCompressed(DXGI_FORMAT format)
{
switch(format)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return true;
default:
return false;
}
}
// Only some formats are supported. For others it returns 0.
static UINT GetBitsPerPixel(DXGI_FORMAT format)
{
switch(format)
{
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_R32G32B32A32_UINT:
case DXGI_FORMAT_R32G32B32A32_SINT:
return 128;
case DXGI_FORMAT_R32G32B32_TYPELESS:
case DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT_R32G32B32_UINT:
case DXGI_FORMAT_R32G32B32_SINT:
return 96;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
case DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT_R16G16B16A16_UNORM:
case DXGI_FORMAT_R16G16B16A16_UINT:
case DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT_R16G16B16A16_SINT:
return 64;
case DXGI_FORMAT_R32G32_TYPELESS:
case DXGI_FORMAT_R32G32_FLOAT:
case DXGI_FORMAT_R32G32_UINT:
case DXGI_FORMAT_R32G32_SINT:
return 64;
case DXGI_FORMAT_R32G8X24_TYPELESS:
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
return 64;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
case DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT_R10G10B10A2_UINT:
case DXGI_FORMAT_R11G11B10_FLOAT:
return 32;
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT_R8G8B8A8_SNORM:
case DXGI_FORMAT_R8G8B8A8_SINT:
return 32;
case DXGI_FORMAT_R16G16_TYPELESS:
case DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT_R16G16_UNORM:
case DXGI_FORMAT_R16G16_UINT:
case DXGI_FORMAT_R16G16_SNORM:
case DXGI_FORMAT_R16G16_SINT:
return 32;
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT_R32_SINT:
return 32;
case DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
return 32;
case DXGI_FORMAT_R8G8_TYPELESS:
case DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT_R8G8_UINT:
case DXGI_FORMAT_R8G8_SNORM:
case DXGI_FORMAT_R8G8_SINT:
return 16;
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_D16_UNORM:
case DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT_R16_SNORM:
case DXGI_FORMAT_R16_SINT:
return 16;
case DXGI_FORMAT_R8_TYPELESS:
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R8_UINT:
case DXGI_FORMAT_R8_SNORM:
case DXGI_FORMAT_R8_SINT:
case DXGI_FORMAT_A8_UNORM:
return 8;
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
return 4;
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
return 8;
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
return 8;
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC4_SNORM:
return 4;
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC5_SNORM:
return 8;
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC6H_SF16:
return 8;
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return 8;
default:
return 0;
}
}
// This algorithm is overly conservative.
static bool CanUseSmallAlignment(const D3D12_RESOURCE_DESC& resourceDesc)
{
if(resourceDesc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D)
return false;
if((resourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0)
return false;
if(resourceDesc.SampleDesc.Count > 1)
return false;
if(resourceDesc.DepthOrArraySize != 1)
return false;
UINT sizeX = (UINT)resourceDesc.Width;
UINT sizeY = resourceDesc.Height;
UINT bitsPerPixel = GetBitsPerPixel(resourceDesc.Format);
if(bitsPerPixel == 0)
return false;
if(IsFormatCompressed(resourceDesc.Format))
{
sizeX = DivideRoudingUp(sizeX / 4, 1u);
sizeY = DivideRoudingUp(sizeY / 4, 1u);
bitsPerPixel *= 16;
}
UINT tileSizeX = 0, tileSizeY = 0;
switch(bitsPerPixel)
{
case 8: tileSizeX = 64; tileSizeY = 64; break;
case 16: tileSizeX = 64; tileSizeY = 32; break;
case 32: tileSizeX = 32; tileSizeY = 32; break;
case 64: tileSizeX = 32; tileSizeY = 16; break;
case 128: tileSizeX = 16; tileSizeY = 16; break;
default: return false;
}
const UINT tileCount = DivideRoudingUp(sizeX, tileSizeX) * DivideRoudingUp(sizeY, tileSizeY);
return tileCount <= 16;
}
static D3D12_HEAP_FLAGS GetExtraHeapFlagsToIgnore()
{
D3D12_HEAP_FLAGS result =
D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
return result;
}
static inline bool IsHeapTypeValid(D3D12_HEAP_TYPE type)
{
return type == D3D12_HEAP_TYPE_DEFAULT ||
type == D3D12_HEAP_TYPE_UPLOAD ||
type == D3D12_HEAP_TYPE_READBACK;
}
////////////////////////////////////////////////////////////////////////////////
// Private class Vector
/*
Dynamically resizing continuous array. Class with interface similar to std::vector.
T must be POD because constructors and destructors are not called and memcpy is
used for these objects.
*/
template<typename T>
class Vector
{
public:
typedef T value_type;
// allocationCallbacks externally owned, must outlive this object.
Vector(const ALLOCATION_CALLBACKS& allocationCallbacks) :
m_AllocationCallbacks(allocationCallbacks),
m_pArray(NULL),
m_Count(0),
m_Capacity(0)
{
}
Vector(size_t count, const ALLOCATION_CALLBACKS& allocationCallbacks) :
m_AllocationCallbacks(allocationCallbacks),
m_pArray(count ? AllocateArray<T>(allocationCallbacks, count) : NULL),
m_Count(count),
m_Capacity(count)
{
}
Vector(const Vector<T>& src) :
m_AllocationCallbacks(src.m_AllocationCallbacks),
m_pArray(src.m_Count ? AllocateArray<T>(src.m_AllocationCallbacks, src.m_Count) : NULL),
m_Count(src.m_Count),
m_Capacity(src.m_Count)
{
if(m_Count > 0)
{
memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
}
}
~Vector()
{
Free(m_AllocationCallbacks, m_pArray);
}
Vector& operator=(const Vector<T>& rhs)
{
if(&rhs != this)
{
resize(rhs.m_Count);
if(m_Count != 0)
{
memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
}
}
return *this;
}
bool empty() const { return m_Count == 0; }
size_t size() const { return m_Count; }
T* data() { return m_pArray; }
const T* data() const { return m_pArray; }
T& operator[](size_t index)
{
D3D12MA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
const T& operator[](size_t index) const
{
D3D12MA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
T& front()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
const T& front() const
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
T& back()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
const T& back() const
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
void reserve(size_t newCapacity, bool freeMemory = false)
{
newCapacity = D3D12MA_MAX(newCapacity, m_Count);
if((newCapacity < m_Capacity) && !freeMemory)
{
newCapacity = m_Capacity;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? AllocateArray<T>(m_AllocationCallbacks, newCapacity) : NULL;
if(m_Count != 0)
{
memcpy(newArray, m_pArray, m_Count * sizeof(T));
}
Free(m_AllocationCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
}
void resize(size_t newCount, bool freeMemory = false)
{
size_t newCapacity = m_Capacity;
if(newCount > m_Capacity)
{
newCapacity = D3D12MA_MAX(newCount, D3D12MA_MAX(m_Capacity * 3 / 2, (size_t)8));
}
else if(freeMemory)
{
newCapacity = newCount;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? AllocateArray<T>(m_AllocationCallbacks, newCapacity) : NULL;
const size_t elementsToCopy = D3D12MA_MIN(m_Count, newCount);
if(elementsToCopy != 0)
{
memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
}
Free(m_AllocationCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
m_Count = newCount;
}
void clear(bool freeMemory = false)
{
resize(0, freeMemory);
}
void insert(size_t index, const T& src)
{
D3D12MA_HEAVY_ASSERT(index <= m_Count);
const size_t oldCount = size();
resize(oldCount + 1);
if(index < oldCount)
{
memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
}
m_pArray[index] = src;
}
void remove(size_t index)
{
D3D12MA_HEAVY_ASSERT(index < m_Count);
const size_t oldCount = size();
if(index < oldCount - 1)
{
memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
}
resize(oldCount - 1);
}
void push_back(const T& src)
{
const size_t newIndex = size();
resize(newIndex + 1);
m_pArray[newIndex] = src;
}
void pop_back()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
resize(size() - 1);
}
void push_front(const T& src)
{
insert(0, src);
}
void pop_front()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
remove(0);
}
typedef T* iterator;
iterator begin() { return m_pArray; }
iterator end() { return m_pArray + m_Count; }
template<typename CmpLess>
size_t InsertSorted(const T& value, const CmpLess& cmp)
{
const size_t indexToInsert = BinaryFindFirstNotLess<CmpLess, iterator, T>(
m_pArray,
m_pArray + m_Count,
value,
cmp) - m_pArray;
insert(indexToInsert, value);
return indexToInsert;
}
template<typename CmpLess>
bool RemoveSorted(const T& value, const CmpLess& cmp)
{
const iterator it = BinaryFindFirstNotLess(
m_pArray,
m_pArray + m_Count,
value,
cmp);
if((it != end()) && !cmp(*it, value) && !cmp(value, *it))
{
size_t indexToRemove = it - begin();
remove(indexToRemove);
return true;
}
return false;
}
private:
const ALLOCATION_CALLBACKS& m_AllocationCallbacks;
T* m_pArray;
size_t m_Count;
size_t m_Capacity;
};
////////////////////////////////////////////////////////////////////////////////
// Private class StringBuilder
class StringBuilder
{
public:
StringBuilder(const ALLOCATION_CALLBACKS& allocationCallbacks) : m_Data(allocationCallbacks) { }
size_t GetLength() const { return m_Data.size(); }
LPCWSTR GetData() const { return m_Data.data(); }
void Add(WCHAR ch) { m_Data.push_back(ch); }
void Add(LPCWSTR str);
void AddNewLine() { Add(L'\n'); }
void AddNumber(UINT num);
void AddNumber(UINT64 num);
private:
Vector<WCHAR> m_Data;
};
void StringBuilder::Add(LPCWSTR str)
{
const size_t len = wcslen(str);
if (len > 0)
{
const size_t oldCount = m_Data.size();
m_Data.resize(oldCount + len);
memcpy(m_Data.data() + oldCount, str, len * sizeof(WCHAR));
}
}
void StringBuilder::AddNumber(UINT num)
{
WCHAR buf[11];
buf[10] = L'\0';
WCHAR *p = &buf[10];
do
{
*--p = L'0' + (num % 10);
num /= 10;
}
while (num);
Add(p);
}
void StringBuilder::AddNumber(UINT64 num)
{
WCHAR buf[21];
buf[20] = L'\0';
WCHAR *p = &buf[20];
do
{
*--p = L'0' + (num % 10);
num /= 10;
}
while (num);
Add(p);
}
////////////////////////////////////////////////////////////////////////////////
// Private class JsonWriter
class JsonWriter
{
public:
JsonWriter(const ALLOCATION_CALLBACKS& allocationCallbacks, StringBuilder& stringBuilder);
~JsonWriter();
void BeginObject(bool singleLine = false);
void EndObject();
void BeginArray(bool singleLine = false);
void EndArray();
void WriteString(LPCWSTR pStr);
void BeginString(LPCWSTR pStr = NULL);
void ContinueString(LPCWSTR pStr);
void ContinueString(UINT num);
void ContinueString(UINT64 num);
void AddAllocationToObject(const Allocation& alloc);
// void ContinueString_Pointer(const void* ptr);
void EndString(LPCWSTR pStr = NULL);
void WriteNumber(UINT num);
void WriteNumber(UINT64 num);
void WriteBool(bool b);
void WriteNull();
private:
static const WCHAR* const INDENT;
enum CollectionType
{
COLLECTION_TYPE_OBJECT,
COLLECTION_TYPE_ARRAY,
};
struct StackItem
{
CollectionType type;
UINT valueCount;
bool singleLineMode;
};
StringBuilder& m_SB;
Vector<StackItem> m_Stack;
bool m_InsideString;
void BeginValue(bool isString);
void WriteIndent(bool oneLess = false);
};
const WCHAR* const JsonWriter::INDENT = L" ";
JsonWriter::JsonWriter(const ALLOCATION_CALLBACKS& allocationCallbacks, StringBuilder& stringBuilder) :
m_SB(stringBuilder),
m_Stack(allocationCallbacks),
m_InsideString(false)
{
}
JsonWriter::~JsonWriter()
{
D3D12MA_ASSERT(!m_InsideString);
D3D12MA_ASSERT(m_Stack.empty());
}
void JsonWriter::BeginObject(bool singleLine)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add(L'{');
StackItem stackItem;
stackItem.type = COLLECTION_TYPE_OBJECT;
stackItem.valueCount = 0;
stackItem.singleLineMode = singleLine;
m_Stack.push_back(stackItem);
}
void JsonWriter::EndObject()
{
D3D12MA_ASSERT(!m_InsideString);
D3D12MA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
D3D12MA_ASSERT(m_Stack.back().valueCount % 2 == 0);
WriteIndent(true);
m_SB.Add(L'}');
m_Stack.pop_back();
}
void JsonWriter::BeginArray(bool singleLine)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add(L'[');
StackItem stackItem;
stackItem.type = COLLECTION_TYPE_ARRAY;
stackItem.valueCount = 0;
stackItem.singleLineMode = singleLine;
m_Stack.push_back(stackItem);
}
void JsonWriter::EndArray()
{
D3D12MA_ASSERT(!m_InsideString);
D3D12MA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
WriteIndent(true);
m_SB.Add(L']');
m_Stack.pop_back();
}
void JsonWriter::WriteString(LPCWSTR pStr)
{
BeginString(pStr);
EndString();
}
void JsonWriter::BeginString(LPCWSTR pStr)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(true);
m_InsideString = true;
m_SB.Add(L'"');
if (pStr != NULL)
{
ContinueString(pStr);
}
}
void JsonWriter::ContinueString(LPCWSTR pStr)
{
D3D12MA_ASSERT(m_InsideString);
D3D12MA_ASSERT(pStr);
for (const WCHAR *p = pStr; *p; ++p)
{
// the strings we encode are assumed to be in UTF-16LE format, the native
// windows wide character unicode format. In this encoding unicode code
// points U+0000 to U+D7FF and U+E000 to U+FFFF are encoded in two bytes,
// and everything else takes more than two bytes. We will reject any
// multi wchar character encodings for simplicity.
UINT val = (UINT)*p;
D3D12MA_ASSERT(((val <= 0xD7FF) || (0xE000 <= val && val <= 0xFFFF)) &&
"Character not currently supported.");
switch (*p)
{
case L'"': m_SB.Add(L'\\'); m_SB.Add(L'"'); break;
case L'\\': m_SB.Add(L'\\'); m_SB.Add(L'\\'); break;
case L'/': m_SB.Add(L'\\'); m_SB.Add(L'/'); break;
case L'\b': m_SB.Add(L'\\'); m_SB.Add(L'b'); break;
case L'\f': m_SB.Add(L'\\'); m_SB.Add(L'f'); break;
case L'\n': m_SB.Add(L'\\'); m_SB.Add(L'n'); break;
case L'\r': m_SB.Add(L'\\'); m_SB.Add(L'r'); break;
case L'\t': m_SB.Add(L'\\'); m_SB.Add(L't'); break;
default:
// conservatively use encoding \uXXXX for any unicode character
// requiring more than one byte.
if (32 <= val && val < 256)
m_SB.Add(*p);
else
{
m_SB.Add(L'\\');
m_SB.Add(L'u');
for (UINT i = 0; i < 4; ++i)
{
UINT hexDigit = (val & 0xF000) >> 12;
val <<= 4;
if (hexDigit < 10)
m_SB.Add(L'0' + (WCHAR)hexDigit);
else
m_SB.Add(L'A' + (WCHAR)hexDigit);
}
}
break;
}
}
}
void JsonWriter::ContinueString(UINT num)
{
D3D12MA_ASSERT(m_InsideString);
m_SB.AddNumber(num);
}
void JsonWriter::ContinueString(UINT64 num)
{
D3D12MA_ASSERT(m_InsideString);
m_SB.AddNumber(num);
}
void JsonWriter::EndString(LPCWSTR pStr)
{
D3D12MA_ASSERT(m_InsideString);
if (pStr)
ContinueString(pStr);
m_SB.Add(L'"');
m_InsideString = false;
}
void JsonWriter::WriteNumber(UINT num)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(num);
}
void JsonWriter::WriteNumber(UINT64 num)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(num);
}
void JsonWriter::WriteBool(bool b)
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
if (b)
m_SB.Add(L"true");
else
m_SB.Add(L"false");
}
void JsonWriter::WriteNull()
{
D3D12MA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add(L"null");
}
void JsonWriter::BeginValue(bool isString)
{
if (!m_Stack.empty())
{
StackItem& currItem = m_Stack.back();
if (currItem.type == COLLECTION_TYPE_OBJECT && currItem.valueCount % 2 == 0)
{
D3D12MA_ASSERT(isString);
}
if (currItem.type == COLLECTION_TYPE_OBJECT && currItem.valueCount % 2 == 1)
{
m_SB.Add(L':'); m_SB.Add(L' ');
}
else if (currItem.valueCount > 0)
{
m_SB.Add(L','); m_SB.Add(L' ');
WriteIndent();
}
else
{
WriteIndent();
}
++currItem.valueCount;
}
}
void JsonWriter::WriteIndent(bool oneLess)
{
if (!m_Stack.empty() && !m_Stack.back().singleLineMode)
{
m_SB.AddNewLine();
size_t count = m_Stack.size();
if (count > 0 && oneLess)
{
--count;
}
for (size_t i = 0; i < count; ++i)
{
m_SB.Add(INDENT);
}
}
}
void JsonWriter::AddAllocationToObject(const Allocation& alloc)
{
WriteString(L"Type");
switch (alloc.m_PackedData.GetResourceDimension()) {
case D3D12_RESOURCE_DIMENSION_UNKNOWN:
WriteString(L"UNKNOWN");
break;
case D3D12_RESOURCE_DIMENSION_BUFFER:
WriteString(L"BUFFER");
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE1D:
WriteString(L"TEXTURE1D");
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE2D:
WriteString(L"TEXTURE2D");
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE3D:
WriteString(L"TEXTURE3D");
break;
default: D3D12MA_ASSERT(0); break;
}
WriteString(L"Size");
WriteNumber(alloc.GetSize());
LPCWSTR name = alloc.GetName();
if(name != NULL)
{
WriteString(L"Name");
WriteString(name);
}
if(alloc.m_PackedData.GetResourceFlags())
{
WriteString(L"Flags");
WriteNumber((UINT)alloc.m_PackedData.GetResourceFlags());
}
if(alloc.m_PackedData.GetTextureLayout())
{
WriteString(L"Layout");
WriteNumber((UINT)alloc.m_PackedData.GetTextureLayout());
}
if(alloc.m_CreationFrameIndex)
{
WriteString(L"CreationFrameIndex");
WriteNumber(alloc.m_CreationFrameIndex);
}
}
////////////////////////////////////////////////////////////////////////////////
// Private class PoolAllocator
/*
Allocator for objects of type T using a list of arrays (pools) to speed up
allocation. Number of elements that can be allocated is not bounded because
allocator can create multiple blocks.
T should be POD because constructor and destructor is not called in Alloc or
Free.
*/
template<typename T>
class PoolAllocator
{
D3D12MA_CLASS_NO_COPY(PoolAllocator)
public:
// allocationCallbacks externally owned, must outlive this object.
PoolAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT firstBlockCapacity);
~PoolAllocator() { Clear(); }
void Clear();
template<typename... Types> T* Alloc(Types... args);
void Free(T* ptr);
private:
union Item
{
UINT NextFreeIndex; // UINT32_MAX means end of list.
alignas(T) char Value[sizeof(T)];
};
struct ItemBlock
{
Item* pItems;
UINT Capacity;
UINT FirstFreeIndex;
};
const ALLOCATION_CALLBACKS& m_AllocationCallbacks;
const UINT m_FirstBlockCapacity;
Vector<ItemBlock> m_ItemBlocks;
ItemBlock& CreateNewBlock();
};
template<typename T>
PoolAllocator<T>::PoolAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT firstBlockCapacity) :
m_AllocationCallbacks(allocationCallbacks),
m_FirstBlockCapacity(firstBlockCapacity),
m_ItemBlocks(allocationCallbacks)
{
D3D12MA_ASSERT(m_FirstBlockCapacity > 1);
}
template<typename T>
void PoolAllocator<T>::Clear()
{
for(size_t i = m_ItemBlocks.size(); i--; )
{
D3D12MA_DELETE_ARRAY(m_AllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);
}
m_ItemBlocks.clear(true);
}
template<typename T>
template<typename... Types> T* PoolAllocator<T>::Alloc(Types... args)
{
for(size_t i = m_ItemBlocks.size(); i--; )
{
ItemBlock& block = m_ItemBlocks[i];
// This block has some free items: Use first one.
if(block.FirstFreeIndex != UINT32_MAX)
{
Item* const pItem = &block.pItems[block.FirstFreeIndex];
block.FirstFreeIndex = pItem->NextFreeIndex;
T* result = (T*)&pItem->Value;
new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
return result;
}
}
// No block has free item: Create new one and use it.
ItemBlock& newBlock = CreateNewBlock();
Item* const pItem = &newBlock.pItems[0];
newBlock.FirstFreeIndex = pItem->NextFreeIndex;
T* result = (T*)pItem->Value;
new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
return result;
}
template<typename T>
void PoolAllocator<T>::Free(T* ptr)
{
// Search all memory blocks to find ptr.
for(size_t i = m_ItemBlocks.size(); i--; )
{
ItemBlock& block = m_ItemBlocks[i];
Item* pItemPtr;
memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
// Check if pItemPtr is in address range of this block.
if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))
{
ptr->~T(); // Explicit destructor call.
const UINT index = static_cast<UINT>(pItemPtr - block.pItems);
pItemPtr->NextFreeIndex = block.FirstFreeIndex;
block.FirstFreeIndex = index;
return;
}
}
D3D12MA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
}
template<typename T>
typename PoolAllocator<T>::ItemBlock& PoolAllocator<T>::CreateNewBlock()
{
const UINT newBlockCapacity = m_ItemBlocks.empty() ?
m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;
const ItemBlock newBlock = {
D3D12MA_NEW_ARRAY(m_AllocationCallbacks, Item, newBlockCapacity),
newBlockCapacity,
0 };
m_ItemBlocks.push_back(newBlock);
// Setup singly-linked list of all free items in this block.
for(UINT i = 0; i < newBlockCapacity - 1; ++i)
{
newBlock.pItems[i].NextFreeIndex = i + 1;
}
newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;
return m_ItemBlocks.back();
}
////////////////////////////////////////////////////////////////////////////////
// Private class List
/*
Doubly linked list, with elements allocated out of PoolAllocator.
Has custom interface, as well as STL-style interface, including iterator and
const_iterator.
*/
template<typename T>
class List
{
D3D12MA_CLASS_NO_COPY(List)
public:
struct Item
{
Item* pPrev;
Item* pNext;
T Value;
};
// allocationCallbacks externally owned, must outlive this object.
List(const ALLOCATION_CALLBACKS& allocationCallbacks);
~List();
void Clear();
size_t GetCount() const { return m_Count; }
bool IsEmpty() const { return m_Count == 0; }
Item* Front() { return m_pFront; }
const Item* Front() const { return m_pFront; }
Item* Back() { return m_pBack; }
const Item* Back() const { return m_pBack; }
Item* PushBack();
Item* PushFront();
Item* PushBack(const T& value);
Item* PushFront(const T& value);
void PopBack();
void PopFront();
// Item can be null - it means PushBack.
Item* InsertBefore(Item* pItem);
// Item can be null - it means PushFront.
Item* InsertAfter(Item* pItem);
Item* InsertBefore(Item* pItem, const T& value);
Item* InsertAfter(Item* pItem, const T& value);
void Remove(Item* pItem);
class iterator
{
public:
iterator() :
m_pList(NULL),
m_pItem(NULL)
{
}
T& operator*() const
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
return m_pItem->Value;
}
T* operator->() const
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
return &m_pItem->Value;
}
iterator& operator++()
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
m_pItem = m_pItem->pNext;
return *this;
}
iterator& operator--()
{
if(m_pItem != NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
D3D12MA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
iterator operator++(int)
{
iterator result = *this;
++*this;
return result;
}
iterator operator--(int)
{
iterator result = *this;
--*this;
return result;
}
bool operator==(const iterator& rhs) const
{
D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const iterator& rhs) const
{
D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
List<T>* m_pList;
Item* m_pItem;
iterator(List<T>* pList, Item* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
friend class List<T>;
};
class const_iterator
{
public:
const_iterator() :
m_pList(NULL),
m_pItem(NULL)
{
}
const_iterator(const iterator& src) :
m_pList(src.m_pList),
m_pItem(src.m_pItem)
{
}
const T& operator*() const
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
return m_pItem->Value;
}
const T* operator->() const
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
return &m_pItem->Value;
}
const_iterator& operator++()
{
D3D12MA_HEAVY_ASSERT(m_pItem != NULL);
m_pItem = m_pItem->pNext;
return *this;
}
const_iterator& operator--()
{
if(m_pItem != NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
D3D12MA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
const_iterator operator++(int)
{
const_iterator result = *this;
++*this;
return result;
}
const_iterator operator--(int)
{
const_iterator result = *this;
--*this;
return result;
}
bool operator==(const const_iterator& rhs) const
{
D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const const_iterator& rhs) const
{
D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
const_iterator(const List<T>* pList, const Item* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
const List<T>* m_pList;
const Item* m_pItem;
friend class List<T>;
};
bool empty() const { return IsEmpty(); }
size_t size() const { return GetCount(); }
iterator begin() { return iterator(this, Front()); }
iterator end() { return iterator(this, NULL); }
const_iterator cbegin() const { return const_iterator(this, Front()); }
const_iterator cend() const { return const_iterator(this, NULL); }
void clear() { Clear(); }
void push_back(const T& value) { PushBack(value); }
void erase(iterator it) { Remove(it.m_pItem); }
iterator insert(iterator it, const T& value) { return iterator(this, InsertBefore(it.m_pItem, value)); }
private:
const ALLOCATION_CALLBACKS& m_AllocationCallbacks;
PoolAllocator<Item> m_ItemAllocator;
Item* m_pFront;
Item* m_pBack;
size_t m_Count;
};
template<typename T>
List<T>::List(const ALLOCATION_CALLBACKS& allocationCallbacks) :
m_AllocationCallbacks(allocationCallbacks),
m_ItemAllocator(allocationCallbacks, 128),
m_pFront(NULL),
m_pBack(NULL),
m_Count(0)
{
}
template<typename T>
List<T>::~List()
{
// Intentionally not calling Clear, because that would be unnecessary
// computations to return all items to m_ItemAllocator as free.
}
template<typename T>
void List<T>::Clear()
{
if(!IsEmpty())
{
Item* pItem = m_pBack;
while(pItem != NULL)
{
Item* const pPrevItem = pItem->pPrev;
m_ItemAllocator.Free(pItem);
pItem = pPrevItem;
}
m_pFront = NULL;
m_pBack = NULL;
m_Count = 0;
}
}
template<typename T>
typename List<T>::Item* List<T>::PushBack()
{
Item* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pNext = NULL;
if(IsEmpty())
{
pNewItem->pPrev = NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pPrev = m_pBack;
m_pBack->pNext = pNewItem;
m_pBack = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
typename List<T>::Item* List<T>::PushFront()
{
Item* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pPrev = NULL;
if(IsEmpty())
{
pNewItem->pNext = NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pNext = m_pFront;
m_pFront->pPrev = pNewItem;
m_pFront = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
typename List<T>::Item* List<T>::PushBack(const T& value)
{
Item* const pNewItem = PushBack();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
typename List<T>::Item* List<T>::PushFront(const T& value)
{
Item* const pNewItem = PushFront();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
void List<T>::PopBack()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
Item* const pBackItem = m_pBack;
Item* const pPrevItem = pBackItem->pPrev;
if(pPrevItem != NULL)
{
pPrevItem->pNext = NULL;
}
m_pBack = pPrevItem;
m_ItemAllocator.Free(pBackItem);
--m_Count;
}
template<typename T>
void List<T>::PopFront()
{
D3D12MA_HEAVY_ASSERT(m_Count > 0);
Item* const pFrontItem = m_pFront;
Item* const pNextItem = pFrontItem->pNext;
if(pNextItem != NULL)
{
pNextItem->pPrev = NULL;
}
m_pFront = pNextItem;
m_ItemAllocator.Free(pFrontItem);
--m_Count;
}
template<typename T>
void List<T>::Remove(Item* pItem)
{
D3D12MA_HEAVY_ASSERT(pItem != NULL);
D3D12MA_HEAVY_ASSERT(m_Count > 0);
if(pItem->pPrev != NULL)
{
pItem->pPrev->pNext = pItem->pNext;
}
else
{
D3D12MA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = pItem->pNext;
}
if(pItem->pNext != NULL)
{
pItem->pNext->pPrev = pItem->pPrev;
}
else
{
D3D12MA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = pItem->pPrev;
}
m_ItemAllocator.Free(pItem);
--m_Count;
}
template<typename T>
typename List<T>::Item* List<T>::InsertBefore(Item* pItem)
{
if(pItem != NULL)
{
Item* const prevItem = pItem->pPrev;
Item* const newItem = m_ItemAllocator.Alloc();
newItem->pPrev = prevItem;
newItem->pNext = pItem;
pItem->pPrev = newItem;
if(prevItem != NULL)
{
prevItem->pNext = newItem;
}
else
{
D3D12MA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = newItem;
}
++m_Count;
return newItem;
}
else
{
return PushBack();
}
}
template<typename T>
typename List<T>::Item* List<T>::InsertAfter(Item* pItem)
{
if(pItem != NULL)
{
Item* const nextItem = pItem->pNext;
Item* const newItem = m_ItemAllocator.Alloc();
newItem->pNext = nextItem;
newItem->pPrev = pItem;
pItem->pNext = newItem;
if(nextItem != NULL)
{
nextItem->pPrev = newItem;
}
else
{
D3D12MA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = newItem;
}
++m_Count;
return newItem;
}
else
return PushFront();
}
template<typename T>
typename List<T>::Item* List<T>::InsertBefore(Item* pItem, const T& value)
{
Item* const newItem = InsertBefore(pItem);
newItem->Value = value;
return newItem;
}
template<typename T>
typename List<T>::Item* List<T>::InsertAfter(Item* pItem, const T& value)
{
Item* const newItem = InsertAfter(pItem);
newItem->Value = value;
return newItem;
}
////////////////////////////////////////////////////////////////////////////////
// Private class AllocationObjectAllocator definition
/*
Thread-safe wrapper over PoolAllocator free list, for allocation of Allocation objects.
*/
class AllocationObjectAllocator
{
D3D12MA_CLASS_NO_COPY(AllocationObjectAllocator);
public:
AllocationObjectAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks);
template<typename... Types> Allocation* Allocate(Types... args);
void Free(Allocation* alloc);
private:
D3D12MA_MUTEX m_Mutex;
PoolAllocator<Allocation> m_Allocator;
};
////////////////////////////////////////////////////////////////////////////////
// Private class BlockMetadata and derived classes - declarations
enum SuballocationType
{
SUBALLOCATION_TYPE_FREE = 0,
SUBALLOCATION_TYPE_ALLOCATION = 1,
};
/*
Represents a region of NormalBlock that is either assigned and returned as
allocated memory block or free.
*/
struct Suballocation
{
UINT64 offset;
UINT64 size;
void* userData;
SuballocationType type;
};
// Comparator for offsets.
struct SuballocationOffsetLess
{
bool operator()(const Suballocation& lhs, const Suballocation& rhs) const
{
return lhs.offset < rhs.offset;
}
};
struct SuballocationOffsetGreater
{
bool operator()(const Suballocation& lhs, const Suballocation& rhs) const
{
return lhs.offset > rhs.offset;
}
};
typedef List<Suballocation> SuballocationList;
struct SuballocationItemSizeLess
{
bool operator()(const SuballocationList::iterator lhs, const SuballocationList::iterator rhs) const
{
return lhs->size < rhs->size;
}
bool operator()(const SuballocationList::iterator lhs, UINT64 rhsSize) const
{
return lhs->size < rhsSize;
}
};
/*
Parameters of planned allocation inside a NormalBlock.
*/
struct AllocationRequest
{
UINT64 offset;
UINT64 sumFreeSize; // Sum size of free items that overlap with proposed allocation.
UINT64 sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.
SuballocationList::iterator item;
BOOL zeroInitialized;
};
/*
Keeps track of the range of bytes that are surely initialized with zeros.
Everything outside of it is considered uninitialized memory that may contain
garbage data.
The range is left-inclusive.
*/
class ZeroInitializedRange
{
public:
void Reset(UINT64 size)
{
D3D12MA_ASSERT(size > 0);
m_ZeroBeg = 0;
m_ZeroEnd = size;
}
BOOL IsRangeZeroInitialized(UINT64 beg, UINT64 end) const
{
D3D12MA_ASSERT(beg < end);
return m_ZeroBeg <= beg && end <= m_ZeroEnd;
}
void MarkRangeAsUsed(UINT64 usedBeg, UINT64 usedEnd)
{
D3D12MA_ASSERT(usedBeg < usedEnd);
// No new bytes marked.
if(usedEnd <= m_ZeroBeg || m_ZeroEnd <= usedBeg)
{
return;
}
// All bytes marked.
if(usedBeg <= m_ZeroBeg && m_ZeroEnd <= usedEnd)
{
m_ZeroBeg = m_ZeroEnd = 0;
}
// Some bytes marked.
else
{
const UINT64 remainingZeroBefore = usedBeg > m_ZeroBeg ? usedBeg - m_ZeroBeg : 0;
const UINT64 remainingZeroAfter = usedEnd < m_ZeroEnd ? m_ZeroEnd - usedEnd : 0;
D3D12MA_ASSERT(remainingZeroBefore > 0 || remainingZeroAfter > 0);
if(remainingZeroBefore > remainingZeroAfter)
{
m_ZeroEnd = usedBeg;
}
else
{
m_ZeroBeg = usedEnd;
}
}
}
private:
UINT64 m_ZeroBeg = 0, m_ZeroEnd = 0;
};
/*
Data structure used for bookkeeping of allocations and unused ranges of memory
in a single ID3D12Heap memory block.
*/
class BlockMetadata
{
public:
BlockMetadata(const ALLOCATION_CALLBACKS* allocationCallbacks, bool isVirtual);
virtual ~BlockMetadata() { }
virtual void Init(UINT64 size) { m_Size = size; }
// Validates all data structures inside this object. If not valid, returns false.
virtual bool Validate() const = 0;
UINT64 GetSize() const { return m_Size; }
bool IsVirtual() const { return m_IsVirtual; }
virtual size_t GetAllocationCount() const = 0;
virtual UINT64 GetSumFreeSize() const = 0;
virtual UINT64 GetUnusedRangeSizeMax() const = 0;
// Returns true if this block is empty - contains only single free suballocation.
virtual bool IsEmpty() const = 0;
virtual void GetAllocationInfo(UINT64 offset, VIRTUAL_ALLOCATION_INFO& outInfo) const = 0;
// Tries to find a place for suballocation with given parameters inside this block.
// If succeeded, fills pAllocationRequest and returns true.
// If failed, returns false.
virtual bool CreateAllocationRequest(
UINT64 allocSize,
UINT64 allocAlignment,
AllocationRequest* pAllocationRequest) = 0;
// Makes actual allocation based on request. Request must already be checked and valid.
virtual void Alloc(
const AllocationRequest& request,
UINT64 allocSize,
void* userData) = 0;
virtual void FreeAtOffset(UINT64 offset) = 0;
// Frees all allocations.
// Careful! Don't call it if there are Allocation objects owned by pUserData of of cleared allocations!
virtual void Clear() = 0;
virtual void SetAllocationUserData(UINT64 offset, void* userData) = 0;
virtual void CalcAllocationStatInfo(StatInfo& outInfo) const = 0;
virtual void WriteAllocationInfoToJson(JsonWriter& json) const = 0;
protected:
const ALLOCATION_CALLBACKS* GetAllocs() const { return m_pAllocationCallbacks; }
private:
UINT64 m_Size;
bool m_IsVirtual;
const ALLOCATION_CALLBACKS* m_pAllocationCallbacks;
D3D12MA_CLASS_NO_COPY(BlockMetadata);
};
class BlockMetadata_Generic : public BlockMetadata
{
public:
BlockMetadata_Generic(const ALLOCATION_CALLBACKS* allocationCallbacks, bool isVirtual);
virtual ~BlockMetadata_Generic();
virtual void Init(UINT64 size);
virtual bool Validate() const;
virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }
virtual UINT64 GetSumFreeSize() const { return m_SumFreeSize; }
virtual UINT64 GetUnusedRangeSizeMax() const;
virtual bool IsEmpty() const;
virtual void GetAllocationInfo(UINT64 offset, VIRTUAL_ALLOCATION_INFO& outInfo) const;
virtual bool CreateAllocationRequest(
UINT64 allocSize,
UINT64 allocAlignment,
AllocationRequest* pAllocationRequest);
virtual void Alloc(
const AllocationRequest& request,
UINT64 allocSize,
void* userData);
virtual void FreeAtOffset(UINT64 offset);
virtual void Clear();
virtual void SetAllocationUserData(UINT64 offset, void* userData);
virtual void CalcAllocationStatInfo(StatInfo& outInfo) const;
virtual void WriteAllocationInfoToJson(JsonWriter& json) const;
private:
UINT m_FreeCount;
UINT64 m_SumFreeSize;
SuballocationList m_Suballocations;
// Suballocations that are free and have size greater than certain threshold.
// Sorted by size, ascending.
Vector<SuballocationList::iterator> m_FreeSuballocationsBySize;
ZeroInitializedRange m_ZeroInitializedRange;
bool ValidateFreeSuballocationList() const;
// Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
// If yes, fills pOffset and returns true. If no, returns false.
bool CheckAllocation(
UINT64 allocSize,
UINT64 allocAlignment,
SuballocationList::const_iterator suballocItem,
UINT64* pOffset,
UINT64* pSumFreeSize,
UINT64* pSumItemSize,
BOOL *pZeroInitialized) const;
// Given free suballocation, it merges it with following one, which must also be free.
void MergeFreeWithNext(SuballocationList::iterator item);
// Releases given suballocation, making it free.
// Merges it with adjacent free suballocations if applicable.
// Returns iterator to new free suballocation at this place.
SuballocationList::iterator FreeSuballocation(SuballocationList::iterator suballocItem);
// Given free suballocation, it inserts it into sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void RegisterFreeSuballocation(SuballocationList::iterator item);
// Given free suballocation, it removes it from sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void UnregisterFreeSuballocation(SuballocationList::iterator item);
D3D12MA_CLASS_NO_COPY(BlockMetadata_Generic)
};
////////////////////////////////////////////////////////////////////////////////
// Private class MemoryBlock definition
/*
Represents a single block of device memory (heap).
Base class for inheritance.
Thread-safety: This class must be externally synchronized.
*/
class MemoryBlock
{
public:
MemoryBlock(
AllocatorPimpl* allocator,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 size,
UINT id);
virtual ~MemoryBlock();
// Creates the ID3D12Heap.
D3D12_HEAP_TYPE GetHeapType() const { return m_HeapType; }
D3D12_HEAP_FLAGS GetHeapFlags() const { return m_HeapFlags; }
UINT64 GetSize() const { return m_Size; }
UINT GetId() const { return m_Id; }
ID3D12Heap* GetHeap() const { return m_Heap; }
protected:
AllocatorPimpl* const m_Allocator;
const D3D12_HEAP_TYPE m_HeapType;
const D3D12_HEAP_FLAGS m_HeapFlags;
const UINT64 m_Size;
const UINT m_Id;
HRESULT Init();
private:
ID3D12Heap* m_Heap = NULL;
D3D12MA_CLASS_NO_COPY(MemoryBlock)
};
////////////////////////////////////////////////////////////////////////////////
// Private class NormalBlock definition
/*
Represents a single block of device memory (heap) with all the data about its
regions (aka suballocations, Allocation), assigned and free.
Thread-safety: This class must be externally synchronized.
*/
class NormalBlock : public MemoryBlock
{
public:
BlockMetadata* m_pMetadata;
NormalBlock(
AllocatorPimpl* allocator,
BlockVector* blockVector,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 size,
UINT id);
virtual ~NormalBlock();
HRESULT Init();
BlockVector* GetBlockVector() const { return m_BlockVector; }
// Validates all data structures inside this object. If not valid, returns false.
bool Validate() const;
private:
BlockVector* m_BlockVector;
D3D12MA_CLASS_NO_COPY(NormalBlock)
};
////////////////////////////////////////////////////////////////////////////////
// Private class BlockVector definition
/*
Sequence of NormalBlock. Represents memory blocks allocated for a specific
heap type and possibly resource type (if only Tier 1 is supported).
Synchronized internally with a mutex.
*/
class BlockVector
{
D3D12MA_CLASS_NO_COPY(BlockVector)
public:
BlockVector(
AllocatorPimpl* hAllocator,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
bool explicitBlockSize);
~BlockVector();
HRESULT CreateMinBlocks();
UINT GetHeapType() const { return m_HeapType; }
UINT64 GetPreferredBlockSize() const { return m_PreferredBlockSize; }
bool IsEmpty();
HRESULT Allocate(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
size_t allocationCount,
Allocation** pAllocations);
void Free(
Allocation* hAllocation);
HRESULT CreateResource(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
const D3D12_RESOURCE_DESC& resourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
HRESULT SetMinBytes(UINT64 minBytes);
void AddStats(StatInfo& outStats);
void AddStats(Stats& outStats);
void WriteBlockInfoToJson(JsonWriter& json);
private:
AllocatorPimpl* const m_hAllocator;
const D3D12_HEAP_TYPE m_HeapType;
const D3D12_HEAP_FLAGS m_HeapFlags;
const UINT64 m_PreferredBlockSize;
const size_t m_MinBlockCount;
const size_t m_MaxBlockCount;
const bool m_ExplicitBlockSize;
UINT64 m_MinBytes;
/* There can be at most one allocation that is completely empty - a
hysteresis to avoid pessimistic case of alternating creation and destruction
of a VkDeviceMemory. */
bool m_HasEmptyBlock;
D3D12MA_RW_MUTEX m_Mutex;
// Incrementally sorted by sumFreeSize, ascending.
Vector<NormalBlock*> m_Blocks;
UINT m_NextBlockId;
UINT64 CalcSumBlockSize() const;
UINT64 CalcMaxBlockSize() const;
// Finds and removes given block from vector.
void Remove(NormalBlock* pBlock);
// Performs single step in sorting m_Blocks. They may not be fully sorted
// after this call.
void IncrementallySortBlocks();
HRESULT AllocatePage(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
Allocation** pAllocation);
HRESULT AllocateFromBlock(
NormalBlock* pBlock,
UINT64 size,
UINT64 alignment,
ALLOCATION_FLAGS allocFlags,
Allocation** pAllocation);
HRESULT CreateBlock(UINT64 blockSize, size_t* pNewBlockIndex);
};
////////////////////////////////////////////////////////////////////////////////
// Private class AllocatorPimpl definition
static const UINT DEFAULT_POOL_MAX_COUNT = 9;
struct CurrentBudgetData
{
D3D12MA_ATOMIC_UINT64 m_BlockBytes[HEAP_TYPE_COUNT];
D3D12MA_ATOMIC_UINT64 m_AllocationBytes[HEAP_TYPE_COUNT];
D3D12MA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch;
D3D12MA_RW_MUTEX m_BudgetMutex;
UINT64 m_D3D12UsageLocal, m_D3D12UsageNonLocal;
UINT64 m_D3D12BudgetLocal, m_D3D12BudgetNonLocal;
UINT64 m_BlockBytesAtBudgetFetch[HEAP_TYPE_COUNT];
CurrentBudgetData()
{
for(UINT i = 0; i < HEAP_TYPE_COUNT; ++i)
{
m_BlockBytes[i] = 0;
m_AllocationBytes[i] = 0;
m_BlockBytesAtBudgetFetch[i] = 0;
}
m_D3D12UsageLocal = 0;
m_D3D12UsageNonLocal = 0;
m_D3D12BudgetLocal = 0;
m_D3D12BudgetNonLocal = 0;
m_OperationsSinceBudgetFetch = 0;
}
void AddAllocation(UINT heapTypeIndex, UINT64 allocationSize)
{
m_AllocationBytes[heapTypeIndex] += allocationSize;
++m_OperationsSinceBudgetFetch;
}
void RemoveAllocation(UINT heapTypeIndex, UINT64 allocationSize)
{
m_AllocationBytes[heapTypeIndex] -= allocationSize;
++m_OperationsSinceBudgetFetch;
}
};
class AllocatorPimpl
{
public:
CurrentBudgetData m_Budget;
AllocatorPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);
HRESULT Init(const ALLOCATOR_DESC& desc);
~AllocatorPimpl();
ID3D12Device* GetDevice() const { return m_Device; }
// Shortcut for "Allocation Callbacks", because this function is called so often.
const ALLOCATION_CALLBACKS& GetAllocs() const { return m_AllocationCallbacks; }
const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const { return m_D3D12Options; }
bool SupportsResourceHeapTier2() const { return m_D3D12Options.ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2; }
bool UseMutex() const { return m_UseMutex; }
AllocationObjectAllocator& GetAllocationObjectAllocator() { return m_AllocationObjectAllocator; }
bool HeapFlagsFulfillResourceHeapTier(D3D12_HEAP_FLAGS flags) const;
HRESULT CreateResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
HRESULT AllocateMemory(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
Allocation** ppAllocation);
HRESULT CreateAliasingResource(
Allocation* pAllocation,
UINT64 AllocationLocalOffset,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
REFIID riidResource,
void** ppvResource);
HRESULT SetDefaultHeapMinBytes(
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 minBytes);
// Unregisters allocation from the collection of dedicated allocations.
// Allocation object must be deleted externally afterwards.
void FreeCommittedMemory(Allocation* allocation);
// Unregisters allocation from the collection of placed allocations.
// Allocation object must be deleted externally afterwards.
void FreePlacedMemory(Allocation* allocation);
// Unregisters allocation from the collection of dedicated allocations and destroys associated heap.
// Allocation object must be deleted externally afterwards.
void FreeHeapMemory(Allocation* allocation);
void SetCurrentFrameIndex(UINT frameIndex);
UINT GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
void CalculateStats(Stats& outStats);
void GetBudget(Budget* outGpuBudget, Budget* outCpuBudget);
void GetBudgetForHeapType(Budget& outBudget, D3D12_HEAP_TYPE heapType);
void BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap);
void FreeStatsString(WCHAR* pStatsString);
private:
friend class Allocator;
friend class Pool;
/*
Heuristics that decides whether a resource should better be placed in its own,
dedicated allocation (committed resource rather than placed resource).
*/
static bool PrefersCommittedAllocation(const D3D12_RESOURCE_DESC& resourceDesc);
const bool m_UseMutex;
const bool m_AlwaysCommitted;
ID3D12Device* m_Device; // AddRef
IDXGIAdapter* m_Adapter; // AddRef
#if D3D12MA_DXGI_1_4
IDXGIAdapter3* m_Adapter3; // AddRef, optional
#endif
UINT64 m_PreferredBlockSize;
ALLOCATION_CALLBACKS m_AllocationCallbacks;
D3D12MA_ATOMIC_UINT32 m_CurrentFrameIndex;
DXGI_ADAPTER_DESC m_AdapterDesc;
D3D12_FEATURE_DATA_D3D12_OPTIONS m_D3D12Options;
AllocationObjectAllocator m_AllocationObjectAllocator;
typedef Vector<Allocation*> AllocationVectorType;
AllocationVectorType* m_pCommittedAllocations[HEAP_TYPE_COUNT];
D3D12MA_RW_MUTEX m_CommittedAllocationsMutex[HEAP_TYPE_COUNT];
typedef Vector<Pool*> PoolVectorType;
PoolVectorType* m_pPools[HEAP_TYPE_COUNT];
D3D12MA_RW_MUTEX m_PoolsMutex[HEAP_TYPE_COUNT];
// Default pools.
BlockVector* m_BlockVectors[DEFAULT_POOL_MAX_COUNT];
// # Used only when ResourceHeapTier = 1
UINT64 m_DefaultPoolTier1MinBytes[DEFAULT_POOL_MAX_COUNT]; // Default 0
UINT64 m_DefaultPoolHeapTypeMinBytes[HEAP_TYPE_COUNT]; // Default UINT64_MAX, meaning not set
D3D12MA_RW_MUTEX m_DefaultPoolMinBytesMutex;
// Allocates and registers new committed resource with implicit heap, as dedicated allocation.
// Creates and returns Allocation object.
HRESULT AllocateCommittedResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
// Allocates and registers new heap without any resources placed in it, as dedicated allocation.
// Creates and returns Allocation object.
HRESULT AllocateHeap(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO& allocInfo,
Allocation** ppAllocation);
/*
If SupportsResourceHeapTier2():
0: D3D12_HEAP_TYPE_DEFAULT
1: D3D12_HEAP_TYPE_UPLOAD
2: D3D12_HEAP_TYPE_READBACK
else:
0: D3D12_HEAP_TYPE_DEFAULT + buffer
1: D3D12_HEAP_TYPE_DEFAULT + texture
2: D3D12_HEAP_TYPE_DEFAULT + texture RT or DS
3: D3D12_HEAP_TYPE_UPLOAD + buffer
4: D3D12_HEAP_TYPE_UPLOAD + texture
5: D3D12_HEAP_TYPE_UPLOAD + texture RT or DS
6: D3D12_HEAP_TYPE_READBACK + buffer
7: D3D12_HEAP_TYPE_READBACK + texture
8: D3D12_HEAP_TYPE_READBACK + texture RT or DS
*/
UINT CalcDefaultPoolCount() const;
UINT CalcDefaultPoolIndex(const ALLOCATION_DESC& allocDesc, const D3D12_RESOURCE_DESC& resourceDesc) const;
// This one returns UINT32_MAX if nonstandard heap flags are used and index cannot be calculcated.
static UINT CalcDefaultPoolIndex(D3D12_HEAP_TYPE heapType, D3D12_HEAP_FLAGS heapFlags, bool supportsResourceHeapTier2);
UINT CalcDefaultPoolIndex(D3D12_HEAP_TYPE heapType, D3D12_HEAP_FLAGS heapFlags) const
{
return CalcDefaultPoolIndex(heapType, heapFlags, SupportsResourceHeapTier2());
}
UINT CalcDefaultPoolIndex(const ALLOCATION_DESC& allocDesc) const
{
return CalcDefaultPoolIndex(allocDesc.HeapType, allocDesc.ExtraHeapFlags);
}
void CalcDefaultPoolParams(D3D12_HEAP_TYPE& outHeapType, D3D12_HEAP_FLAGS& outHeapFlags, UINT index) const;
// Registers Allocation object in m_pCommittedAllocations.
void RegisterCommittedAllocation(Allocation* alloc, D3D12_HEAP_TYPE heapType);
// Unregisters Allocation object from m_pCommittedAllocations.
void UnregisterCommittedAllocation(Allocation* alloc, D3D12_HEAP_TYPE heapType);
// Registers Pool object in m_pPools.
void RegisterPool(Pool* pool, D3D12_HEAP_TYPE heapType);
// Unregisters Pool object from m_pPools.
void UnregisterPool(Pool* pool, D3D12_HEAP_TYPE heapType);
HRESULT UpdateD3D12Budget();
D3D12_RESOURCE_ALLOCATION_INFO GetResourceAllocationInfo(D3D12_RESOURCE_DESC& inOutResourceDesc) const;
// Writes object { } with data of given budget.
static void WriteBudgetToJson(JsonWriter& json, const Budget& budget);
};
////////////////////////////////////////////////////////////////////////////////
// Private class BlockMetadata implementation
BlockMetadata::BlockMetadata(const ALLOCATION_CALLBACKS* allocationCallbacks, bool isVirtual) :
m_Size(0),
m_IsVirtual(isVirtual),
m_pAllocationCallbacks(allocationCallbacks)
{
D3D12MA_ASSERT(allocationCallbacks);
}
////////////////////////////////////////////////////////////////////////////////
// Private class BlockMetadata_Generic implementation
BlockMetadata_Generic::BlockMetadata_Generic(const ALLOCATION_CALLBACKS* allocationCallbacks, bool isVirtual) :
BlockMetadata(allocationCallbacks, isVirtual),
m_FreeCount(0),
m_SumFreeSize(0),
m_Suballocations(*allocationCallbacks),
m_FreeSuballocationsBySize(*allocationCallbacks)
{
D3D12MA_ASSERT(allocationCallbacks);
}
BlockMetadata_Generic::~BlockMetadata_Generic()
{
}
void BlockMetadata_Generic::Init(UINT64 size)
{
BlockMetadata::Init(size);
m_ZeroInitializedRange.Reset(size);
m_FreeCount = 1;
m_SumFreeSize = size;
Suballocation suballoc = {};
suballoc.offset = 0;
suballoc.size = size;
suballoc.type = SUBALLOCATION_TYPE_FREE;
suballoc.userData = NULL;
D3D12MA_ASSERT(size > MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
m_Suballocations.push_back(suballoc);
SuballocationList::iterator suballocItem = m_Suballocations.end();
--suballocItem;
m_FreeSuballocationsBySize.push_back(suballocItem);
}
bool BlockMetadata_Generic::Validate() const
{
D3D12MA_VALIDATE(!m_Suballocations.empty());
// Expected offset of new suballocation as calculated from previous ones.
UINT64 calculatedOffset = 0;
// Expected number of free suballocations as calculated from traversing their list.
UINT calculatedFreeCount = 0;
// Expected sum size of free suballocations as calculated from traversing their list.
UINT64 calculatedSumFreeSize = 0;
// Expected number of free suballocations that should be registered in
// m_FreeSuballocationsBySize calculated from traversing their list.
size_t freeSuballocationsToRegister = 0;
// True if previous visited suballocation was free.
bool prevFree = false;
for(SuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const Suballocation& subAlloc = *suballocItem;
// Actual offset of this suballocation doesn't match expected one.
D3D12MA_VALIDATE(subAlloc.offset == calculatedOffset);
const bool currFree = (subAlloc.type == SUBALLOCATION_TYPE_FREE);
// Two adjacent free suballocations are invalid. They should be merged.
D3D12MA_VALIDATE(!prevFree || !currFree);
const Allocation* const alloc = (Allocation*)subAlloc.userData;
if(!IsVirtual())
{
D3D12MA_VALIDATE(currFree == (alloc == NULL));
}
if(currFree)
{
calculatedSumFreeSize += subAlloc.size;
++calculatedFreeCount;
if(subAlloc.size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
++freeSuballocationsToRegister;
}
// Margin required between allocations - every free space must be at least that large.
D3D12MA_VALIDATE(subAlloc.size >= D3D12MA_DEBUG_MARGIN);
}
else
{
if(!IsVirtual())
{
D3D12MA_VALIDATE(alloc->GetOffset() == subAlloc.offset);
D3D12MA_VALIDATE(alloc->GetSize() == subAlloc.size);
}
// Margin required between allocations - previous allocation must be free.
D3D12MA_VALIDATE(D3D12MA_DEBUG_MARGIN == 0 || prevFree);
}
calculatedOffset += subAlloc.size;
prevFree = currFree;
}
// Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
// match expected one.
D3D12MA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);
UINT64 lastSize = 0;
for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
{
SuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
// Only free suballocations can be registered in m_FreeSuballocationsBySize.
D3D12MA_VALIDATE(suballocItem->type == SUBALLOCATION_TYPE_FREE);
// They must be sorted by size ascending.
D3D12MA_VALIDATE(suballocItem->size >= lastSize);
lastSize = suballocItem->size;
}
// Check if totals match calculacted values.
D3D12MA_VALIDATE(ValidateFreeSuballocationList());
D3D12MA_VALIDATE(calculatedOffset == GetSize());
D3D12MA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);
D3D12MA_VALIDATE(calculatedFreeCount == m_FreeCount);
return true;
}
UINT64 BlockMetadata_Generic::GetUnusedRangeSizeMax() const
{
if(!m_FreeSuballocationsBySize.empty())
{
return m_FreeSuballocationsBySize.back()->size;
}
else
{
return 0;
}
}
bool BlockMetadata_Generic::IsEmpty() const
{
return (m_Suballocations.size() == 1) && (m_FreeCount == 1);
}
void BlockMetadata_Generic::GetAllocationInfo(UINT64 offset, VIRTUAL_ALLOCATION_INFO& outInfo) const
{
for(SuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const Suballocation& suballoc = *suballocItem;
if(suballoc.offset == offset)
{
outInfo.size = suballoc.size;
outInfo.pUserData = suballoc.userData;
return;
}
}
D3D12MA_ASSERT(0 && "Not found!");
}
bool BlockMetadata_Generic::CreateAllocationRequest(
UINT64 allocSize,
UINT64 allocAlignment,
AllocationRequest* pAllocationRequest)
{
D3D12MA_ASSERT(allocSize > 0);
D3D12MA_ASSERT(pAllocationRequest != NULL);
D3D12MA_HEAVY_ASSERT(Validate());
// There is not enough total free space in this block to fullfill the request: Early return.
if(m_SumFreeSize < allocSize + 2 * D3D12MA_DEBUG_MARGIN)
{
return false;
}
// New algorithm, efficiently searching freeSuballocationsBySize.
const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
if(freeSuballocCount > 0)
{
// Find first free suballocation with size not less than allocSize + 2 * D3D12MA_DEBUG_MARGIN.
SuballocationList::iterator* const it = BinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + freeSuballocCount,
allocSize + 2 * D3D12MA_DEBUG_MARGIN,
SuballocationItemSizeLess());
size_t index = it - m_FreeSuballocationsBySize.data();
for(; index < freeSuballocCount; ++index)
{
if(CheckAllocation(
allocSize,
allocAlignment,
m_FreeSuballocationsBySize[index],
&pAllocationRequest->offset,
&pAllocationRequest->sumFreeSize,
&pAllocationRequest->sumItemSize,
&pAllocationRequest->zeroInitialized))
{
pAllocationRequest->item = m_FreeSuballocationsBySize[index];
return true;
}
}
}
return false;
}
void BlockMetadata_Generic::Alloc(
const AllocationRequest& request,
UINT64 allocSize,
void* userData)
{
D3D12MA_ASSERT(request.item != m_Suballocations.end());
Suballocation& suballoc = *request.item;
// Given suballocation is a free block.
D3D12MA_ASSERT(suballoc.type == SUBALLOCATION_TYPE_FREE);
// Given offset is inside this suballocation.
D3D12MA_ASSERT(request.offset >= suballoc.offset);
const UINT64 paddingBegin = request.offset - suballoc.offset;
D3D12MA_ASSERT(suballoc.size >= paddingBegin + allocSize);
const UINT64 paddingEnd = suballoc.size - paddingBegin - allocSize;
// Unregister this free suballocation from m_FreeSuballocationsBySize and update
// it to become used.
UnregisterFreeSuballocation(request.item);
suballoc.offset = request.offset;
suballoc.size = allocSize;
suballoc.type = SUBALLOCATION_TYPE_ALLOCATION;
suballoc.userData = userData;
// If there are any free bytes remaining at the end, insert new free suballocation after current one.
if(paddingEnd)
{
Suballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset + allocSize;
paddingSuballoc.size = paddingEnd;
paddingSuballoc.type = SUBALLOCATION_TYPE_FREE;
SuballocationList::iterator next = request.item;
++next;
const SuballocationList::iterator paddingEndItem =
m_Suballocations.insert(next, paddingSuballoc);
RegisterFreeSuballocation(paddingEndItem);
}
// If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
if(paddingBegin)
{
Suballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset - paddingBegin;
paddingSuballoc.size = paddingBegin;
paddingSuballoc.type = SUBALLOCATION_TYPE_FREE;
const SuballocationList::iterator paddingBeginItem =
m_Suballocations.insert(request.item, paddingSuballoc);
RegisterFreeSuballocation(paddingBeginItem);
}
// Update totals.
m_FreeCount = m_FreeCount - 1;
if(paddingBegin > 0)
{
++m_FreeCount;
}
if(paddingEnd > 0)
{
++m_FreeCount;
}
m_SumFreeSize -= allocSize;
m_ZeroInitializedRange.MarkRangeAsUsed(request.offset, request.offset + allocSize);
}
void BlockMetadata_Generic::FreeAtOffset(UINT64 offset)
{
for(SuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
Suballocation& suballoc = *suballocItem;
if(suballoc.offset == offset)
{
FreeSuballocation(suballocItem);
return;
}
}
D3D12MA_ASSERT(0 && "Not found!");
}
void BlockMetadata_Generic::Clear()
{
m_FreeCount = 1;
m_SumFreeSize = GetSize();
m_Suballocations.clear();
Suballocation suballoc = {};
suballoc.offset = 0;
suballoc.size = GetSize();
suballoc.type = SUBALLOCATION_TYPE_FREE;
m_Suballocations.push_back(suballoc);
m_FreeSuballocationsBySize.clear();
m_FreeSuballocationsBySize.push_back(m_Suballocations.begin());
}
bool BlockMetadata_Generic::ValidateFreeSuballocationList() const
{
UINT64 lastSize = 0;
for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
{
const SuballocationList::iterator it = m_FreeSuballocationsBySize[i];
D3D12MA_VALIDATE(it->type == SUBALLOCATION_TYPE_FREE);
D3D12MA_VALIDATE(it->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
D3D12MA_VALIDATE(it->size >= lastSize);
lastSize = it->size;
}
return true;
}
bool BlockMetadata_Generic::CheckAllocation(
UINT64 allocSize,
UINT64 allocAlignment,
SuballocationList::const_iterator suballocItem,
UINT64* pOffset,
UINT64* pSumFreeSize,
UINT64* pSumItemSize,
BOOL *pZeroInitialized) const
{
D3D12MA_ASSERT(allocSize > 0);
D3D12MA_ASSERT(suballocItem != m_Suballocations.cend());
D3D12MA_ASSERT(pOffset != NULL && pZeroInitialized != NULL);
*pSumFreeSize = 0;
*pSumItemSize = 0;
*pZeroInitialized = FALSE;
const Suballocation& suballoc = *suballocItem;
D3D12MA_ASSERT(suballoc.type == SUBALLOCATION_TYPE_FREE);
*pSumFreeSize = suballoc.size;
// Size of this suballocation is too small for this request: Early return.
if(suballoc.size < allocSize)
{
return false;
}
// Start from offset equal to beginning of this suballocation.
*pOffset = suballoc.offset;
// Apply D3D12MA_DEBUG_MARGIN at the beginning.
if(D3D12MA_DEBUG_MARGIN > 0)
{
*pOffset += D3D12MA_DEBUG_MARGIN;
}
// Apply alignment.
*pOffset = AlignUp(*pOffset, allocAlignment);
// Calculate padding at the beginning based on current offset.
const UINT64 paddingBegin = *pOffset - suballoc.offset;
// Calculate required margin at the end.
const UINT64 requiredEndMargin = D3D12MA_DEBUG_MARGIN;
// Fail if requested size plus margin before and after is bigger than size of this suballocation.
if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)
{
return false;
}
// All tests passed: Success. pOffset is already filled.
*pZeroInitialized = m_ZeroInitializedRange.IsRangeZeroInitialized(*pOffset, *pOffset + allocSize);
return true;
}
void BlockMetadata_Generic::MergeFreeWithNext(SuballocationList::iterator item)
{
D3D12MA_ASSERT(item != m_Suballocations.end());
D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);
SuballocationList::iterator nextItem = item;
++nextItem;
D3D12MA_ASSERT(nextItem != m_Suballocations.end());
D3D12MA_ASSERT(nextItem->type == SUBALLOCATION_TYPE_FREE);
item->size += nextItem->size;
--m_FreeCount;
m_Suballocations.erase(nextItem);
}
SuballocationList::iterator BlockMetadata_Generic::FreeSuballocation(SuballocationList::iterator suballocItem)
{
// Change this suballocation to be marked as free.
Suballocation& suballoc = *suballocItem;
suballoc.type = SUBALLOCATION_TYPE_FREE;
suballoc.userData = NULL;
// Update totals.
++m_FreeCount;
m_SumFreeSize += suballoc.size;
// Merge with previous and/or next suballocation if it's also free.
bool mergeWithNext = false;
bool mergeWithPrev = false;
SuballocationList::iterator nextItem = suballocItem;
++nextItem;
if((nextItem != m_Suballocations.end()) && (nextItem->type == SUBALLOCATION_TYPE_FREE))
{
mergeWithNext = true;
}
SuballocationList::iterator prevItem = suballocItem;
if(suballocItem != m_Suballocations.begin())
{
--prevItem;
if(prevItem->type == SUBALLOCATION_TYPE_FREE)
{
mergeWithPrev = true;
}
}
if(mergeWithNext)
{
UnregisterFreeSuballocation(nextItem);
MergeFreeWithNext(suballocItem);
}
if(mergeWithPrev)
{
UnregisterFreeSuballocation(prevItem);
MergeFreeWithNext(prevItem);
RegisterFreeSuballocation(prevItem);
return prevItem;
}
else
{
RegisterFreeSuballocation(suballocItem);
return suballocItem;
}
}
void BlockMetadata_Generic::RegisterFreeSuballocation(SuballocationList::iterator item)
{
D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);
D3D12MA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
if(m_FreeSuballocationsBySize.empty())
{
m_FreeSuballocationsBySize.push_back(item);
}
else
{
m_FreeSuballocationsBySize.InsertSorted(item, SuballocationItemSizeLess());
}
}
//D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
void BlockMetadata_Generic::UnregisterFreeSuballocation(SuballocationList::iterator item)
{
D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);
D3D12MA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
SuballocationList::iterator* const it = BinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
item,
SuballocationItemSizeLess());
for(size_t index = it - m_FreeSuballocationsBySize.data();
index < m_FreeSuballocationsBySize.size();
++index)
{
if(m_FreeSuballocationsBySize[index] == item)
{
m_FreeSuballocationsBySize.remove(index);
return;
}
D3D12MA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
}
D3D12MA_ASSERT(0 && "Not found.");
}
//D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
void BlockMetadata_Generic::SetAllocationUserData(UINT64 offset, void* userData)
{
for(SuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
Suballocation& suballoc = *suballocItem;
if(suballoc.offset == offset)
{
suballoc.userData = userData;
return;
}
}
D3D12MA_ASSERT(0 && "Not found!");
}
void BlockMetadata_Generic::CalcAllocationStatInfo(StatInfo& outInfo) const
{
outInfo.BlockCount = 1;
const UINT rangeCount = (UINT)m_Suballocations.size();
outInfo.AllocationCount = rangeCount - m_FreeCount;
outInfo.UnusedRangeCount = m_FreeCount;
outInfo.UsedBytes = GetSize() - m_SumFreeSize;
outInfo.UnusedBytes = m_SumFreeSize;
outInfo.AllocationSizeMin = UINT64_MAX;
outInfo.AllocationSizeMax = 0;
outInfo.UnusedRangeSizeMin = UINT64_MAX;
outInfo.UnusedRangeSizeMax = 0;
for(SuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const Suballocation& suballoc = *suballocItem;
if(suballoc.type == SUBALLOCATION_TYPE_FREE)
{
outInfo.UnusedRangeSizeMin = D3D12MA_MIN(suballoc.size, outInfo.UnusedRangeSizeMin);
outInfo.UnusedRangeSizeMax = D3D12MA_MAX(suballoc.size, outInfo.UnusedRangeSizeMax);
}
else
{
outInfo.AllocationSizeMin = D3D12MA_MIN(suballoc.size, outInfo.AllocationSizeMin);
outInfo.AllocationSizeMax = D3D12MA_MAX(suballoc.size, outInfo.AllocationSizeMax);
}
}
}
void BlockMetadata_Generic::WriteAllocationInfoToJson(JsonWriter& json) const
{
json.BeginObject();
json.WriteString(L"TotalBytes");
json.WriteNumber(GetSize());
json.WriteString(L"UnusuedBytes");
json.WriteNumber(GetSumFreeSize());
json.WriteString(L"Allocations");
json.WriteNumber(GetAllocationCount());
json.WriteString(L"UnusedRanges");
json.WriteNumber(m_FreeCount);
json.WriteString(L"Suballocations");
json.BeginArray();
for(SuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const Suballocation& suballoc = *suballocItem;
json.BeginObject(true);
json.WriteString(L"Offset");
json.WriteNumber(suballoc.offset);
if(suballoc.type == SUBALLOCATION_TYPE_FREE)
{
json.WriteString(L"Type");
json.WriteString(L"FREE");
json.WriteString(L"Size");
json.WriteNumber(suballoc.size);
}
else if(IsVirtual())
{
json.WriteString(L"Type");
json.WriteString(L"ALLOCATION");
json.WriteString(L"Size");
json.WriteNumber(suballoc.size);
if(suballoc.userData)
{
json.WriteString(L"UserData");
json.WriteNumber((uintptr_t)suballoc.userData);
}
}
else
{
const Allocation* const alloc = (const Allocation*)suballoc.userData;
D3D12MA_ASSERT(alloc);
json.AddAllocationToObject(*alloc);
}
json.EndObject();
}
json.EndArray();
json.EndObject();
}
////////////////////////////////////////////////////////////////////////////////
// Private class NormalBlock implementation
NormalBlock::NormalBlock(
AllocatorPimpl* allocator,
BlockVector* blockVector,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 size,
UINT id) :
MemoryBlock(allocator, heapType, heapFlags, size, id),
m_pMetadata(NULL),
m_BlockVector(blockVector)
{
}
NormalBlock::~NormalBlock()
{
if(m_pMetadata != NULL)
{
// THIS IS THE MOST IMPORTANT ASSERT IN THE ENTIRE LIBRARY!
// Hitting it means you have some memory leak - unreleased Allocation objects.
D3D12MA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
D3D12MA_DELETE(m_Allocator->GetAllocs(), m_pMetadata);
}
}
HRESULT NormalBlock::Init()
{
HRESULT hr = MemoryBlock::Init();
if(FAILED(hr))
{
return hr;
}
m_pMetadata = D3D12MA_NEW(m_Allocator->GetAllocs(), BlockMetadata_Generic)(&m_Allocator->GetAllocs(), false);
m_pMetadata->Init(m_Size);
return hr;
}
bool NormalBlock::Validate() const
{
D3D12MA_VALIDATE(GetHeap() &&
m_pMetadata &&
m_pMetadata->GetSize() != 0 &&
m_pMetadata->GetSize() == GetSize());
return m_pMetadata->Validate();
}
////////////////////////////////////////////////////////////////////////////////
// Private class MemoryBlock definition
MemoryBlock::MemoryBlock(
AllocatorPimpl* allocator,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 size,
UINT id) :
m_Allocator(allocator),
m_HeapType(heapType),
m_HeapFlags(heapFlags),
m_Size(size),
m_Id(id)
{
}
MemoryBlock::~MemoryBlock()
{
if(m_Heap)
{
m_Allocator->m_Budget.m_BlockBytes[HeapTypeToIndex(m_HeapType)] -= m_Size;
m_Heap->Release();
}
}
HRESULT MemoryBlock::Init()
{
D3D12MA_ASSERT(m_Heap == NULL && m_Size > 0);
D3D12_HEAP_DESC heapDesc = {};
heapDesc.SizeInBytes = m_Size;
heapDesc.Properties.Type = m_HeapType;
heapDesc.Alignment = HeapFlagsToAlignment(m_HeapFlags);
heapDesc.Flags = m_HeapFlags;
HRESULT hr = m_Allocator->GetDevice()->CreateHeap(&heapDesc, __uuidof(*m_Heap), (void**)&m_Heap);
if(SUCCEEDED(hr))
{
m_Allocator->m_Budget.m_BlockBytes[HeapTypeToIndex(m_HeapType)] += m_Size;
}
return hr;
}
////////////////////////////////////////////////////////////////////////////////
// Private class BlockVector implementation
BlockVector::BlockVector(
AllocatorPimpl* hAllocator,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
bool explicitBlockSize) :
m_hAllocator(hAllocator),
m_HeapType(heapType),
m_HeapFlags(heapFlags),
m_PreferredBlockSize(preferredBlockSize),
m_MinBlockCount(minBlockCount),
m_MaxBlockCount(maxBlockCount),
m_ExplicitBlockSize(explicitBlockSize),
m_MinBytes(0),
m_HasEmptyBlock(false),
m_Blocks(hAllocator->GetAllocs()),
m_NextBlockId(0)
{
}
BlockVector::~BlockVector()
{
for(size_t i = m_Blocks.size(); i--; )
{
D3D12MA_DELETE(m_hAllocator->GetAllocs(), m_Blocks[i]);
}
}
HRESULT BlockVector::CreateMinBlocks()
{
for(size_t i = 0; i < m_MinBlockCount; ++i)
{
HRESULT hr = CreateBlock(m_PreferredBlockSize, NULL);
if(FAILED(hr))
{
return hr;
}
}
return S_OK;
}
bool BlockVector::IsEmpty()
{
MutexLockRead lock(m_Mutex, m_hAllocator->UseMutex());
return m_Blocks.empty();
}
HRESULT BlockVector::Allocate(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
size_t allocationCount,
Allocation** pAllocations)
{
size_t allocIndex;
HRESULT hr = S_OK;
{
MutexLockWrite lock(m_Mutex, m_hAllocator->UseMutex());
for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
{
hr = AllocatePage(
size,
alignment,
allocDesc,
pAllocations + allocIndex);
if(FAILED(hr))
{
break;
}
}
}
if(FAILED(hr))
{
// Free all already created allocations.
while(allocIndex--)
{
Free(pAllocations[allocIndex]);
}
ZeroMemory(pAllocations, sizeof(Allocation*) * allocationCount);
}
return hr;
}
HRESULT BlockVector::AllocatePage(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
Allocation** pAllocation)
{
// Early reject: requested allocation size is larger that maximum block size for this block vector.
if(size + 2 * D3D12MA_DEBUG_MARGIN > m_PreferredBlockSize)
{
return E_OUTOFMEMORY;
}
UINT64 freeMemory;
{
Budget budget = {};
m_hAllocator->GetBudgetForHeapType(budget, m_HeapType);
freeMemory = (budget.UsageBytes < budget.BudgetBytes) ? (budget.BudgetBytes - budget.UsageBytes) : 0;
}
const bool canCreateNewBlock =
((allocDesc.Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) == 0) &&
(m_Blocks.size() < m_MaxBlockCount) &&
// Even if we don't have to stay within budget with this allocation, when the
// budget would be exceeded, we don't want to allocate new blocks, but always
// create resources as committed.
freeMemory >= size;
// 1. Search existing allocations
{
// Forward order in m_Blocks - prefer blocks with smallest amount of free space.
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
{
NormalBlock* const pCurrBlock = m_Blocks[blockIndex];
D3D12MA_ASSERT(pCurrBlock);
HRESULT hr = AllocateFromBlock(
pCurrBlock,
size,
alignment,
allocDesc.Flags,
pAllocation);
if(SUCCEEDED(hr))
{
return hr;
}
}
}
// 2. Try to create new block.
if(canCreateNewBlock)
{
// Calculate optimal size for new block.
UINT64 newBlockSize = m_PreferredBlockSize;
UINT newBlockSizeShift = 0;
if(!m_ExplicitBlockSize)
{
// Allocate 1/8, 1/4, 1/2 as first blocks.
const UINT64 maxExistingBlockSize = CalcMaxBlockSize();
for(UINT i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
{
const UINT64 smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
}
else
{
break;
}
}
}
size_t newBlockIndex = 0;
HRESULT hr = newBlockSize <= freeMemory ?
CreateBlock(newBlockSize, &newBlockIndex) : E_OUTOFMEMORY;
// Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
if(!m_ExplicitBlockSize)
{
while(FAILED(hr) && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
{
const UINT64 smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize >= size)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
hr = newBlockSize <= freeMemory ?
CreateBlock(newBlockSize, &newBlockIndex) : E_OUTOFMEMORY;
}
else
{
break;
}
}
}
if(SUCCEEDED(hr))
{
NormalBlock* const pBlock = m_Blocks[newBlockIndex];
D3D12MA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
hr = AllocateFromBlock(
pBlock,
size,
alignment,
allocDesc.Flags,
pAllocation);
if(SUCCEEDED(hr))
{
return hr;
}
else
{
// Allocation from new block failed, possibly due to D3D12MA_DEBUG_MARGIN or alignment.
return E_OUTOFMEMORY;
}
}
}
return E_OUTOFMEMORY;
}
void BlockVector::Free(Allocation* hAllocation)
{
NormalBlock* pBlockToDelete = NULL;
bool budgetExceeded = false;
{
Budget budget = {};
m_hAllocator->GetBudgetForHeapType(budget, m_HeapType);
budgetExceeded = budget.UsageBytes >= budget.BudgetBytes;
}
// Scope for lock.
{
MutexLockWrite lock(m_Mutex, m_hAllocator->UseMutex());
NormalBlock* pBlock = hAllocation->m_Placed.block;
pBlock->m_pMetadata->FreeAtOffset(hAllocation->GetOffset());
D3D12MA_HEAVY_ASSERT(pBlock->Validate());
const size_t blockCount = m_Blocks.size();
const UINT64 sumBlockSize = CalcSumBlockSize();
// pBlock became empty after this deallocation.
if(pBlock->m_pMetadata->IsEmpty())
{
// Already has empty Allocation. We don't want to have two, so delete this one.
if((m_HasEmptyBlock || budgetExceeded) &&
blockCount > m_MinBlockCount &&
sumBlockSize - pBlock->m_pMetadata->GetSize() >= m_MinBytes)
{
pBlockToDelete = pBlock;
Remove(pBlock);
}
// We now have first empty block.
else
{
m_HasEmptyBlock = true;
}
}
// pBlock didn't become empty, but we have another empty block - find and free that one.
// (This is optional, heuristics.)
else if(m_HasEmptyBlock && blockCount > m_MinBlockCount)
{
NormalBlock* pLastBlock = m_Blocks.back();
if(pLastBlock->m_pMetadata->IsEmpty() &&
sumBlockSize - pLastBlock->m_pMetadata->GetSize() >= m_MinBytes)
{
pBlockToDelete = pLastBlock;
m_Blocks.pop_back();
m_HasEmptyBlock = false;
}
}
IncrementallySortBlocks();
}
// Destruction of a free Allocation. Deferred until this point, outside of mutex
// lock, for performance reason.
if(pBlockToDelete != NULL)
{
D3D12MA_DELETE(m_hAllocator->GetAllocs(), pBlockToDelete);
}
}
HRESULT BlockVector::CreateResource(
UINT64 size,
UINT64 alignment,
const ALLOCATION_DESC& allocDesc,
const D3D12_RESOURCE_DESC& resourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource)
{
HRESULT hr = Allocate(size, alignment, allocDesc, 1, ppAllocation);
if(SUCCEEDED(hr))
{
ID3D12Resource* res = NULL;
hr = m_hAllocator->GetDevice()->CreatePlacedResource(
(*ppAllocation)->m_Placed.block->GetHeap(),
(*ppAllocation)->GetOffset(),
&resourceDesc,
InitialResourceState,
pOptimizedClearValue,
IID_PPV_ARGS(&res));
if(SUCCEEDED(hr))
{
if(ppvResource != NULL)
{
hr = res->QueryInterface(riidResource, ppvResource);
}
if(SUCCEEDED(hr))
{
(*ppAllocation)->SetResource(res, &resourceDesc);
}
else
{
res->Release();
SAFE_RELEASE(*ppAllocation);
}
}
else
{
SAFE_RELEASE(*ppAllocation);
}
}
return hr;
}
UINT64 BlockVector::CalcSumBlockSize() const
{
UINT64 result = 0;
for(size_t i = m_Blocks.size(); i--; )
{
result += m_Blocks[i]->m_pMetadata->GetSize();
}
return result;
}
UINT64 BlockVector::CalcMaxBlockSize() const
{
UINT64 result = 0;
for(size_t i = m_Blocks.size(); i--; )
{
result = D3D12MA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
if(result >= m_PreferredBlockSize)
{
break;
}
}
return result;
}
void BlockVector::Remove(NormalBlock* pBlock)
{
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
if(m_Blocks[blockIndex] == pBlock)
{
m_Blocks.remove(blockIndex);
return;
}
}
D3D12MA_ASSERT(0);
}
void BlockVector::IncrementallySortBlocks()
{
// Bubble sort only until first swap.
for(size_t i = 1; i < m_Blocks.size(); ++i)
{
if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
{
D3D12MA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
return;
}
}
}
HRESULT BlockVector::AllocateFromBlock(
NormalBlock* pBlock,
UINT64 size,
UINT64 alignment,
ALLOCATION_FLAGS allocFlags,
Allocation** pAllocation)
{
AllocationRequest currRequest = {};
if(pBlock->m_pMetadata->CreateAllocationRequest(
size,
alignment,
&currRequest))
{
// We no longer have an empty Allocation.
if(pBlock->m_pMetadata->IsEmpty())
{
m_HasEmptyBlock = false;
}
*pAllocation = m_hAllocator->GetAllocationObjectAllocator().Allocate(m_hAllocator, size, currRequest.zeroInitialized);
pBlock->m_pMetadata->Alloc(currRequest, size, *pAllocation);
(*pAllocation)->InitPlaced(currRequest.offset, alignment, pBlock);
D3D12MA_HEAVY_ASSERT(pBlock->Validate());
m_hAllocator->m_Budget.AddAllocation(HeapTypeToIndex(m_HeapType), size);
return S_OK;
}
return E_OUTOFMEMORY;
}
HRESULT BlockVector::CreateBlock(UINT64 blockSize, size_t* pNewBlockIndex)
{
NormalBlock* const pBlock = D3D12MA_NEW(m_hAllocator->GetAllocs(), NormalBlock)(
m_hAllocator,
this,
m_HeapType,
m_HeapFlags,
blockSize,
m_NextBlockId++);
HRESULT hr = pBlock->Init();
if(FAILED(hr))
{
D3D12MA_DELETE(m_hAllocator->GetAllocs(), pBlock);
return hr;
}
m_Blocks.push_back(pBlock);
if(pNewBlockIndex != NULL)
{
*pNewBlockIndex = m_Blocks.size() - 1;
}
return hr;
}
HRESULT BlockVector::SetMinBytes(UINT64 minBytes)
{
MutexLockWrite lock(m_Mutex, m_hAllocator->UseMutex());
if(minBytes == m_MinBytes)
{
return S_OK;
}
HRESULT hr = S_OK;
UINT64 sumBlockSize = CalcSumBlockSize();
size_t blockCount = m_Blocks.size();
// New minBytes is smaller - may be able to free some blocks.
if(minBytes < m_MinBytes)
{
m_HasEmptyBlock = false; // Will recalculate this value from scratch.
for(size_t blockIndex = blockCount; blockIndex--; )
{
NormalBlock* const block = m_Blocks[blockIndex];
const UINT64 size = block->m_pMetadata->GetSize();
const bool isEmpty = block->m_pMetadata->IsEmpty();
if(isEmpty &&
sumBlockSize - size >= minBytes &&
blockCount - 1 >= m_MinBlockCount)
{
D3D12MA_DELETE(m_hAllocator->GetAllocs(), block);
m_Blocks.remove(blockIndex);
sumBlockSize -= size;
--blockCount;
}
else
{
if(isEmpty)
{
m_HasEmptyBlock = true;
}
}
}
}
// New minBytes is larger - may need to allocate some blocks.
else
{
const UINT64 minBlockSize = m_PreferredBlockSize >> NEW_BLOCK_SIZE_SHIFT_MAX;
while(SUCCEEDED(hr) && sumBlockSize < minBytes)
{
if(blockCount < m_MaxBlockCount)
{
UINT64 newBlockSize = m_PreferredBlockSize;
if(!m_ExplicitBlockSize)
{
if(sumBlockSize + newBlockSize > minBytes)
{
newBlockSize = minBytes - sumBlockSize;
}
// Next one would be the last block to create and its size would be smaller than
// the smallest block size we want to use here, so make this one smaller.
else if(blockCount + 1 < m_MaxBlockCount &&
sumBlockSize + newBlockSize + minBlockSize > minBytes)
{
newBlockSize -= minBlockSize + sumBlockSize + m_PreferredBlockSize - minBytes;
}
}
hr = CreateBlock(newBlockSize, NULL);
if(SUCCEEDED(hr))
{
m_HasEmptyBlock = true;
sumBlockSize += newBlockSize;
++blockCount;
}
}
else
{
hr = E_INVALIDARG;
}
}
}
m_MinBytes = minBytes;
return hr;
}
void BlockVector::AddStats(StatInfo& outStats)
{
MutexLockRead lock(m_Mutex, m_hAllocator->UseMutex());
for(size_t i = 0; i < m_Blocks.size(); ++i)
{
const NormalBlock* const pBlock = m_Blocks[i];
D3D12MA_ASSERT(pBlock);
D3D12MA_HEAVY_ASSERT(pBlock->Validate());
StatInfo blockStatInfo;
pBlock->m_pMetadata->CalcAllocationStatInfo(blockStatInfo);
AddStatInfo(outStats, blockStatInfo);
}
}
void BlockVector::AddStats(Stats& outStats)
{
const UINT heapTypeIndex = HeapTypeToIndex(m_HeapType);
StatInfo* const pStatInfo = &outStats.HeapType[heapTypeIndex];
MutexLockRead lock(m_Mutex, m_hAllocator->UseMutex());
for(size_t i = 0; i < m_Blocks.size(); ++i)
{
const NormalBlock* const pBlock = m_Blocks[i];
D3D12MA_ASSERT(pBlock);
D3D12MA_HEAVY_ASSERT(pBlock->Validate());
StatInfo blockStatInfo;
pBlock->m_pMetadata->CalcAllocationStatInfo(blockStatInfo);
AddStatInfo(outStats.Total, blockStatInfo);
AddStatInfo(*pStatInfo, blockStatInfo);
}
}
void BlockVector::WriteBlockInfoToJson(JsonWriter& json)
{
MutexLockRead lock(m_Mutex, m_hAllocator->UseMutex());
json.BeginObject();
for (size_t i = 0, count = m_Blocks.size(); i < count; ++i)
{
const NormalBlock* const pBlock = m_Blocks[i];
D3D12MA_ASSERT(pBlock);
D3D12MA_HEAVY_ASSERT(pBlock->Validate());
json.BeginString();
json.ContinueString(pBlock->GetId());
json.EndString();
pBlock->m_pMetadata->WriteAllocationInfoToJson(json);
}
json.EndObject();
}
////////////////////////////////////////////////////////////////////////////////
// Private class PoolPimpl
class PoolPimpl
{
public:
PoolPimpl(AllocatorPimpl* allocator, const POOL_DESC& desc);
HRESULT Init();
~PoolPimpl();
AllocatorPimpl* GetAllocator() const { return m_Allocator; }
const POOL_DESC& GetDesc() const { return m_Desc; }
BlockVector* GetBlockVector() { return m_BlockVector; }
HRESULT SetMinBytes(UINT64 minBytes) { return m_BlockVector->SetMinBytes(minBytes); }
void CalculateStats(StatInfo& outStats);
void SetName(LPCWSTR Name);
LPCWSTR GetName() const { return m_Name; }
private:
friend class Allocator;
AllocatorPimpl* m_Allocator; // Externally owned object.
POOL_DESC m_Desc;
BlockVector* m_BlockVector; // Owned object.
wchar_t* m_Name;
void FreeName();
};
PoolPimpl::PoolPimpl(AllocatorPimpl* allocator, const POOL_DESC& desc) :
m_Allocator(allocator),
m_Desc(desc),
m_BlockVector(NULL),
m_Name(NULL)
{
const bool explicitBlockSize = desc.BlockSize != 0;
const UINT64 preferredBlockSize = explicitBlockSize ? desc.BlockSize : D3D12MA_DEFAULT_BLOCK_SIZE;
D3D12_HEAP_FLAGS heapFlags = desc.HeapFlags;
UINT maxBlockCount = desc.MaxBlockCount != 0 ? desc.MaxBlockCount : UINT_MAX;
m_BlockVector = D3D12MA_NEW(allocator->GetAllocs(), BlockVector)(
allocator, desc.HeapType, heapFlags,
preferredBlockSize,
desc.MinBlockCount, maxBlockCount,
explicitBlockSize);
}
HRESULT PoolPimpl::Init()
{
return m_BlockVector->CreateMinBlocks();
}
PoolPimpl::~PoolPimpl()
{
FreeName();
D3D12MA_DELETE(m_Allocator->GetAllocs(), m_BlockVector);
}
void PoolPimpl::CalculateStats(StatInfo& outStats)
{
ZeroMemory(&outStats, sizeof(outStats));
outStats.AllocationSizeMin = UINT64_MAX;
outStats.UnusedRangeSizeMin = UINT64_MAX;
m_BlockVector->AddStats(outStats);
PostProcessStatInfo(outStats);
}
void PoolPimpl::SetName(LPCWSTR Name)
{
FreeName();
if(Name)
{
const size_t nameCharCount = wcslen(Name) + 1;
m_Name = D3D12MA_NEW_ARRAY(m_Allocator->GetAllocs(), WCHAR, nameCharCount);
memcpy(m_Name, Name, nameCharCount * sizeof(WCHAR));
}
}
void PoolPimpl::FreeName()
{
if(m_Name)
{
const size_t nameCharCount = wcslen(m_Name) + 1;
D3D12MA_DELETE_ARRAY(m_Allocator->GetAllocs(), m_Name, nameCharCount);
m_Name = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////
// Public class Pool implementation
void Pool::Release()
{
if(this == NULL)
{
return;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
D3D12MA_DELETE(m_Pimpl->GetAllocator()->GetAllocs(), this);
}
POOL_DESC Pool::GetDesc() const
{
return m_Pimpl->GetDesc();
}
HRESULT Pool::SetMinBytes(UINT64 minBytes)
{
return m_Pimpl->SetMinBytes(minBytes);
}
void Pool::CalculateStats(StatInfo* pStats)
{
D3D12MA_ASSERT(pStats);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->CalculateStats(*pStats);
}
void Pool::SetName(LPCWSTR Name)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->SetName(Name);
}
LPCWSTR Pool::GetName() const
{
return m_Pimpl->GetName();
}
Pool::Pool(Allocator* allocator, const POOL_DESC &desc) :
m_Pimpl(D3D12MA_NEW(allocator->m_Pimpl->GetAllocs(), PoolPimpl)(allocator->m_Pimpl, desc))
{
}
Pool::~Pool()
{
m_Pimpl->GetAllocator()->UnregisterPool(this, m_Pimpl->GetDesc().HeapType);
D3D12MA_DELETE(m_Pimpl->GetAllocator()->GetAllocs(), m_Pimpl);
}
////////////////////////////////////////////////////////////////////////////////
// Private class AllocatorPimpl implementation
AllocatorPimpl::AllocatorPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc) :
m_UseMutex((desc.Flags & ALLOCATOR_FLAG_SINGLETHREADED) == 0),
m_AlwaysCommitted((desc.Flags & ALLOCATOR_FLAG_ALWAYS_COMMITTED) != 0),
m_Device(desc.pDevice),
m_Adapter(desc.pAdapter),
#if D3D12MA_DXGI_1_4
m_Adapter3(NULL),
#endif
m_PreferredBlockSize(desc.PreferredBlockSize != 0 ? desc.PreferredBlockSize : D3D12MA_DEFAULT_BLOCK_SIZE),
m_AllocationCallbacks(allocationCallbacks),
m_CurrentFrameIndex(0),
// Below this line don't use allocationCallbacks but m_AllocationCallbacks!!!
m_AllocationObjectAllocator(m_AllocationCallbacks)
{
// desc.pAllocationCallbacks intentionally ignored here, preprocessed by CreateAllocator.
ZeroMemory(&m_D3D12Options, sizeof(m_D3D12Options));
ZeroMemory(m_pCommittedAllocations, sizeof(m_pCommittedAllocations));
ZeroMemory(m_pPools, sizeof(m_pPools));
ZeroMemory(m_BlockVectors, sizeof(m_BlockVectors));
ZeroMemory(m_DefaultPoolTier1MinBytes, sizeof(m_DefaultPoolTier1MinBytes));
for(UINT i = 0; i < HEAP_TYPE_COUNT; ++i)
{
m_DefaultPoolHeapTypeMinBytes[i] = UINT64_MAX;
}
for(UINT heapTypeIndex = 0; heapTypeIndex < HEAP_TYPE_COUNT; ++heapTypeIndex)
{
m_pCommittedAllocations[heapTypeIndex] = D3D12MA_NEW(GetAllocs(), AllocationVectorType)(GetAllocs());
m_pPools[heapTypeIndex] = D3D12MA_NEW(GetAllocs(), PoolVectorType)(GetAllocs());
}
m_Device->AddRef();
m_Adapter->AddRef();
}
HRESULT AllocatorPimpl::Init(const ALLOCATOR_DESC& desc)
{
#if D3D12MA_DXGI_1_4
desc.pAdapter->QueryInterface<IDXGIAdapter3>(&m_Adapter3);
#endif
HRESULT hr = m_Adapter->GetDesc(&m_AdapterDesc);
if(FAILED(hr))
{
return hr;
}
hr = m_Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &m_D3D12Options, sizeof(m_D3D12Options));
if(FAILED(hr))
{
return hr;
}
const UINT defaultPoolCount = CalcDefaultPoolCount();
for(UINT i = 0; i < defaultPoolCount; ++i)
{
D3D12_HEAP_TYPE heapType;
D3D12_HEAP_FLAGS heapFlags;
CalcDefaultPoolParams(heapType, heapFlags, i);
m_BlockVectors[i] = D3D12MA_NEW(GetAllocs(), BlockVector)(
this, // hAllocator
heapType, // heapType
heapFlags, // heapFlags
m_PreferredBlockSize,
0, // minBlockCount
SIZE_MAX, // maxBlockCount
false); // explicitBlockSize
// No need to call m_pBlockVectors[i]->CreateMinBlocks here, becase minBlockCount is 0.
}
#if D3D12MA_DXGI_1_4
if(m_Adapter3)
{
UpdateD3D12Budget();
}
#endif
return S_OK;
}
AllocatorPimpl::~AllocatorPimpl()
{
#if D3D12MA_DXGI_1_4
SAFE_RELEASE(m_Adapter3);
#endif
SAFE_RELEASE(m_Adapter);
SAFE_RELEASE(m_Device);
for(UINT i = DEFAULT_POOL_MAX_COUNT; i--; )
{
D3D12MA_DELETE(GetAllocs(), m_BlockVectors[i]);
}
for(UINT i = HEAP_TYPE_COUNT; i--; )
{
if(m_pPools[i] && !m_pPools[i]->empty())
{
D3D12MA_ASSERT(0 && "Unfreed pools found!");
}
D3D12MA_DELETE(GetAllocs(), m_pPools[i]);
}
for(UINT i = HEAP_TYPE_COUNT; i--; )
{
if(m_pCommittedAllocations[i] && !m_pCommittedAllocations[i]->empty())
{
D3D12MA_ASSERT(0 && "Unfreed committed allocations found!");
}
D3D12MA_DELETE(GetAllocs(), m_pCommittedAllocations[i]);
}
}
bool AllocatorPimpl::HeapFlagsFulfillResourceHeapTier(D3D12_HEAP_FLAGS flags) const
{
if(SupportsResourceHeapTier2())
{
return true;
}
else
{
const bool allowBuffers = (flags & D3D12_HEAP_FLAG_DENY_BUFFERS ) == 0;
const bool allowRtDsTextures = (flags & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES ) == 0;
const bool allowNonRtDsTextures = (flags & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES) == 0;
const uint8_t allowedGroupCount = (allowBuffers ? 1 : 0) + (allowRtDsTextures ? 1 : 0) + (allowNonRtDsTextures ? 1 : 0);
return allowedGroupCount == 1;
}
}
HRESULT AllocatorPimpl::CreateResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource)
{
*ppAllocation = NULL;
if(ppvResource)
{
*ppvResource = NULL;
}
if(pAllocDesc->CustomPool == NULL)
{
if(!IsHeapTypeValid(pAllocDesc->HeapType))
{
return E_INVALIDARG;
}
}
ALLOCATION_DESC finalAllocDesc = *pAllocDesc;
D3D12_RESOURCE_DESC finalResourceDesc = *pResourceDesc;
D3D12_RESOURCE_ALLOCATION_INFO resAllocInfo = GetResourceAllocationInfo(finalResourceDesc);
resAllocInfo.Alignment = D3D12MA_MAX<UINT64>(resAllocInfo.Alignment, D3D12MA_DEBUG_ALIGNMENT);
D3D12MA_ASSERT(IsPow2(resAllocInfo.Alignment));
D3D12MA_ASSERT(resAllocInfo.SizeInBytes > 0);
if(pAllocDesc->CustomPool != NULL)
{
if((finalAllocDesc.Flags & ALLOCATION_FLAG_COMMITTED) != 0)
{
return E_INVALIDARG;
}
BlockVector* blockVector = pAllocDesc->CustomPool->m_Pimpl->GetBlockVector();
D3D12MA_ASSERT(blockVector);
return blockVector->CreateResource(
resAllocInfo.SizeInBytes,
resAllocInfo.Alignment,
finalAllocDesc,
finalResourceDesc,
InitialResourceState,
pOptimizedClearValue,
ppAllocation,
riidResource,
ppvResource);
}
else
{
const UINT defaultPoolIndex = CalcDefaultPoolIndex(*pAllocDesc, finalResourceDesc);
const bool requireCommittedMemory = defaultPoolIndex == UINT32_MAX;
if(requireCommittedMemory)
{
return AllocateCommittedResource(
&finalAllocDesc,
&finalResourceDesc,
resAllocInfo,
InitialResourceState,
pOptimizedClearValue,
ppAllocation,
riidResource,
ppvResource);
}
BlockVector* const blockVector = m_BlockVectors[defaultPoolIndex];
D3D12MA_ASSERT(blockVector);
const UINT64 preferredBlockSize = blockVector->GetPreferredBlockSize();
bool preferCommittedMemory =
m_AlwaysCommitted ||
PrefersCommittedAllocation(finalResourceDesc) ||
// Heuristics: Allocate committed memory if requested size if greater than half of preferred block size.
resAllocInfo.SizeInBytes > preferredBlockSize / 2;
if(preferCommittedMemory &&
(finalAllocDesc.Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) == 0)
{
finalAllocDesc.Flags |= ALLOCATION_FLAG_COMMITTED;
}
if((finalAllocDesc.Flags & ALLOCATION_FLAG_COMMITTED) != 0)
{
return AllocateCommittedResource(
&finalAllocDesc,
&finalResourceDesc,
resAllocInfo,
InitialResourceState,
pOptimizedClearValue,
ppAllocation,
riidResource,
ppvResource);
}
else
{
HRESULT hr = blockVector->CreateResource(
resAllocInfo.SizeInBytes,
resAllocInfo.Alignment,
finalAllocDesc,
finalResourceDesc,
InitialResourceState,
pOptimizedClearValue,
ppAllocation,
riidResource,
ppvResource);
if(SUCCEEDED(hr))
{
return hr;
}
return AllocateCommittedResource(
&finalAllocDesc,
&finalResourceDesc,
resAllocInfo,
InitialResourceState,
pOptimizedClearValue,
ppAllocation,
riidResource,
ppvResource);
}
}
}
HRESULT AllocatorPimpl::AllocateMemory(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
Allocation** ppAllocation)
{
*ppAllocation = NULL;
if(pAllocDesc->CustomPool != NULL)
{
BlockVector* const blockVector = pAllocDesc->CustomPool->m_Pimpl->GetBlockVector();
D3D12MA_ASSERT(blockVector);
return blockVector->Allocate(
pAllocInfo->SizeInBytes,
pAllocInfo->Alignment,
*pAllocDesc,
1,
(Allocation**)ppAllocation);
}
else
{
if(!IsHeapTypeValid(pAllocDesc->HeapType))
{
return E_INVALIDARG;
}
ALLOCATION_DESC finalAllocDesc = *pAllocDesc;
const UINT defaultPoolIndex = CalcDefaultPoolIndex(*pAllocDesc);
bool requireCommittedMemory = (defaultPoolIndex == UINT32_MAX);
if(requireCommittedMemory)
{
return AllocateHeap(&finalAllocDesc, *pAllocInfo, ppAllocation);
}
BlockVector* blockVector = m_BlockVectors[defaultPoolIndex];
D3D12MA_ASSERT(blockVector);
const UINT64 preferredBlockSize = blockVector->GetPreferredBlockSize();
const bool preferCommittedMemory =
m_AlwaysCommitted ||
// Heuristics: Allocate committed memory if requested size if greater than half of preferred block size.
pAllocInfo->SizeInBytes > preferredBlockSize / 2;
if(preferCommittedMemory &&
(finalAllocDesc.Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) == 0)
{
finalAllocDesc.Flags |= ALLOCATION_FLAG_COMMITTED;
}
if((finalAllocDesc.Flags & ALLOCATION_FLAG_COMMITTED) != 0)
{
return AllocateHeap(&finalAllocDesc, *pAllocInfo, ppAllocation);
}
else
{
HRESULT hr = blockVector->Allocate(
pAllocInfo->SizeInBytes,
pAllocInfo->Alignment,
finalAllocDesc,
1,
(Allocation**)ppAllocation);
if(SUCCEEDED(hr))
{
return hr;
}
return AllocateHeap(&finalAllocDesc, *pAllocInfo, ppAllocation);
}
}
}
HRESULT AllocatorPimpl::CreateAliasingResource(
Allocation* pAllocation,
UINT64 AllocationLocalOffset,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
REFIID riidResource,
void** ppvResource)
{
*ppvResource = NULL;
D3D12_RESOURCE_DESC resourceDesc2 = *pResourceDesc;
D3D12_RESOURCE_ALLOCATION_INFO resAllocInfo = GetResourceAllocationInfo(resourceDesc2);
resAllocInfo.Alignment = D3D12MA_MAX<UINT64>(resAllocInfo.Alignment, D3D12MA_DEBUG_ALIGNMENT);
D3D12MA_ASSERT(IsPow2(resAllocInfo.Alignment));
D3D12MA_ASSERT(resAllocInfo.SizeInBytes > 0);
ID3D12Heap* const existingHeap = pAllocation->GetHeap();
const UINT64 existingOffset = pAllocation->GetOffset();
const UINT64 existingSize = pAllocation->GetSize();
const UINT64 newOffset = existingOffset + AllocationLocalOffset;
if(existingHeap == NULL ||
AllocationLocalOffset + resAllocInfo.SizeInBytes > existingSize ||
newOffset % resAllocInfo.Alignment != 0)
{
return E_INVALIDARG;
}
return m_Device->CreatePlacedResource(
existingHeap,
newOffset,
&resourceDesc2,
InitialResourceState,
pOptimizedClearValue,
riidResource,
ppvResource);
}
HRESULT AllocatorPimpl::SetDefaultHeapMinBytes(
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 minBytes)
{
if(!IsHeapTypeValid(heapType))
{
D3D12MA_ASSERT(0 && "Allocator::SetDefaultHeapMinBytes: Invalid heapType passed.");
return E_INVALIDARG;
}
if(SupportsResourceHeapTier2())
{
if(heapFlags != D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES &&
heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS &&
heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES &&
heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES)
{
D3D12MA_ASSERT(0 && "Allocator::SetDefaultHeapMinBytes: Invalid heapFlags passed.");
return E_INVALIDARG;
}
UINT64 newMinBytes = UINT64_MAX;
{
MutexLockWrite lock(m_DefaultPoolMinBytesMutex, m_UseMutex);
if(heapFlags == D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES)
{
m_DefaultPoolHeapTypeMinBytes[HeapTypeToIndex(heapType)] = minBytes;
newMinBytes = minBytes;
}
else
{
const UINT defaultPoolTier1Index = CalcDefaultPoolIndex(heapType, heapFlags, false);
m_DefaultPoolTier1MinBytes[defaultPoolTier1Index] = minBytes;
newMinBytes = m_DefaultPoolHeapTypeMinBytes[HeapTypeToIndex(heapType)];
if(newMinBytes == UINT64_MAX)
{
newMinBytes = m_DefaultPoolTier1MinBytes[CalcDefaultPoolIndex(heapType, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, false)] +
m_DefaultPoolTier1MinBytes[CalcDefaultPoolIndex(heapType, D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, false)] +
m_DefaultPoolTier1MinBytes[CalcDefaultPoolIndex(heapType, D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES, false)];
}
}
}
const UINT defaultPoolIndex = CalcDefaultPoolIndex(heapType, D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES);
return m_BlockVectors[defaultPoolIndex]->SetMinBytes(newMinBytes);
}
else
{
if(heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS &&
heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES &&
heapFlags != D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES)
{
D3D12MA_ASSERT(0 && "Allocator::SetDefaultHeapMinBytes: Invalid heapFlags passed.");
return E_INVALIDARG;
}
const UINT defaultPoolIndex = CalcDefaultPoolIndex(heapType, heapFlags);
return m_BlockVectors[defaultPoolIndex]->SetMinBytes(minBytes);
}
}
bool AllocatorPimpl::PrefersCommittedAllocation(const D3D12_RESOURCE_DESC& resourceDesc)
{
// Intentional. It may change in the future.
return false;
}
HRESULT AllocatorPimpl::AllocateCommittedResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource)
{
if((pAllocDesc->Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) != 0)
{
return E_OUTOFMEMORY;
}
if((pAllocDesc->Flags & ALLOCATION_FLAG_WITHIN_BUDGET) != 0)
{
Budget budget = {};
GetBudgetForHeapType(budget, pAllocDesc->HeapType);
if(budget.UsageBytes + resAllocInfo.SizeInBytes > budget.BudgetBytes)
{
return E_OUTOFMEMORY;
}
}
D3D12_HEAP_PROPERTIES heapProps = {};
heapProps.Type = pAllocDesc->HeapType;
const D3D12_HEAP_FLAGS heapFlags = pAllocDesc->ExtraHeapFlags;
ID3D12Resource* res = NULL;
HRESULT hr = m_Device->CreateCommittedResource(
&heapProps, heapFlags, pResourceDesc, InitialResourceState,
pOptimizedClearValue, IID_PPV_ARGS(&res));
if(SUCCEEDED(hr))
{
if(ppvResource != NULL)
{
hr = res->QueryInterface(riidResource, ppvResource);
}
if(SUCCEEDED(hr))
{
const BOOL wasZeroInitialized = TRUE;
Allocation* alloc = m_AllocationObjectAllocator.Allocate(this, resAllocInfo.SizeInBytes, wasZeroInitialized);
alloc->InitCommitted(pAllocDesc->HeapType);
alloc->SetResource(res, pResourceDesc);
*ppAllocation = alloc;
RegisterCommittedAllocation(*ppAllocation, pAllocDesc->HeapType);
const UINT heapTypeIndex = HeapTypeToIndex(pAllocDesc->HeapType);
m_Budget.AddAllocation(heapTypeIndex, resAllocInfo.SizeInBytes);
m_Budget.m_BlockBytes[heapTypeIndex] += resAllocInfo.SizeInBytes;
}
else
{
res->Release();
}
}
return hr;
}
HRESULT AllocatorPimpl::AllocateHeap(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO& allocInfo,
Allocation** ppAllocation)
{
*ppAllocation = nullptr;
if((pAllocDesc->Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) != 0)
{
return E_OUTOFMEMORY;
}
if((pAllocDesc->Flags & ALLOCATION_FLAG_WITHIN_BUDGET) != 0)
{
Budget budget = {};
GetBudgetForHeapType(budget, pAllocDesc->HeapType);
if(budget.UsageBytes + allocInfo.SizeInBytes > budget.BudgetBytes)
{
return E_OUTOFMEMORY;
}
}
D3D12_HEAP_FLAGS heapFlags = pAllocDesc->ExtraHeapFlags;
D3D12_HEAP_DESC heapDesc = {};
heapDesc.SizeInBytes = allocInfo.SizeInBytes;
heapDesc.Properties.Type = pAllocDesc->HeapType;
heapDesc.Alignment = allocInfo.Alignment;
heapDesc.Flags = heapFlags;
ID3D12Heap* heap = nullptr;
HRESULT hr = m_Device->CreateHeap(&heapDesc, __uuidof(*heap), (void**)&heap);
if(SUCCEEDED(hr))
{
const BOOL wasZeroInitialized = TRUE;
(*ppAllocation) = m_AllocationObjectAllocator.Allocate(this, allocInfo.SizeInBytes, wasZeroInitialized);
(*ppAllocation)->InitHeap(pAllocDesc->HeapType, heap);
RegisterCommittedAllocation(*ppAllocation, pAllocDesc->HeapType);
const UINT heapTypeIndex = HeapTypeToIndex(pAllocDesc->HeapType);
m_Budget.AddAllocation(heapTypeIndex, allocInfo.SizeInBytes);
m_Budget.m_BlockBytes[heapTypeIndex] += allocInfo.SizeInBytes;
}
return hr;
}
UINT AllocatorPimpl::CalcDefaultPoolCount() const
{
if(SupportsResourceHeapTier2())
{
return 3;
}
else
{
return 9;
}
}
UINT AllocatorPimpl::CalcDefaultPoolIndex(const ALLOCATION_DESC& allocDesc, const D3D12_RESOURCE_DESC& resourceDesc) const
{
const D3D12_HEAP_FLAGS extraHeapFlags = allocDesc.ExtraHeapFlags & ~GetExtraHeapFlagsToIgnore();
if(extraHeapFlags != 0)
{
return UINT32_MAX;
}
UINT poolIndex = UINT_MAX;
switch(allocDesc.HeapType)
{
case D3D12_HEAP_TYPE_DEFAULT: poolIndex = 0; break;
case D3D12_HEAP_TYPE_UPLOAD: poolIndex = 1; break;
case D3D12_HEAP_TYPE_READBACK: poolIndex = 2; break;
default: D3D12MA_ASSERT(0);
}
if(!SupportsResourceHeapTier2())
{
poolIndex *= 3;
if(resourceDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER)
{
++poolIndex;
const bool isRenderTargetOrDepthStencil =
(resourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
if(isRenderTargetOrDepthStencil)
{
++poolIndex;
}
}
}
return poolIndex;
}
UINT AllocatorPimpl::CalcDefaultPoolIndex(D3D12_HEAP_TYPE heapType, D3D12_HEAP_FLAGS heapFlags, bool supportsResourceHeapTier2)
{
const D3D12_HEAP_FLAGS extraHeapFlags = heapFlags & ~GetExtraHeapFlagsToIgnore();
if(extraHeapFlags != 0)
{
return UINT32_MAX;
}
UINT poolIndex = UINT_MAX;
switch(heapType)
{
case D3D12_HEAP_TYPE_DEFAULT: poolIndex = 0; break;
case D3D12_HEAP_TYPE_UPLOAD: poolIndex = 1; break;
case D3D12_HEAP_TYPE_READBACK: poolIndex = 2; break;
default: D3D12MA_ASSERT(0);
}
if(!supportsResourceHeapTier2)
{
poolIndex *= 3;
const bool allowBuffers = (heapFlags & D3D12_HEAP_FLAG_DENY_BUFFERS) == 0;
const bool allowRtDsTextures = (heapFlags & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES) == 0;
const bool allowNonRtDsTextures = (heapFlags & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES) == 0;
const uint8_t allowedGroupCount = (allowBuffers ? 1 : 0) + (allowRtDsTextures ? 1 : 0) + (allowNonRtDsTextures ? 1 : 0);
if(allowedGroupCount != 1)
{
return UINT32_MAX;
}
if(!allowBuffers)
{
++poolIndex;
if(allowRtDsTextures)
{
++poolIndex;
}
}
}
return poolIndex;
}
void AllocatorPimpl::CalcDefaultPoolParams(D3D12_HEAP_TYPE& outHeapType, D3D12_HEAP_FLAGS& outHeapFlags, UINT index) const
{
outHeapType = D3D12_HEAP_TYPE_DEFAULT;
outHeapFlags = D3D12_HEAP_FLAG_NONE;
if(!SupportsResourceHeapTier2())
{
switch(index % 3)
{
case 0:
outHeapFlags = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
break;
case 1:
outHeapFlags = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES;
break;
case 2:
outHeapFlags = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
break;
}
index /= 3;
}
switch(index)
{
case 0:
outHeapType = D3D12_HEAP_TYPE_DEFAULT;
break;
case 1:
outHeapType = D3D12_HEAP_TYPE_UPLOAD;
break;
case 2:
outHeapType = D3D12_HEAP_TYPE_READBACK;
break;
default:
D3D12MA_ASSERT(0);
}
}
void AllocatorPimpl::RegisterCommittedAllocation(Allocation* alloc, D3D12_HEAP_TYPE heapType)
{
const UINT heapTypeIndex = HeapTypeToIndex(heapType);
MutexLockWrite lock(m_CommittedAllocationsMutex[heapTypeIndex], m_UseMutex);
AllocationVectorType* const committedAllocations = m_pCommittedAllocations[heapTypeIndex];
D3D12MA_ASSERT(committedAllocations);
committedAllocations->InsertSorted(alloc, PointerLess());
}
void AllocatorPimpl::UnregisterCommittedAllocation(Allocation* alloc, D3D12_HEAP_TYPE heapType)
{
const UINT heapTypeIndex = HeapTypeToIndex(heapType);
MutexLockWrite lock(m_CommittedAllocationsMutex[heapTypeIndex], m_UseMutex);
AllocationVectorType* const committedAllocations = m_pCommittedAllocations[heapTypeIndex];
D3D12MA_ASSERT(committedAllocations);
bool success = committedAllocations->RemoveSorted(alloc, PointerLess());
D3D12MA_ASSERT(success);
}
void AllocatorPimpl::RegisterPool(Pool* pool, D3D12_HEAP_TYPE heapType)
{
const UINT heapTypeIndex = HeapTypeToIndex(heapType);
MutexLockWrite lock(m_PoolsMutex[heapTypeIndex], m_UseMutex);
PoolVectorType* const pools = m_pPools[heapTypeIndex];
D3D12MA_ASSERT(pools);
pools->InsertSorted(pool, PointerLess());
}
void AllocatorPimpl::UnregisterPool(Pool* pool, D3D12_HEAP_TYPE heapType)
{
const UINT heapTypeIndex = HeapTypeToIndex(heapType);
MutexLockWrite lock(m_PoolsMutex[heapTypeIndex], m_UseMutex);
PoolVectorType* const pools = m_pPools[heapTypeIndex];
D3D12MA_ASSERT(pools);
bool success = pools->RemoveSorted(pool, PointerLess());
D3D12MA_ASSERT(success);
}
void AllocatorPimpl::FreeCommittedMemory(Allocation* allocation)
{
D3D12MA_ASSERT(allocation && allocation->m_PackedData.GetType() == Allocation::TYPE_COMMITTED);
UnregisterCommittedAllocation(allocation, allocation->m_Committed.heapType);
const UINT64 allocationSize = allocation->GetSize();
const UINT heapTypeIndex = HeapTypeToIndex(allocation->m_Committed.heapType);
m_Budget.RemoveAllocation(heapTypeIndex, allocationSize);
m_Budget.m_BlockBytes[heapTypeIndex] -= allocationSize;
}
void AllocatorPimpl::FreePlacedMemory(Allocation* allocation)
{
D3D12MA_ASSERT(allocation && allocation->m_PackedData.GetType() == Allocation::TYPE_PLACED);
NormalBlock* const block = allocation->m_Placed.block;
D3D12MA_ASSERT(block);
BlockVector* const blockVector = block->GetBlockVector();
D3D12MA_ASSERT(blockVector);
m_Budget.RemoveAllocation(HeapTypeToIndex(block->GetHeapType()), allocation->GetSize());
blockVector->Free(allocation);
}
void AllocatorPimpl::FreeHeapMemory(Allocation* allocation)
{
D3D12MA_ASSERT(allocation && allocation->m_PackedData.GetType() == Allocation::TYPE_HEAP);
UnregisterCommittedAllocation(allocation, allocation->m_Heap.heapType);
SAFE_RELEASE(allocation->m_Heap.heap);
const UINT heapTypeIndex = HeapTypeToIndex(allocation->m_Heap.heapType);
const UINT64 allocationSize = allocation->GetSize();
m_Budget.m_BlockBytes[heapTypeIndex] -= allocationSize;
m_Budget.RemoveAllocation(heapTypeIndex, allocationSize);
}
void AllocatorPimpl::SetCurrentFrameIndex(UINT frameIndex)
{
m_CurrentFrameIndex.store(frameIndex);
#if D3D12MA_DXGI_1_4
if(m_Adapter3)
{
UpdateD3D12Budget();
}
#endif
}
void AllocatorPimpl::CalculateStats(Stats& outStats)
{
// Init stats
ZeroMemory(&outStats, sizeof(outStats));
outStats.Total.AllocationSizeMin = UINT64_MAX;
outStats.Total.UnusedRangeSizeMin = UINT64_MAX;
for(size_t i = 0; i < HEAP_TYPE_COUNT; i++)
{
outStats.HeapType[i].AllocationSizeMin = UINT64_MAX;
outStats.HeapType[i].UnusedRangeSizeMin = UINT64_MAX;
}
// Process deafult pools.
for(size_t i = 0; i < HEAP_TYPE_COUNT; ++i)
{
BlockVector* const pBlockVector = m_BlockVectors[i];
D3D12MA_ASSERT(pBlockVector);
pBlockVector->AddStats(outStats);
}
// Process custom pools
for(size_t heapTypeIndex = 0; heapTypeIndex < HEAP_TYPE_COUNT; ++heapTypeIndex)
{
MutexLockRead lock(m_PoolsMutex[heapTypeIndex], m_UseMutex);
const PoolVectorType* const poolVector = m_pPools[heapTypeIndex];
D3D12MA_ASSERT(poolVector);
for(size_t poolIndex = 0, count = poolVector->size(); poolIndex < count; ++poolIndex)
{
Pool* pool = (*poolVector)[poolIndex];
pool->m_Pimpl->GetBlockVector()->AddStats(outStats);
}
}
// Process committed allocations.
for(size_t heapTypeIndex = 0; heapTypeIndex < HEAP_TYPE_COUNT; ++heapTypeIndex)
{
StatInfo& heapStatInfo = outStats.HeapType[heapTypeIndex];
MutexLockRead lock(m_CommittedAllocationsMutex[heapTypeIndex], m_UseMutex);
const AllocationVectorType* const allocationVector = m_pCommittedAllocations[heapTypeIndex];
D3D12MA_ASSERT(allocationVector);
for(size_t allocIndex = 0, count = allocationVector->size(); allocIndex < count; ++allocIndex)
{
UINT64 size = (*allocationVector)[allocIndex]->GetSize();
StatInfo statInfo = {};
statInfo.BlockCount = 1;
statInfo.AllocationCount = 1;
statInfo.UnusedRangeCount = 0;
statInfo.UsedBytes = size;
statInfo.UnusedBytes = 0;
statInfo.AllocationSizeMin = size;
statInfo.AllocationSizeMax = size;
statInfo.UnusedRangeSizeMin = UINT64_MAX;
statInfo.UnusedRangeSizeMax = 0;
AddStatInfo(outStats.Total, statInfo);
AddStatInfo(heapStatInfo, statInfo);
}
}
// Post process
PostProcessStatInfo(outStats.Total);
for(size_t i = 0; i < HEAP_TYPE_COUNT; ++i)
PostProcessStatInfo(outStats.HeapType[i]);
}
void AllocatorPimpl::GetBudget(Budget* outGpuBudget, Budget* outCpuBudget)
{
if(outGpuBudget)
{
// Taking DEFAULT.
outGpuBudget->BlockBytes = m_Budget.m_BlockBytes[0];
outGpuBudget->AllocationBytes = m_Budget.m_AllocationBytes[0];
}
if(outCpuBudget)
{
// Taking UPLOAD + READBACK.
outCpuBudget->BlockBytes = m_Budget.m_BlockBytes[1] + m_Budget.m_BlockBytes[2];
outCpuBudget->AllocationBytes = m_Budget.m_AllocationBytes[1] + m_Budget.m_AllocationBytes[2];
}
#if D3D12MA_DXGI_1_4
if(m_Adapter3)
{
if(m_Budget.m_OperationsSinceBudgetFetch < 30)
{
MutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex);
if(outGpuBudget)
{
if(m_Budget.m_D3D12UsageLocal + outGpuBudget->BlockBytes > m_Budget.m_BlockBytesAtBudgetFetch[0])
{
outGpuBudget->UsageBytes = m_Budget.m_D3D12UsageLocal +
outGpuBudget->BlockBytes - m_Budget.m_BlockBytesAtBudgetFetch[0];
}
else
{
outGpuBudget->UsageBytes = 0;
}
outGpuBudget->BudgetBytes = m_Budget.m_D3D12BudgetLocal;
}
if(outCpuBudget)
{
if(m_Budget.m_D3D12UsageNonLocal + outCpuBudget->BlockBytes > m_Budget.m_BlockBytesAtBudgetFetch[1] + m_Budget.m_BlockBytesAtBudgetFetch[2])
{
outCpuBudget->UsageBytes = m_Budget.m_D3D12UsageNonLocal +
outCpuBudget->BlockBytes - (m_Budget.m_BlockBytesAtBudgetFetch[1] + m_Budget.m_BlockBytesAtBudgetFetch[2]);
}
else
{
outCpuBudget->UsageBytes = 0;
}
outCpuBudget->BudgetBytes = m_Budget.m_D3D12BudgetNonLocal;
}
}
else
{
UpdateD3D12Budget(); // Outside of mutex lock
GetBudget(outGpuBudget, outCpuBudget); // Recursion
}
}
else
#endif
{
if(outGpuBudget)
{
const UINT64 gpuMemorySize = m_AdapterDesc.DedicatedVideoMemory + m_AdapterDesc.DedicatedSystemMemory; // TODO: Is this right?
outGpuBudget->UsageBytes = outGpuBudget->BlockBytes;
outGpuBudget->BudgetBytes = gpuMemorySize * 8 / 10; // 80% heuristics.
}
if(outCpuBudget)
{
const UINT64 cpuMemorySize = m_AdapterDesc.SharedSystemMemory; // TODO: Is this right?
outCpuBudget->UsageBytes = outCpuBudget->BlockBytes;
outCpuBudget->BudgetBytes = cpuMemorySize * 8 / 10; // 80% heuristics.
}
}
}
void AllocatorPimpl::GetBudgetForHeapType(Budget& outBudget, D3D12_HEAP_TYPE heapType)
{
switch(heapType)
{
case D3D12_HEAP_TYPE_DEFAULT:
GetBudget(&outBudget, NULL);
break;
case D3D12_HEAP_TYPE_UPLOAD:
case D3D12_HEAP_TYPE_READBACK:
GetBudget(NULL, &outBudget);
break;
default: D3D12MA_ASSERT(0);
}
}
static void AddStatInfoToJson(JsonWriter& json, const StatInfo& statInfo)
{
json.BeginObject();
json.WriteString(L"Blocks");
json.WriteNumber(statInfo.BlockCount);
json.WriteString(L"Allocations");
json.WriteNumber(statInfo.AllocationCount);
json.WriteString(L"UnusedRanges");
json.WriteNumber(statInfo.UnusedRangeCount);
json.WriteString(L"UsedBytes");
json.WriteNumber(statInfo.UsedBytes);
json.WriteString(L"UnusedBytes");
json.WriteNumber(statInfo.UnusedBytes);
json.WriteString(L"AllocationSize");
json.BeginObject(true);
json.WriteString(L"Min");
json.WriteNumber(statInfo.AllocationSizeMin);
json.WriteString(L"Avg");
json.WriteNumber(statInfo.AllocationSizeAvg);
json.WriteString(L"Max");
json.WriteNumber(statInfo.AllocationSizeMax);
json.EndObject();
json.WriteString(L"UnusedRangeSize");
json.BeginObject(true);
json.WriteString(L"Min");
json.WriteNumber(statInfo.UnusedRangeSizeMin);
json.WriteString(L"Avg");
json.WriteNumber(statInfo.UnusedRangeSizeAvg);
json.WriteString(L"Max");
json.WriteNumber(statInfo.UnusedRangeSizeMax);
json.EndObject();
json.EndObject();
}
void AllocatorPimpl::BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap)
{
StringBuilder sb(GetAllocs());
{
JsonWriter json(GetAllocs(), sb);
Budget gpuBudget = {}, cpuBudget = {};
GetBudget(&gpuBudget, &cpuBudget);
Stats stats;
CalculateStats(stats);
json.BeginObject();
json.WriteString(L"Total");
AddStatInfoToJson(json, stats.Total);
for (size_t heapType = 0; heapType < HEAP_TYPE_COUNT; ++heapType)
{
json.WriteString(HeapTypeNames[heapType]);
AddStatInfoToJson(json, stats.HeapType[heapType]);
}
json.WriteString(L"Budget");
json.BeginObject();
{
json.WriteString(L"GPU");
WriteBudgetToJson(json, gpuBudget);
json.WriteString(L"CPU");
WriteBudgetToJson(json, cpuBudget);
}
json.EndObject();
if (DetailedMap)
{
json.WriteString(L"DetailedMap");
json.BeginObject();
json.WriteString(L"DefaultPools");
json.BeginObject();
if (SupportsResourceHeapTier2())
{
for (size_t heapType = 0; heapType < HEAP_TYPE_COUNT; ++heapType)
{
json.WriteString(HeapTypeNames[heapType]);
json.BeginObject();
json.WriteString(L"Blocks");
BlockVector* blockVector = m_BlockVectors[heapType];
D3D12MA_ASSERT(blockVector);
blockVector->WriteBlockInfoToJson(json);
json.EndObject(); // heap name
}
}
else
{
for (size_t heapType = 0; heapType < HEAP_TYPE_COUNT; ++heapType)
{
for (size_t heapSubType = 0; heapSubType < 3; ++heapSubType)
{
static const WCHAR* const heapSubTypeName[] = {
L" + buffer",
L" + texture",
L" + texture RT or DS",
};
json.BeginString();
json.ContinueString(HeapTypeNames[heapType]);
json.ContinueString(heapSubTypeName[heapSubType]);
json.EndString();
json.BeginObject();
json.WriteString(L"Blocks");
BlockVector* blockVector = m_BlockVectors[heapType * 3 + heapSubType];
D3D12MA_ASSERT(blockVector);
blockVector->WriteBlockInfoToJson(json);
json.EndObject(); // heap name
}
}
}
json.EndObject(); // DefaultPools
json.WriteString(L"CommittedAllocations");
json.BeginObject();
for (size_t heapType = 0; heapType < HEAP_TYPE_COUNT; ++heapType)
{
json.WriteString(HeapTypeNames[heapType]);
MutexLockRead lock(m_CommittedAllocationsMutex[heapType], m_UseMutex);
json.BeginArray();
const AllocationVectorType* const allocationVector = m_pCommittedAllocations[heapType];
D3D12MA_ASSERT(allocationVector);
for (size_t i = 0, count = allocationVector->size(); i < count; ++i)
{
Allocation* alloc = (*allocationVector)[i];
D3D12MA_ASSERT(alloc);
json.BeginObject(true);
json.AddAllocationToObject(*alloc);
json.EndObject();
}
json.EndArray();
}
json.EndObject(); // CommittedAllocations
json.EndObject(); // DetailedMap
}
json.EndObject();
}
const size_t length = sb.GetLength();
WCHAR* result = AllocateArray<WCHAR>(GetAllocs(), length + 1);
memcpy(result, sb.GetData(), length * sizeof(WCHAR));
result[length] = L'\0';
*ppStatsString = result;
}
void AllocatorPimpl::FreeStatsString(WCHAR* pStatsString)
{
D3D12MA_ASSERT(pStatsString);
Free(GetAllocs(), pStatsString);
}
HRESULT AllocatorPimpl::UpdateD3D12Budget()
{
#if D3D12MA_DXGI_1_4
D3D12MA_ASSERT(m_Adapter3);
DXGI_QUERY_VIDEO_MEMORY_INFO infoLocal = {};
DXGI_QUERY_VIDEO_MEMORY_INFO infoNonLocal = {};
HRESULT hrLocal = m_Adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &infoLocal);
HRESULT hrNonLocal = m_Adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &infoNonLocal);
{
MutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex);
if(SUCCEEDED(hrLocal))
{
m_Budget.m_D3D12UsageLocal = infoLocal.CurrentUsage;
m_Budget.m_D3D12BudgetLocal = infoLocal.Budget;
}
if(SUCCEEDED(hrNonLocal))
{
m_Budget.m_D3D12UsageNonLocal = infoNonLocal.CurrentUsage;
m_Budget.m_D3D12BudgetNonLocal = infoNonLocal.Budget;
}
for(UINT i = 0; i < HEAP_TYPE_COUNT; ++i)
{
m_Budget.m_BlockBytesAtBudgetFetch[i] = m_Budget.m_BlockBytes[i].load();
}
m_Budget.m_OperationsSinceBudgetFetch = 0;
}
return FAILED(hrLocal) ? hrLocal : hrNonLocal;
#else
return S_OK;
#endif
}
D3D12_RESOURCE_ALLOCATION_INFO AllocatorPimpl::GetResourceAllocationInfo(D3D12_RESOURCE_DESC& inOutResourceDesc) const
{
#if D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT
if(inOutResourceDesc.Alignment == 0 &&
inOutResourceDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
(inOutResourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) == 0
#if D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT == 1
&& CanUseSmallAlignment(inOutResourceDesc)
#endif
)
{
/*
The algorithm here is based on Microsoft sample: "Small Resources Sample"
https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12SmallResources
*/
const UINT64 smallAlignmentToTry = inOutResourceDesc.SampleDesc.Count > 1 ?
D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT :
D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT;
inOutResourceDesc.Alignment = smallAlignmentToTry;
const D3D12_RESOURCE_ALLOCATION_INFO smallAllocInfo = m_Device->GetResourceAllocationInfo(0, 1, &inOutResourceDesc);
// Check if alignment requested has been granted.
if(smallAllocInfo.Alignment == smallAlignmentToTry)
{
return smallAllocInfo;
}
inOutResourceDesc.Alignment = 0; // Restore original
}
#endif // #if D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT
return m_Device->GetResourceAllocationInfo(0, 1, &inOutResourceDesc);
}
void AllocatorPimpl::WriteBudgetToJson(JsonWriter& json, const Budget& budget)
{
json.BeginObject();
{
json.WriteString(L"BlockBytes");
json.WriteNumber(budget.BlockBytes);
json.WriteString(L"AllocationBytes");
json.WriteNumber(budget.AllocationBytes);
json.WriteString(L"UsageBytes");
json.WriteNumber(budget.UsageBytes);
json.WriteString(L"BudgetBytes");
json.WriteNumber(budget.BudgetBytes);
}
json.EndObject();
}
////////////////////////////////////////////////////////////////////////////////
// Public class Allocation implementation
void Allocation::PackedData::SetType(Type type)
{
const UINT u = (UINT)type;
D3D12MA_ASSERT(u < (1u << 2));
m_Type = u;
}
void Allocation::PackedData::SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension)
{
const UINT u = (UINT)resourceDimension;
D3D12MA_ASSERT(u < (1u << 3));
m_ResourceDimension = u;
}
void Allocation::PackedData::SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags)
{
const UINT u = (UINT)resourceFlags;
D3D12MA_ASSERT(u < (1u << 24));
m_ResourceFlags = u;
}
void Allocation::PackedData::SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout)
{
const UINT u = (UINT)textureLayout;
D3D12MA_ASSERT(u < (1u << 9));
m_TextureLayout = u;
}
void Allocation::Release()
{
if(this == NULL)
{
return;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
SAFE_RELEASE(m_Resource);
switch(m_PackedData.GetType())
{
case TYPE_COMMITTED:
m_Allocator->FreeCommittedMemory(this);
break;
case TYPE_PLACED:
m_Allocator->FreePlacedMemory(this);
break;
case TYPE_HEAP:
m_Allocator->FreeHeapMemory(this);
break;
}
FreeName();
m_Allocator->GetAllocationObjectAllocator().Free(this);
}
UINT64 Allocation::GetOffset() const
{
switch(m_PackedData.GetType())
{
case TYPE_COMMITTED:
case TYPE_HEAP:
return 0;
case TYPE_PLACED:
return m_Placed.offset;
default:
D3D12MA_ASSERT(0);
return 0;
}
}
ID3D12Heap* Allocation::GetHeap() const
{
switch(m_PackedData.GetType())
{
case TYPE_COMMITTED:
return NULL;
case TYPE_PLACED:
return m_Placed.block->GetHeap();
case TYPE_HEAP:
return m_Heap.heap;
default:
D3D12MA_ASSERT(0);
return 0;
}
}
void Allocation::SetName(LPCWSTR Name)
{
FreeName();
if(Name)
{
const size_t nameCharCount = wcslen(Name) + 1;
m_Name = D3D12MA_NEW_ARRAY(m_Allocator->GetAllocs(), WCHAR, nameCharCount);
memcpy(m_Name, Name, nameCharCount * sizeof(WCHAR));
}
}
Allocation::Allocation(AllocatorPimpl* allocator, UINT64 size, BOOL wasZeroInitialized) :
m_Allocator{allocator},
m_Size{size},
m_Resource{NULL},
m_CreationFrameIndex{allocator->GetCurrentFrameIndex()},
m_Name{NULL}
{
D3D12MA_ASSERT(allocator);
m_PackedData.SetType(TYPE_COUNT);
m_PackedData.SetResourceDimension(D3D12_RESOURCE_DIMENSION_UNKNOWN);
m_PackedData.SetResourceFlags(D3D12_RESOURCE_FLAG_NONE);
m_PackedData.SetTextureLayout(D3D12_TEXTURE_LAYOUT_UNKNOWN);
m_PackedData.SetWasZeroInitialized(wasZeroInitialized);
}
Allocation::~Allocation()
{
// Nothing here, everything already done in Release.
}
void Allocation::InitCommitted(D3D12_HEAP_TYPE heapType)
{
m_PackedData.SetType(TYPE_COMMITTED);
m_Committed.heapType = heapType;
}
void Allocation::InitPlaced(UINT64 offset, UINT64 alignment, NormalBlock* block)
{
m_PackedData.SetType(TYPE_PLACED);
m_Placed.offset = offset;
m_Placed.block = block;
}
void Allocation::InitHeap(D3D12_HEAP_TYPE heapType, ID3D12Heap* heap)
{
m_PackedData.SetType(TYPE_HEAP);
m_Heap.heapType = heapType;
m_Heap.heap = heap;
}
void Allocation::SetResource(ID3D12Resource* resource, const D3D12_RESOURCE_DESC* pResourceDesc)
{
D3D12MA_ASSERT(m_Resource == NULL && pResourceDesc);
m_Resource = resource;
m_PackedData.SetResourceDimension(pResourceDesc->Dimension);
m_PackedData.SetResourceFlags(pResourceDesc->Flags);
m_PackedData.SetTextureLayout(pResourceDesc->Layout);
}
void Allocation::FreeName()
{
if(m_Name)
{
const size_t nameCharCount = wcslen(m_Name) + 1;
D3D12MA_DELETE_ARRAY(m_Allocator->GetAllocs(), m_Name, nameCharCount);
m_Name = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////
// Private class AllocationObjectAllocator implementation
AllocationObjectAllocator::AllocationObjectAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks) :
m_Allocator(allocationCallbacks, 1024)
{
}
template<typename... Types> Allocation* AllocationObjectAllocator::Allocate(Types... args)
{
MutexLock mutexLock(m_Mutex);
return m_Allocator.Alloc(std::forward<Types>(args)...);
}
void AllocationObjectAllocator::Free(Allocation* alloc)
{
MutexLock mutexLock(m_Mutex);
m_Allocator.Free(alloc);
}
////////////////////////////////////////////////////////////////////////////////
// Public class Allocator implementation
Allocator::Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc) :
m_Pimpl(D3D12MA_NEW(allocationCallbacks, AllocatorPimpl)(allocationCallbacks, desc))
{
}
Allocator::~Allocator()
{
D3D12MA_DELETE(m_Pimpl->GetAllocs(), m_Pimpl);
}
void Allocator::Release()
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
// Copy is needed because otherwise we would call destructor and invalidate the structure with callbacks before using it to free memory.
const ALLOCATION_CALLBACKS allocationCallbacksCopy = m_Pimpl->GetAllocs();
D3D12MA_DELETE(allocationCallbacksCopy, this);
}
const D3D12_FEATURE_DATA_D3D12_OPTIONS& Allocator::GetD3D12Options() const
{
return m_Pimpl->GetD3D12Options();
}
HRESULT Allocator::CreateResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource)
{
if(!pAllocDesc || !pResourceDesc || !ppAllocation)
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to Allocator::CreateResource.");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
return m_Pimpl->CreateResource(pAllocDesc, pResourceDesc, InitialResourceState, pOptimizedClearValue, ppAllocation, riidResource, ppvResource);
}
HRESULT Allocator::AllocateMemory(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
Allocation** ppAllocation)
{
if(!pAllocDesc ||
!pAllocInfo ||
!ppAllocation ||
!(pAllocInfo->Alignment == 0 ||
pAllocInfo->Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT ||
pAllocInfo->Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) ||
pAllocInfo->SizeInBytes == 0 ||
pAllocInfo->SizeInBytes % (64ull * 1024) != 0)
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to Allocator::AllocateMemory.");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
return m_Pimpl->AllocateMemory(pAllocDesc, pAllocInfo, ppAllocation);
}
HRESULT Allocator::CreateAliasingResource(
Allocation* pAllocation,
UINT64 AllocationLocalOffset,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
REFIID riidResource,
void** ppvResource)
{
if(!pAllocation || !pResourceDesc || !ppvResource)
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to Allocator::CreateAliasingResource.");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
return m_Pimpl->CreateAliasingResource(pAllocation, AllocationLocalOffset, pResourceDesc, InitialResourceState, pOptimizedClearValue, riidResource, ppvResource);
}
HRESULT Allocator::CreatePool(
const POOL_DESC* pPoolDesc,
Pool** ppPool)
{
if(!pPoolDesc || !ppPool ||
!IsHeapTypeValid(pPoolDesc->HeapType) ||
(pPoolDesc->MaxBlockCount > 0 && pPoolDesc->MaxBlockCount < pPoolDesc->MinBlockCount))
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to Allocator::CreatePool.");
return E_INVALIDARG;
}
if(!m_Pimpl->HeapFlagsFulfillResourceHeapTier(pPoolDesc->HeapFlags))
{
D3D12MA_ASSERT(0 && "Invalid pPoolDesc->HeapFlags passed to Allocator::CreatePool. Did you forget to handle ResourceHeapTier=1?");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
*ppPool = D3D12MA_NEW(m_Pimpl->GetAllocs(), Pool)(this, *pPoolDesc);
HRESULT hr = (*ppPool)->m_Pimpl->Init();
if(SUCCEEDED(hr))
{
m_Pimpl->RegisterPool(*ppPool, pPoolDesc->HeapType);
}
else
{
D3D12MA_DELETE(m_Pimpl->GetAllocs(), *ppPool);
*ppPool = NULL;
}
return hr;
}
HRESULT Allocator::SetDefaultHeapMinBytes(
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
UINT64 minBytes)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
return m_Pimpl->SetDefaultHeapMinBytes(heapType, heapFlags, minBytes);
}
void Allocator::SetCurrentFrameIndex(UINT frameIndex)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->SetCurrentFrameIndex(frameIndex);
}
void Allocator::CalculateStats(Stats* pStats)
{
D3D12MA_ASSERT(pStats);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->CalculateStats(*pStats);
}
void Allocator::GetBudget(Budget* pGpuBudget, Budget* pCpuBudget)
{
if(pGpuBudget == NULL && pCpuBudget == NULL)
{
return;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->GetBudget(pGpuBudget, pCpuBudget);
}
void Allocator::BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap) const
{
D3D12MA_ASSERT(ppStatsString);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->BuildStatsString(ppStatsString, DetailedMap);
}
void Allocator::FreeStatsString(WCHAR* pStatsString) const
{
if (pStatsString != NULL)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->FreeStatsString(pStatsString);
}
}
////////////////////////////////////////////////////////////////////////////////
// Private class VirtualBlockPimpl definition
class VirtualBlockPimpl
{
public:
const ALLOCATION_CALLBACKS m_AllocationCallbacks;
const UINT64 m_Size;
BlockMetadata_Generic m_Metadata;
VirtualBlockPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT64 size);
~VirtualBlockPimpl();
};
VirtualBlockPimpl::VirtualBlockPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT64 size) :
m_AllocationCallbacks(allocationCallbacks),
m_Size(size),
m_Metadata(&m_AllocationCallbacks,
true) // isVirtual
{
m_Metadata.Init(m_Size);
}
VirtualBlockPimpl::~VirtualBlockPimpl()
{
}
////////////////////////////////////////////////////////////////////////////////
// Public class VirtualBlock implementation
VirtualBlock::VirtualBlock(const ALLOCATION_CALLBACKS& allocationCallbacks, const VIRTUAL_BLOCK_DESC& desc) :
m_Pimpl(D3D12MA_NEW(allocationCallbacks, VirtualBlockPimpl)(allocationCallbacks, desc.Size))
{
}
VirtualBlock::~VirtualBlock()
{
// THIS IS AN IMPORTANT ASSERT!
// Hitting it means you have some memory leak - unreleased allocations in this virtual block.
D3D12MA_ASSERT(m_Pimpl->m_Metadata.IsEmpty() && "Some allocations were not freed before destruction of this virtual block!");
D3D12MA_DELETE(m_Pimpl->m_AllocationCallbacks, m_Pimpl);
}
void VirtualBlock::Release()
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
// Copy is needed because otherwise we would call destructor and invalidate the structure with callbacks before using it to free memory.
const ALLOCATION_CALLBACKS allocationCallbacksCopy = m_Pimpl->m_AllocationCallbacks;
D3D12MA_DELETE(allocationCallbacksCopy, this);
}
BOOL VirtualBlock::IsEmpty() const
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
return m_Pimpl->m_Metadata.IsEmpty() ? TRUE : FALSE;
}
void VirtualBlock::GetAllocationInfo(UINT64 offset, VIRTUAL_ALLOCATION_INFO* pInfo) const
{
D3D12MA_ASSERT(offset != UINT64_MAX && pInfo);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->m_Metadata.GetAllocationInfo(offset, *pInfo);
}
HRESULT VirtualBlock::Allocate(const VIRTUAL_ALLOCATION_DESC* pDesc, UINT64* pOffset)
{
if(!pDesc || !pOffset || pDesc->Size == 0 || !IsPow2(pDesc->Alignment))
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to VirtualBlock::Allocate.");
return E_INVALIDARG;
}
*pOffset = UINT64_MAX;
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
const UINT64 alignment = pDesc->Alignment != 0 ? pDesc->Alignment : 1;
AllocationRequest allocRequest = {};
if(m_Pimpl->m_Metadata.CreateAllocationRequest(pDesc->Size, alignment, &allocRequest))
{
m_Pimpl->m_Metadata.Alloc(allocRequest, pDesc->Size, pDesc->pUserData);
D3D12MA_HEAVY_ASSERT(m_Pimpl->m_Metadata.Validate());
*pOffset = allocRequest.offset;
return S_OK;
}
else
{
return E_OUTOFMEMORY;
}
}
void VirtualBlock::FreeAllocation(UINT64 offset)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
D3D12MA_ASSERT(offset != UINT64_MAX);
m_Pimpl->m_Metadata.FreeAtOffset(offset);
D3D12MA_HEAVY_ASSERT(m_Pimpl->m_Metadata.Validate());
}
void VirtualBlock::Clear()
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->m_Metadata.Clear();
D3D12MA_HEAVY_ASSERT(m_Pimpl->m_Metadata.Validate());
}
void VirtualBlock::SetAllocationUserData(UINT64 offset, void* pUserData)
{
D3D12MA_ASSERT(offset != UINT64_MAX);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
m_Pimpl->m_Metadata.SetAllocationUserData(offset, pUserData);
}
void VirtualBlock::CalculateStats(StatInfo* pInfo) const
{
D3D12MA_ASSERT(pInfo);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
D3D12MA_HEAVY_ASSERT(m_Pimpl->m_Metadata.Validate());
m_Pimpl->m_Metadata.CalcAllocationStatInfo(*pInfo);
}
void VirtualBlock::BuildStatsString(WCHAR** ppStatsString) const
{
D3D12MA_ASSERT(ppStatsString);
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
StringBuilder sb(m_Pimpl->m_AllocationCallbacks);
{
JsonWriter json(m_Pimpl->m_AllocationCallbacks, sb);
D3D12MA_HEAVY_ASSERT(m_Pimpl->m_Metadata.Validate());
m_Pimpl->m_Metadata.WriteAllocationInfoToJson(json);
} // Scope for JsonWriter
const size_t length = sb.GetLength();
WCHAR* result = AllocateArray<WCHAR>(m_Pimpl->m_AllocationCallbacks, length + 1);
memcpy(result, sb.GetData(), length * sizeof(WCHAR));
result[length] = L'\0';
*ppStatsString = result;
}
void VirtualBlock::FreeStatsString(WCHAR* pStatsString) const
{
if (pStatsString != NULL)
{
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
D3D12MA::Free(m_Pimpl->m_AllocationCallbacks, pStatsString);
}
}
////////////////////////////////////////////////////////////////////////////////
// Public global functions
HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator)
{
if(!pDesc || !ppAllocator || !pDesc->pDevice || !pDesc->pAdapter ||
!(pDesc->PreferredBlockSize == 0 || (pDesc->PreferredBlockSize >= 16 && pDesc->PreferredBlockSize < 0x10000000000ull)))
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to CreateAllocator.");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
ALLOCATION_CALLBACKS allocationCallbacks;
SetupAllocationCallbacks(allocationCallbacks, pDesc->pAllocationCallbacks);
*ppAllocator = D3D12MA_NEW(allocationCallbacks, Allocator)(allocationCallbacks, *pDesc);
HRESULT hr = (*ppAllocator)->m_Pimpl->Init(*pDesc);
if(FAILED(hr))
{
D3D12MA_DELETE(allocationCallbacks, *ppAllocator);
*ppAllocator = NULL;
}
return hr;
}
HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC* pDesc, VirtualBlock** ppVirtualBlock)
{
if(!pDesc || !ppVirtualBlock)
{
D3D12MA_ASSERT(0 && "Invalid arguments passed to CreateVirtualBlock.");
return E_INVALIDARG;
}
D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK
ALLOCATION_CALLBACKS allocationCallbacks;
SetupAllocationCallbacks(allocationCallbacks, pDesc->pAllocationCallbacks);
*ppVirtualBlock = D3D12MA_NEW(allocationCallbacks, VirtualBlock)(allocationCallbacks, *pDesc);
return S_OK;
}
} // namespace D3D12MA
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
if (pindexBest->nHeight >= LAST_POW_BLOCK)
return 0;
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
pindexPrevStake = pindex;
nStakesHandled++;
}
pindex = pindex->pprev;
}
return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// pitbull: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT)
result.push_back(Pair("policy", "strict"));
if (CheckpointsMode == Checkpoints::ADVISORY)
result.push_back(Pair("policy", "advisory"));
if (CheckpointsMode == Checkpoints::PERMISSIVE)
result.push_back(Pair("policy", "permissive"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
|
/**
*
* HttpClientImpl.cc
* An Tao
*
* Copyright 2018, An Tao. All rights reserved.
* https://github.com/an-tao/drogon
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Drogon
*
*/
#include "HttpClientImpl.h"
#include "HttpResponseImpl.h"
#include "HttpRequestImpl.h"
#include "HttpResponseParser.h"
#include "HttpAppFrameworkImpl.h"
#include <drogon/config.h>
#include <algorithm>
#include <stdlib.h>
using namespace trantor;
using namespace drogon;
using namespace std::placeholders;
void HttpClientImpl::createTcpClient()
{
LOG_TRACE << "New TcpClient," << _server.toIpPort();
_tcpClient =
std::make_shared<trantor::TcpClient>(_loop, _server, "httpClient");
#ifdef OpenSSL_FOUND
if (_useSSL)
{
_tcpClient->enableSSL();
}
#endif
auto thisPtr = shared_from_this();
std::weak_ptr<HttpClientImpl> weakPtr = thisPtr;
_tcpClient->setConnectionCallback(
[weakPtr](const trantor::TcpConnectionPtr &connPtr) {
auto thisPtr = weakPtr.lock();
if (!thisPtr)
return;
if (connPtr->connected())
{
connPtr->setContext(std::make_shared<HttpResponseParser>());
// send request;
LOG_TRACE << "Connection established!";
while (thisPtr->_pipeliningCallbacks.size() <=
thisPtr->_pipeliningDepth &&
!thisPtr->_requestsBuffer.empty())
{
thisPtr->sendReq(connPtr,
thisPtr->_requestsBuffer.front().first);
thisPtr->_pipeliningCallbacks.push(
std::move(thisPtr->_requestsBuffer.front()));
thisPtr->_requestsBuffer.pop();
}
}
else
{
LOG_TRACE << "connection disconnect";
thisPtr->onError(ReqResult::NetworkFailure);
}
});
_tcpClient->setConnectionErrorCallback([weakPtr]() {
auto thisPtr = weakPtr.lock();
if (!thisPtr)
return;
// can't connect to server
thisPtr->onError(ReqResult::BadServerAddress);
});
_tcpClient->setMessageCallback(
[weakPtr](const trantor::TcpConnectionPtr &connPtr,
trantor::MsgBuffer *msg) {
auto thisPtr = weakPtr.lock();
if (thisPtr)
{
thisPtr->onRecvMessage(connPtr, msg);
}
});
_tcpClient->connect();
}
HttpClientImpl::HttpClientImpl(trantor::EventLoop *loop,
const trantor::InetAddress &addr,
bool useSSL)
: _loop(loop), _server(addr), _useSSL(useSSL)
{
}
HttpClientImpl::HttpClientImpl(trantor::EventLoop *loop,
const std::string &hostString)
: _loop(loop)
{
auto lowerHost = hostString;
std::transform(lowerHost.begin(),
lowerHost.end(),
lowerHost.begin(),
tolower);
if (lowerHost.find("https://") != std::string::npos)
{
_useSSL = true;
lowerHost = lowerHost.substr(8);
}
else if (lowerHost.find("http://") != std::string::npos)
{
_useSSL = false;
lowerHost = lowerHost.substr(7);
}
else
{
return;
}
auto pos = lowerHost.find(']');
if (lowerHost[0] == '[' && pos != std::string::npos)
{
// ipv6
_domain = lowerHost.substr(1, pos - 1);
if (lowerHost[pos + 1] == ':')
{
auto portStr = lowerHost.substr(pos + 2);
pos = portStr.find('/');
if (pos != std::string::npos)
{
portStr = portStr.substr(0, pos);
}
auto port = atoi(portStr.c_str());
if (port > 0 && port < 65536)
{
_server = InetAddress(_domain, port, true);
}
}
else
{
if (_useSSL)
{
_server = InetAddress(_domain, 443, true);
}
else
{
_server = InetAddress(_domain, 80, true);
}
}
}
else
{
auto pos = lowerHost.find(':');
if (pos != std::string::npos)
{
_domain = lowerHost.substr(0, pos);
auto portStr = lowerHost.substr(pos + 1);
pos = portStr.find('/');
if (pos != std::string::npos)
{
portStr = portStr.substr(0, pos);
}
auto port = atoi(portStr.c_str());
if (port > 0 && port < 65536)
{
_server = InetAddress(_domain, port);
}
}
else
{
_domain = lowerHost;
pos = _domain.find('/');
if (pos != std::string::npos)
{
_domain = _domain.substr(0, pos);
}
if (_useSSL)
{
_server = InetAddress(_domain, 443);
}
else
{
_server = InetAddress(_domain, 80);
}
}
}
LOG_TRACE << "userSSL=" << _useSSL << " domain=" << _domain;
}
HttpClientImpl::~HttpClientImpl()
{
LOG_TRACE << "Deconstruction HttpClient";
}
void HttpClientImpl::sendRequest(const drogon::HttpRequestPtr &req,
const drogon::HttpReqCallback &callback)
{
auto thisPtr = shared_from_this();
_loop->runInLoop([thisPtr, req, callback]() {
thisPtr->sendRequestInLoop(req, callback);
});
}
void HttpClientImpl::sendRequest(const drogon::HttpRequestPtr &req,
drogon::HttpReqCallback &&callback)
{
auto thisPtr = shared_from_this();
_loop->runInLoop([thisPtr, req, callback = std::move(callback)]() {
thisPtr->sendRequestInLoop(req, callback);
});
}
void HttpClientImpl::sendRequestInLoop(const drogon::HttpRequestPtr &req,
const drogon::HttpReqCallback &callback)
{
_loop->assertInLoopThread();
req->addHeader("Connection", "Keep-Alive");
// req->addHeader("Accept", "*/*");
if (!_domain.empty())
{
req->addHeader("Host", _domain);
}
req->addHeader("User-Agent", "DrogonClient");
for (auto &cookie : _validCookies)
{
if ((cookie.expiresDate().microSecondsSinceEpoch() == 0 ||
cookie.expiresDate() > trantor::Date::now()) &&
(cookie.path().empty() || req->path().find(cookie.path()) == 0))
{
req->addCookie(cookie.key(), cookie.value());
}
}
if (!_tcpClient)
{
_requestsBuffer.push(
{req,
[thisPtr = shared_from_this(),
callback](ReqResult result, const HttpResponsePtr &response) {
callback(result, response);
}});
if (!_dns)
{
bool hasIpv6Address = false;
if (_server.isIpV6())
{
auto ipaddr = _server.ip6NetEndian();
for (int i = 0; i < 4; i++)
{
if (ipaddr[i] != 0)
{
hasIpv6Address = true;
break;
}
}
}
if (_server.ipNetEndian() == 0 && !hasIpv6Address &&
!_domain.empty() && _server.portNetEndian() != 0)
{
_dns = true;
if (!_resolver)
{
_resolver = trantor::Resolver::newResolver(_loop);
}
_resolver->resolve(
_domain,
[thisPtr = shared_from_this(),
hasIpv6Address](const trantor::InetAddress &addr) {
thisPtr->_loop->runInLoop([thisPtr,
addr,
hasIpv6Address]() {
auto port = thisPtr->_server.portNetEndian();
thisPtr->_server = addr;
thisPtr->_server.setPortNetEndian(port);
LOG_TRACE << "dns:domain=" << thisPtr->_domain
<< ";ip=" << thisPtr->_server.toIp();
thisPtr->_dns = false;
if ((thisPtr->_server.ipNetEndian() != 0 ||
hasIpv6Address) &&
thisPtr->_server.portNetEndian() != 0)
{
thisPtr->createTcpClient();
}
else
{
while (!(thisPtr->_requestsBuffer).empty())
{
auto &reqAndCb =
(thisPtr->_requestsBuffer).front();
reqAndCb.second(ReqResult::BadServerAddress,
nullptr);
(thisPtr->_requestsBuffer).pop();
}
return;
}
});
});
return;
}
if ((_server.ipNetEndian() != 0 || hasIpv6Address) &&
_server.portNetEndian() != 0)
{
createTcpClient();
}
else
{
_requestsBuffer.pop();
callback(ReqResult::BadServerAddress, nullptr);
assert(_requestsBuffer.empty());
return;
}
}
}
else
{
// send request;
auto connPtr = _tcpClient->connection();
auto thisPtr = shared_from_this();
if (connPtr && connPtr->connected())
{
if (_pipeliningCallbacks.size() <= _pipeliningDepth &&
_requestsBuffer.empty())
{
sendReq(connPtr, req);
_pipeliningCallbacks.push(
{req,
[thisPtr, callback](ReqResult result,
const HttpResponsePtr &response) {
callback(result, response);
}});
}
else
{
_requestsBuffer.push(
{req,
[thisPtr, callback](ReqResult result,
const HttpResponsePtr &response) {
callback(result, response);
}});
}
}
else
{
_requestsBuffer.push(
{req,
[thisPtr, callback](ReqResult result,
const HttpResponsePtr &response) {
callback(result, response);
}});
}
}
}
void HttpClientImpl::sendReq(const trantor::TcpConnectionPtr &connPtr,
const HttpRequestPtr &req)
{
trantor::MsgBuffer buffer;
assert(req);
auto implPtr = static_cast<HttpRequestImpl *>(req.get());
implPtr->appendToBuffer(&buffer);
LOG_TRACE << "Send request:"
<< std::string(buffer.peek(), buffer.readableBytes());
_bytesSent += buffer.readableBytes();
connPtr->send(std::move(buffer));
}
void HttpClientImpl::onRecvMessage(const trantor::TcpConnectionPtr &connPtr,
trantor::MsgBuffer *msg)
{
auto responseParser = connPtr->getContext<HttpResponseParser>();
// LOG_TRACE << "###:" << msg->readableBytes();
auto msgSize = msg->readableBytes();
while (msg->readableBytes() > 0)
{
assert(!_pipeliningCallbacks.empty());
auto &firstReq = _pipeliningCallbacks.front();
if (firstReq.first->method() == Head)
{
responseParser->setForHeadMethod();
}
if (!responseParser->parseResponse(msg))
{
onError(ReqResult::BadResponse);
_bytesReceived += (msgSize - msg->readableBytes());
return;
}
if (responseParser->gotAll())
{
auto resp = responseParser->responseImpl();
responseParser->reset();
assert(!_pipeliningCallbacks.empty());
auto &type = resp->getHeaderBy("content-type");
if (resp->getHeaderBy("content-encoding") == "gzip")
{
resp->gunzip();
}
if (type.find("application/json") != std::string::npos)
{
resp->parseJson();
}
auto cb = std::move(firstReq);
_pipeliningCallbacks.pop();
handleCookies(resp);
_bytesReceived += (msgSize - msg->readableBytes());
msgSize = msg->readableBytes();
cb.second(ReqResult::Ok, resp);
// LOG_TRACE << "pipelining buffer size=" <<
// _pipeliningCallbacks.size(); LOG_TRACE << "requests buffer size="
// << _requestsBuffer.size();
if (!_requestsBuffer.empty())
{
auto &reqAndCb = _requestsBuffer.front();
sendReq(connPtr, reqAndCb.first);
_pipeliningCallbacks.push(std::move(reqAndCb));
_requestsBuffer.pop();
}
else
{
if (resp->ifCloseConnection() && _pipeliningCallbacks.empty())
{
_tcpClient.reset();
}
}
}
else
{
break;
}
}
}
HttpClientPtr HttpClient::newHttpClient(const std::string &ip,
uint16_t port,
bool useSSL,
trantor::EventLoop *loop)
{
bool isIpv6 = ip.find(':') == std::string::npos ? false : true;
return std::make_shared<HttpClientImpl>(
loop == nullptr ? HttpAppFrameworkImpl::instance().getLoop() : loop,
trantor::InetAddress(ip, port, isIpv6),
useSSL);
}
HttpClientPtr HttpClient::newHttpClient(const std::string &hostString,
trantor::EventLoop *loop)
{
return std::make_shared<HttpClientImpl>(
loop == nullptr ? HttpAppFrameworkImpl::instance().getLoop() : loop,
hostString);
}
void HttpClientImpl::onError(ReqResult result)
{
while (!_pipeliningCallbacks.empty())
{
auto cb = std::move(_pipeliningCallbacks.front());
_pipeliningCallbacks.pop();
cb.second(result, nullptr);
}
while (!_requestsBuffer.empty())
{
auto cb = std::move(_requestsBuffer.front().second);
_requestsBuffer.pop();
cb(result, nullptr);
}
_tcpClient.reset();
}
void HttpClientImpl::handleCookies(const HttpResponseImplPtr &resp)
{
_loop->assertInLoopThread();
if (!_enableCookies)
return;
for (auto &iter : resp->getCookies())
{
auto &cookie = iter.second;
if (!cookie.domain().empty() && cookie.domain() != _domain)
{
continue;
}
if (cookie.isSecure())
{
if (_useSSL)
{
_validCookies.emplace_back(cookie);
}
}
else
{
_validCookies.emplace_back(cookie);
}
}
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/debugger/cmd/cmd_out.h"
namespace HPHP { namespace Eval {
///////////////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(debuggerflow);
void CmdOut::help(DebuggerClient &client) {
client.helpTitle("Out Command");
client.helpCmds(
"[o]ut {count=1}", "steps out function calls",
nullptr
);
client.helpBody(
"Use this command at break to step out function calls. Specify a "
"count to step out more than one level of function calls."
);
}
void CmdOut::onSetup(DebuggerProxy &proxy, CmdInterrupt &interrupt) {
TRACE(2, "CmdOut::onSetup\n");
assert(!m_complete); // Complete cmds should not be asked to do work.
m_stackDepth = proxy.getStackDepth();
m_vmDepth = g_vmContext->m_nesting;
// Simply setup a "step out breakpoint" and let the program run.
setupStepOuts();
}
void CmdOut::onBeginInterrupt(DebuggerProxy &proxy, CmdInterrupt &interrupt) {
TRACE(2, "CmdOut::onBeginInterrupt\n");
assert(!m_complete); // Complete cmds should not be asked to do work.
m_needsVMInterrupt = false;
int currentVMDepth = g_vmContext->m_nesting;
int currentStackDepth = proxy.getStackDepth();
// Deeper or same depth? Keep running.
if ((currentVMDepth > m_vmDepth) ||
((currentVMDepth == m_vmDepth) && (currentStackDepth >= m_stackDepth))) {
TRACE(2, "CmdOut: deeper, keep running...\n");
return;
}
if (interrupt.getInterruptType() == ExceptionHandler) {
// If we're about to enter an exception handler we turn interrupts on to
// ensure we stop when control reaches the handler. The normal logic below
// will decide if we're done at that point or not.
TRACE(2, "CmdOut: exception thrown\n");
removeLocationFilter();
m_needsVMInterrupt = true;
return;
}
TRACE(2, "CmdOut: shallower stack depth, done.\n");
cleanupStepOuts();
m_complete = (decCount() == 0);
if (!m_complete) {
TRACE(2, "CmdOut: not complete, step out again.\n");
onSetup(proxy, interrupt);
}
}
///////////////////////////////////////////////////////////////////////////////
}}
|
#pragma once
#include <sys/time.h>
#include <chrono>
auto get_time() {
return std::chrono::high_resolution_clock::now();
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "velox/substrait/SubstraitToVeloxPlan.h"
#include "velox/substrait/TypeUtils.h"
namespace facebook::velox::substrait {
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::AggregateRel& sAgg) {
std::shared_ptr<const core::PlanNode> childNode;
if (sAgg.has_input()) {
childNode = toVeloxPlan(sAgg.input());
} else {
VELOX_FAIL("Child Rel is expected in AggregateRel.");
}
// Construct Velox grouping expressions.
auto inputTypes = childNode->outputType();
std::vector<std::shared_ptr<const core::FieldAccessTypedExpr>>
veloxGroupingExprs;
const auto& groupings = sAgg.groupings();
int inputPlanNodeId = planNodeId_ - 1;
// The index of output column.
int outIdx = 0;
for (const auto& grouping : groupings) {
auto groupingExprs = grouping.grouping_expressions();
for (const auto& groupingExpr : groupingExprs) {
// Velox's groupings are limited to be Field, so groupingExpr is
// expected to be FieldReference.
auto fieldExpr = exprConverter_->toVeloxExpr(
groupingExpr.selection(), inputPlanNodeId);
veloxGroupingExprs.emplace_back(fieldExpr);
outIdx += 1;
}
}
// Parse measures to get Aggregation phase and expressions.
bool phaseInited = false;
core::AggregationNode::Step aggStep;
// Project expressions are used to conduct a pre-projection before
// Aggregation if needed.
std::vector<std::shared_ptr<const core::ITypedExpr>> projectExprs;
std::vector<std::string> projectOutNames;
std::vector<std::shared_ptr<const core::CallTypedExpr>> aggExprs;
aggExprs.reserve(sAgg.measures().size());
// Construct Velox Aggregate expressions.
for (const auto& sMea : sAgg.measures()) {
auto aggFunction = sMea.measure();
// Get the params of this Aggregate function.
std::vector<std::shared_ptr<const core::ITypedExpr>> aggParams;
auto args = aggFunction.args();
aggParams.reserve(args.size());
for (auto arg : args) {
auto typeCase = arg.rex_type_case();
switch (typeCase) {
case ::substrait::Expression::RexTypeCase::kSelection: {
aggParams.emplace_back(
exprConverter_->toVeloxExpr(arg.selection(), inputPlanNodeId));
break;
}
case ::substrait::Expression::RexTypeCase::kScalarFunction: {
// Pre-projection is needed before Aggregate.
// The input of Aggregatation will be the output of the
// pre-projection.
auto sFunc = arg.scalar_function();
projectExprs.emplace_back(
exprConverter_->toVeloxExpr(sFunc, inputPlanNodeId));
auto colOutName = subParser_->makeNodeName(planNodeId_, outIdx);
projectOutNames.emplace_back(colOutName);
auto outType = subParser_->parseType(sFunc.output_type());
auto aggInputParam =
std::make_shared<const core::FieldAccessTypedExpr>(
toVeloxType(outType->type), colOutName);
aggParams.emplace_back(aggInputParam);
break;
}
default:
VELOX_NYI(
"Substrait conversion not supported for arg type '{}'", typeCase);
}
}
auto funcId = aggFunction.function_reference();
auto funcName = subParser_->findVeloxFunction(functionMap_, funcId);
auto aggOutType = subParser_->parseType(aggFunction.output_type());
auto aggExpr = std::make_shared<const core::CallTypedExpr>(
toVeloxType(aggOutType->type), std::move(aggParams), funcName);
aggExprs.emplace_back(aggExpr);
// Initialize the Aggregate Step.
if (!phaseInited) {
auto phase = aggFunction.phase();
switch (phase) {
case ::substrait::AGGREGATION_PHASE_INITIAL_TO_INTERMEDIATE:
aggStep = core::AggregationNode::Step::kPartial;
break;
case ::substrait::AGGREGATION_PHASE_INTERMEDIATE_TO_INTERMEDIATE:
aggStep = core::AggregationNode::Step::kIntermediate;
break;
case ::substrait::AGGREGATION_PHASE_INTERMEDIATE_TO_RESULT:
aggStep = core::AggregationNode::Step::kFinal;
break;
default:
VELOX_NYI("Substrait conversion not supported for phase '{}'", phase);
}
phaseInited = true;
}
outIdx += 1;
}
// Construct the Aggregate Node.
bool ignoreNullKeys = false;
std::vector<std::shared_ptr<const core::FieldAccessTypedExpr>> aggregateMasks(
outIdx);
std::vector<std::shared_ptr<const core::FieldAccessTypedExpr>>
preGroupingExprs;
if (projectOutNames.size() == 0) {
// Conduct Aggregation directly.
std::vector<std::string> aggOutNames;
aggOutNames.reserve(outIdx);
for (int idx = 0; idx < outIdx; idx++) {
aggOutNames.emplace_back(subParser_->makeNodeName(planNodeId_, idx));
}
return std::make_shared<core::AggregationNode>(
nextPlanNodeId(),
aggStep,
veloxGroupingExprs,
preGroupingExprs,
aggOutNames,
aggExprs,
aggregateMasks,
ignoreNullKeys,
childNode);
} else {
// A Project Node is needed before Aggregation.
auto projectNode = std::make_shared<core::ProjectNode>(
nextPlanNodeId(),
std::move(projectOutNames),
std::move(projectExprs),
childNode);
std::vector<std::string> aggOutNames;
aggOutNames.reserve(outIdx);
for (int idx = 0; idx < outIdx; idx++) {
aggOutNames.emplace_back(subParser_->makeNodeName(planNodeId_, idx));
}
return std::make_shared<core::AggregationNode>(
nextPlanNodeId(),
aggStep,
veloxGroupingExprs,
preGroupingExprs,
aggOutNames,
aggExprs,
aggregateMasks,
ignoreNullKeys,
projectNode);
}
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::ProjectRel& sProject) {
std::shared_ptr<const core::PlanNode> childNode;
if (sProject.has_input()) {
childNode = toVeloxPlan(sProject.input());
} else {
VELOX_FAIL("Child Rel is expected in ProjectRel.");
}
// Construct Velox Expressions.
auto projectExprs = sProject.expressions();
std::vector<std::string> projectNames;
std::vector<std::shared_ptr<const core::ITypedExpr>> expressions;
projectNames.reserve(projectExprs.size());
expressions.reserve(projectExprs.size());
auto prePlanNodeId = planNodeId_ - 1;
int colIdx = 0;
for (const auto& expr : projectExprs) {
expressions.emplace_back(exprConverter_->toVeloxExpr(expr, prePlanNodeId));
projectNames.emplace_back(subParser_->makeNodeName(planNodeId_, colIdx));
colIdx += 1;
}
auto projectNode = std::make_shared<core::ProjectNode>(
nextPlanNodeId(),
std::move(projectNames),
std::move(expressions),
childNode);
return projectNode;
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::FilterRel& sFilter) {
// TODO: Currently Filter is skipped because Filter is Pushdowned to
// TableScan.
std::shared_ptr<const core::PlanNode> childNode;
if (sFilter.has_input()) {
childNode = toVeloxPlan(sFilter.input());
} else {
VELOX_FAIL("Child Rel is expected in FilterRel.");
}
return childNode;
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::ReadRel& sRead,
u_int32_t& index,
std::vector<std::string>& paths,
std::vector<u_int64_t>& starts,
std::vector<u_int64_t>& lengths) {
// Get output names and types.
std::vector<std::string> colNameList;
std::vector<TypePtr> veloxTypeList;
if (sRead.has_base_schema()) {
const auto& baseSchema = sRead.base_schema();
colNameList.reserve(baseSchema.names().size());
for (const auto& name : baseSchema.names()) {
colNameList.emplace_back(name);
}
auto substraitTypeList = subParser_->parseNamedStruct(baseSchema);
veloxTypeList.reserve(substraitTypeList.size());
for (const auto& subType : substraitTypeList) {
veloxTypeList.emplace_back(toVeloxType(subType->type));
}
}
// Parse local files
if (sRead.has_local_files()) {
const auto& fileList = sRead.local_files().items();
paths.reserve(fileList.size());
starts.reserve(fileList.size());
lengths.reserve(fileList.size());
for (const auto& file : fileList) {
// Expect all Partitions share the same index.
index = file.partition_index();
paths.emplace_back(file.uri_file());
starts.emplace_back(file.start());
lengths.emplace_back(file.length());
}
}
// Velox requires Filter Pushdown must being enabled.
bool filterPushdownEnabled = true;
std::shared_ptr<connector::hive::HiveTableHandle> tableHandle;
if (!sRead.has_filter()) {
tableHandle = std::make_shared<connector::hive::HiveTableHandle>(
"hive_table",
filterPushdownEnabled,
connector::hive::SubfieldFilters{},
nullptr);
} else {
connector::hive::SubfieldFilters filters =
toVeloxFilter(colNameList, veloxTypeList, sRead.filter());
tableHandle = std::make_shared<connector::hive::HiveTableHandle>(
"hive_table", filterPushdownEnabled, std::move(filters), nullptr);
}
// Get assignments and out names.
std::vector<std::string> outNames;
outNames.reserve(colNameList.size());
std::unordered_map<std::string, std::shared_ptr<connector::ColumnHandle>>
assignments;
for (int idx = 0; idx < colNameList.size(); idx++) {
auto outName = subParser_->makeNodeName(planNodeId_, idx);
assignments[outName] = std::make_shared<connector::hive::HiveColumnHandle>(
colNameList[idx],
connector::hive::HiveColumnHandle::ColumnType::kRegular,
veloxTypeList[idx]);
outNames.emplace_back(outName);
}
auto outputType = ROW(std::move(outNames), std::move(veloxTypeList));
auto tableScanNode = std::make_shared<core::TableScanNode>(
nextPlanNodeId(), outputType, tableHandle, assignments);
return tableScanNode;
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::Rel& sRel) {
if (sRel.has_aggregate()) {
return toVeloxPlan(sRel.aggregate());
}
if (sRel.has_project()) {
return toVeloxPlan(sRel.project());
}
if (sRel.has_filter()) {
return toVeloxPlan(sRel.filter());
}
if (sRel.has_read()) {
return toVeloxPlan(sRel.read(), partitionIndex_, paths_, starts_, lengths_);
}
VELOX_NYI("Substrait conversion not supported for Rel.");
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::RelRoot& sRoot) {
// TODO: Use the names as the output names for the whole computing.
const auto& sNames = sRoot.names();
if (sRoot.has_input()) {
const auto& sRel = sRoot.input();
return toVeloxPlan(sRel);
}
VELOX_FAIL("Input is expected in RelRoot.");
}
std::shared_ptr<const core::PlanNode> SubstraitVeloxPlanConverter::toVeloxPlan(
const ::substrait::Plan& sPlan) {
// Construct the function map based on the Substrait representation.
for (const auto& sExtension : sPlan.extensions()) {
if (!sExtension.has_extension_function()) {
continue;
}
const auto& sFmap = sExtension.extension_function();
auto id = sFmap.function_anchor();
auto name = sFmap.name();
functionMap_[id] = name;
}
// Construct the expression converter.
exprConverter_ =
std::make_shared<SubstraitVeloxExprConverter>(subParser_, functionMap_);
// In fact, only one RelRoot or Rel is expected here.
for (const auto& sRel : sPlan.relations()) {
if (sRel.has_root()) {
return toVeloxPlan(sRel.root());
}
if (sRel.has_rel()) {
return toVeloxPlan(sRel.rel());
}
}
VELOX_FAIL("RelRoot or Rel is expected in Plan.");
}
std::string SubstraitVeloxPlanConverter::nextPlanNodeId() {
auto id = fmt::format("{}", planNodeId_);
planNodeId_++;
return id;
}
// This class contains the needed infos for Filter Pushdown.
// TODO: Support different types here.
class FilterInfo {
public:
// Used to set the left bound.
void setLeft(double left, bool isExclusive) {
left_ = left;
leftExclusive_ = isExclusive;
if (!isInitialized_) {
isInitialized_ = true;
}
}
// Used to set the right bound.
void setRight(double right, bool isExclusive) {
right_ = right;
rightExclusive_ = isExclusive;
if (!isInitialized_) {
isInitialized_ = true;
}
}
// Will fordis Null value if called once.
void forbidsNull() {
nullAllowed_ = false;
if (!isInitialized_) {
isInitialized_ = true;
}
}
// Return the initialization status.
bool isInitialized() {
return isInitialized_ ? true : false;
}
// The left bound.
std::optional<double> left_ = std::nullopt;
// The right bound.
std::optional<double> right_ = std::nullopt;
// The Null allowing.
bool nullAllowed_ = true;
// If true, left bound will be exclusive.
bool leftExclusive_ = false;
// If true, right bound will be exclusive.
bool rightExclusive_ = false;
private:
bool isInitialized_ = false;
};
connector::hive::SubfieldFilters SubstraitVeloxPlanConverter::toVeloxFilter(
const std::vector<std::string>& inputNameList,
const std::vector<TypePtr>& inputTypeList,
const ::substrait::Expression& sFilter) {
connector::hive::SubfieldFilters filters;
// A map between the column index and the FilterInfo for that column.
std::unordered_map<int, std::shared_ptr<FilterInfo>> colInfoMap;
for (int idx = 0; idx < inputNameList.size(); idx++) {
colInfoMap[idx] = std::make_shared<FilterInfo>();
}
std::vector<::substrait::Expression_ScalarFunction> scalarFunctions;
flattenConditions(sFilter, scalarFunctions);
// Construct the FilterInfo for the related column.
for (const auto& scalarFunction : scalarFunctions) {
auto filterNameSpec = subParser_->findSubstraitFuncSpec(
functionMap_, scalarFunction.function_reference());
auto filterName = subParser_->getSubFunctionName(filterNameSpec);
int32_t colIdx;
// TODO: Add different types' support here.
double val;
for (auto& param : scalarFunction.args()) {
auto typeCase = param.rex_type_case();
switch (typeCase) {
case ::substrait::Expression::RexTypeCase::kSelection: {
auto sel = param.selection();
// TODO: Only direct reference is considered here.
auto dRef = sel.direct_reference();
colIdx = subParser_->parseReferenceSegment(dRef);
break;
}
case ::substrait::Expression::RexTypeCase::kLiteral: {
auto sLit = param.literal();
// TODO: Only double is considered here.
val = sLit.fp64();
break;
}
default:
VELOX_NYI(
"Substrait conversion not supported for arg type '{}'", typeCase);
}
}
if (filterName == "is_not_null") {
colInfoMap[colIdx]->forbidsNull();
} else if (filterName == "gte") {
colInfoMap[colIdx]->setLeft(val, false);
} else if (filterName == "gt") {
colInfoMap[colIdx]->setLeft(val, true);
} else if (filterName == "lte") {
colInfoMap[colIdx]->setRight(val, false);
} else if (filterName == "lt") {
colInfoMap[colIdx]->setRight(val, true);
} else {
VELOX_NYI(
"Substrait conversion not supported for filter name '{}'",
filterName);
}
}
// Construct the Filters.
for (int idx = 0; idx < inputNameList.size(); idx++) {
auto filterInfo = colInfoMap[idx];
double leftBound;
double rightBound;
bool leftUnbounded = true;
bool rightUnbounded = true;
bool leftExclusive = false;
bool rightExclusive = false;
if (filterInfo->isInitialized()) {
if (filterInfo->left_) {
leftUnbounded = false;
leftBound = filterInfo->left_.value();
leftExclusive = filterInfo->leftExclusive_;
}
if (filterInfo->right_) {
rightUnbounded = false;
rightBound = filterInfo->right_.value();
rightExclusive = filterInfo->rightExclusive_;
}
bool nullAllowed = filterInfo->nullAllowed_;
filters[common::Subfield(inputNameList[idx])] =
std::make_unique<common::DoubleRange>(
leftBound,
leftUnbounded,
leftExclusive,
rightBound,
rightUnbounded,
rightExclusive,
nullAllowed);
}
}
return filters;
}
void SubstraitVeloxPlanConverter::flattenConditions(
const ::substrait::Expression& sFilter,
std::vector<::substrait::Expression_ScalarFunction>& scalarFunctions) {
auto typeCase = sFilter.rex_type_case();
switch (typeCase) {
case ::substrait::Expression::RexTypeCase::kScalarFunction: {
auto sFunc = sFilter.scalar_function();
auto filterNameSpec = subParser_->findSubstraitFuncSpec(
functionMap_, sFunc.function_reference());
// TODO: Only and relation is supported here.
if (subParser_->getSubFunctionName(filterNameSpec) == "and") {
for (const auto& sCondition : sFunc.args()) {
flattenConditions(sCondition, scalarFunctions);
}
} else {
scalarFunctions.emplace_back(sFunc);
}
break;
}
default:
VELOX_NYI("GetFlatConditions not supported for type '{}'", typeCase);
}
}
} // namespace facebook::velox::substrait
|
/*
* 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 prim nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior
* written permission.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ex/Exception.h>
#include <fio/InFile.h>
#include <prim/prim.h>
#include <strop/strop.h>
#include <tclap/CmdLine.h>
#include <string>
#include <vector>
#include "parse/Engine.h"
#include "parse/util.h"
s32 main(s32 _argc, char** _argv) {
std::string inputFile;
std::string transactionFile;
std::string messageFile;
std::string packetFile;
std::string latencyfile;
std::string hopcountfile;
f64 scalar;
bool packetHeaderLatency;
std::vector<std::string> filterStrs;
std::string description =
("Parse and analyze SuperSim output files (.mpf). "
"Nic McDonald. See LICENSE and NOTICE files for copyright details.");
try {
// create the command line parser
TCLAP::CmdLine cmd(description, ' ', "1.0");
// define command line args
TCLAP::UnlabeledValueArg<std::string> inputFileArg(
"inputfile", "input file to be parsed",
true, "", "filename", cmd);
TCLAP::ValueArg<std::string> transactionFileArg(
"t", "transactionfile", "output transaction latencies file",
false, "", "filename", cmd);
TCLAP::ValueArg<std::string> messageFileArg(
"m", "messagefile", "output message latencies file",
false, "", "filename", cmd);
TCLAP::ValueArg<std::string> packetFileArg(
"p", "packetfile", "output packet latencies file",
false, "", "filename", cmd);
TCLAP::ValueArg<std::string> latencyFileArg(
"l", "latencyfile", "output aggregate latencies file",
false, "", "filename", cmd);
TCLAP::ValueArg<std::string> hopcountFileArg(
"c", "hopcountfile", "output aggregate hopcounts file",
false, "", "filename", cmd);
TCLAP::ValueArg<f64> scalarArg(
"s", "scalar", "latency scalar",
false, 1.0, "f64", cmd);
TCLAP::SwitchArg packetHeaderLatencyArg(
"", "headerlatency", "use header latency for packets",
cmd, false);
TCLAP::MultiArg<std::string> filterStrsArg(
"f", "filter", "acceptance filters",
false, "filter description", cmd);
// parse the command line
cmd.parse(_argc, _argv);
// copy the values out to variables
inputFile = inputFileArg.getValue();
transactionFile = transactionFileArg.getValue();
messageFile = messageFileArg.getValue();
packetFile = packetFileArg.getValue();
latencyfile = latencyFileArg.getValue();
hopcountfile = hopcountFileArg.getValue();
scalar = scalarArg.getValue();
packetHeaderLatency = packetHeaderLatencyArg.getValue();
filterStrs = filterStrsArg.getValue();
} catch (TCLAP::ArgException& e) {
throw std::runtime_error(e.error().c_str());
}
// create a processing engine
Engine engine(transactionFile, messageFile, packetFile,
latencyfile, hopcountfile, scalar,
packetHeaderLatency, filterStrs);
// create input file object
if (inputFile.size() == 0) {
throw ex::Exception("How do you expect to open a file without a name?\n");
}
fio::InFile inFile(inputFile);
// feed the contents of the file into the processing engine line by line
std::string line;
std::vector<std::string> words;
for (s64 lineNum = 1; true; lineNum++) {
fio::InFile::Status sts = inFile.getLine(&line);
if (sts == fio::InFile::Status::ERROR) {
throw ex::Exception("Error while reading input file\n");
}
if (sts == fio::InFile::Status::END) {
break;
}
line = strop::trim(line);
words.clear();
u64 wordCount = split(line, &words);
if (wordCount == 0) {
continue; // probably the last line
}
if (words.at(0) == "+T") {
// parse the transaction start command
u64 transId = toU64(words.at(1));
u64 transStart = toU64(words.at(2));
engine.transactionStart(transId, transStart);
} else if (words.at(0) == "-T") {
// parse the transaction end command
u64 transId = toU64(words.at(1));
u64 transEnd = toU64(words.at(2));
engine.transactionEnd(transId, transEnd);
} else if (words.at(0) == "+M") {
// parse the message start command
u32 msgId = toU32(words.at(1));
u32 msgSrc = toU32(words.at(2));
u32 msgDst = toU32(words.at(3));
u64 transId = toU64(words.at(4));
u32 protocolClass = toU32(words.at(5));
u32 minimalHops = toU32(words.at(6));
u32 opCode = toU32(words.at(7));
engine.messageStart(msgId, msgSrc, msgDst, transId, protocolClass,
minimalHops, opCode);
} else if (words.at(0) == "-M") {
// parse the message end command
engine.messageEnd();
} else if (words.at(0) == "+P") {
// parse the packet start command
u32 pktId = toU32(words.at(1));
u32 hopCount = toU32(words.at(2));
engine.packetStart(pktId, hopCount);
} else if (words.at(0) == "-P") {
// parse the packet end command
engine.packetEnd();
} else if (words.at(0) == "F") {
// parse the flit occurrence command
u32 flitId = toU32(words.at(1));
u64 flitSend = toU64(words.at(2));
u64 flitRecv = toU64(words.at(3));
engine.flit(flitId, flitSend, flitRecv);
} else {
throw ex::Exception("Invalid line command. File corrupted :(\n");
}
}
engine.complete();
return 0;
}
|
#pragma warning(disable : 4018) // warning C4018: '<' : signed/unsigned mismatch
#include "NvTriStripObjects.h"
#include "NvTriStrip.h"
////////////////////////////////////////////////////////////////////////////////////////
//private data
static unsigned int cacheSize = CACHESIZE_GEFORCE1_2;
static bool bStitchStrips = true;
static unsigned int minStripSize = 0;
static bool bListsOnly = false;
////////////////////////////////////////////////////////////////////////////////////////
// SetListsOnly()
//
// If set to true, will return an optimized list, with no strips at all.
//
// Default value: false
//
void SetListsOnly(const bool _bListsOnly)
{
bListsOnly = _bListsOnly;
}
////////////////////////////////////////////////////////////////////////////////////////
// SetCacheSize()
//
// Sets the cache size which the stripfier uses to optimize the data.
// Controls the length of the generated individual strips.
// This is the "actual" cache size, so 24 for GeForce3 and 16 for GeForce1/2
// You may want to play around with this number to tweak performance.
//
// Default value: 16
//
void SetCacheSize(const unsigned int _cacheSize)
{
cacheSize = _cacheSize;
}
////////////////////////////////////////////////////////////////////////////////////////
// SetStitchStrips()
//
// bool to indicate whether to stitch together strips into one huge strip or not.
// If set to true, you'll get back one huge strip stitched together using degenerate
// triangles.
// If set to false, you'll get back a large number of separate strips.
//
// Default value: true
//
void SetStitchStrips(const bool _bStitchStrips)
{
bStitchStrips = _bStitchStrips;
}
////////////////////////////////////////////////////////////////////////////////////////
// SetMinStripSize()
//
// Sets the minimum acceptable size for a strip, in triangles.
// All strips generated which are shorter than this will be thrown into one big, separate list.
//
// Default value: 0
//
void SetMinStripSize(const unsigned int _minStripSize)
{
minStripSize = _minStripSize;
}
////////////////////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
void GenerateStrips(const unsigned int* in_indices, const unsigned int in_numIndices,
PrimitiveGroup** primGroups, unsigned int* numGroups)
{
//put data in format that the stripifier likes
UIntVec tempIndices;
tempIndices.resize(in_numIndices);
unsigned int maxIndex = 0;
for(int i = 0; i < in_numIndices; i++)
{
tempIndices[i] = in_indices[i];
if(in_indices[i] > maxIndex)
maxIndex = in_indices[i];
}
NvStripInfoVec tempStrips;
NvFaceInfoVec tempFaces;
NvStripifier stripifier;
//do actual stripification
stripifier.Stripify(tempIndices, cacheSize, minStripSize, maxIndex, tempStrips, tempFaces);
//stitch strips together
IntVec stripIndices;
unsigned int numSeparateStrips = 0;
//int i = 0;
if(bListsOnly)
{
//if we're outputting only lists, we're done
*numGroups = 1;
(*primGroups) = new PrimitiveGroup[*numGroups];
PrimitiveGroup* primGroupArray = *primGroups;
//count the total number of indices
unsigned int numIndices = 0;
for(int i = 0; i < tempStrips.size(); i++)
{
numIndices += (int)(tempStrips[i]->m_faces.size()) * 3;
}
//add in the list
numIndices += (int)(tempFaces.size()) * 3;
primGroupArray[0].type = PT_LIST;
primGroupArray[0].numIndices = numIndices;
primGroupArray[0].indices = new unsigned int[numIndices];
//do strips
unsigned int indexCtr = 0;
for(int i = 0; i < tempStrips.size(); i++)
{
for(int j = 0; j < tempStrips[i]->m_faces.size(); j++)
{
//degenerates are of no use with lists
if(!NvStripifier::IsDegenerate(tempStrips[i]->m_faces[j]))
{
primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v0;
primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v1;
primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v2;
}
else
{
//we've removed a tri, reduce the number of indices
primGroupArray[0].numIndices -= 3;
}
}
}
//do lists
for(int i = 0; i < tempFaces.size(); i++)
{
primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v0;
primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v1;
primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v2;
}
}
else
{
stripifier.CreateStrips(tempStrips, stripIndices, bStitchStrips, numSeparateStrips);
//if we're stitching strips together, we better get back only one strip from CreateStrips()
assert( (bStitchStrips && (numSeparateStrips == 1)) || !bStitchStrips);
//convert to output format
*numGroups = numSeparateStrips; //for the strips
if(tempFaces.size() != 0)
(*numGroups)++; //we've got a list as well, increment
(*primGroups) = new PrimitiveGroup[*numGroups];
PrimitiveGroup* primGroupArray = *primGroups;
//first, the strips
int startingLoc = 0;
for(int stripCtr = 0; stripCtr < numSeparateStrips; stripCtr++)
{
int stripLength = 0;
if(!bStitchStrips)
{
//if we've got multiple strips, we need to figure out the correct length
int i;
for(i = startingLoc; i < stripIndices.size(); i++)
{
if(stripIndices[i] == -1)
break;
}
stripLength = i - startingLoc;
}
else
stripLength = (int)(stripIndices.size());
primGroupArray[stripCtr].type = PT_STRIP;
primGroupArray[stripCtr].indices = new unsigned int[stripLength];
primGroupArray[stripCtr].numIndices = stripLength;
int indexCtr = 0;
for(int i = startingLoc; i < stripLength + startingLoc; i++)
primGroupArray[stripCtr].indices[indexCtr++] = stripIndices[i];
//we add 1 to account for the -1 separating strips
//this doesn't break the stitched case since we'll exit the loop
startingLoc += stripLength + 1;
}
//next, the list
if(tempFaces.size() != 0)
{
int faceGroupLoc = (*numGroups) - 1; //the face group is the last one
primGroupArray[faceGroupLoc].type = PT_LIST;
primGroupArray[faceGroupLoc].indices = new unsigned int[tempFaces.size() * 3];
primGroupArray[faceGroupLoc].numIndices = (unsigned int)(tempFaces.size()) * 3;
int indexCtr = 0;
for(int i = 0; i < tempFaces.size(); i++)
{
primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v0;
primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v1;
primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v2;
}
}
}
//clean up everything
//delete strips
for(int i = 0; i < tempStrips.size(); i++)
{
for(int j = 0; j < tempStrips[i]->m_faces.size(); j++)
{
delete tempStrips[i]->m_faces[j];
tempStrips[i]->m_faces[j] = NULL;
}
delete tempStrips[i];
tempStrips[i] = NULL;
}
//delete faces
for(int i = 0; i < tempFaces.size(); i++)
{
delete tempFaces[i];
tempFaces[i] = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////////////
// RemapIndices()
//
// Function to remap your indices to improve spatial locality in your vertex buffer.
//
// in_primGroups: array of PrimitiveGroups you want remapped
// numGroups: number of entries in in_primGroups
// numVerts: number of vertices in your vertex buffer, also can be thought of as the range
// of acceptable values for indices in your primitive groups.
// remappedGroups: array of remapped PrimitiveGroups
//
// Note that, according to the remapping handed back to you, you must reorder your
// vertex buffer.
//
void RemapIndices(const PrimitiveGroup* in_primGroups, const unsigned int numGroups,
const unsigned int numVerts, PrimitiveGroup** remappedGroups)
{
(*remappedGroups) = new PrimitiveGroup[numGroups];
//caches oldIndex --> newIndex conversion
int *indexCache;
indexCache = new int[numVerts];
memset(indexCache, -1, sizeof(int)*numVerts);
//loop over primitive groups
unsigned int indexCtr = 0;
for(int i = 0; i < numGroups; i++)
{
unsigned int numIndices = in_primGroups[i].numIndices;
//init remapped group
(*remappedGroups)[i].type = in_primGroups[i].type;
(*remappedGroups)[i].numIndices = numIndices;
(*remappedGroups)[i].indices = new unsigned int[numIndices];
for(int j = 0; j < numIndices; j++)
{
int cachedIndex = indexCache[in_primGroups[i].indices[j]];
if(cachedIndex == -1) //we haven't seen this index before
{
//point to "last" vertex in VB
(*remappedGroups)[i].indices[j] = indexCtr;
//add to index cache, increment
indexCache[in_primGroups[i].indices[j]] = indexCtr++;
}
else
{
//we've seen this index before
(*remappedGroups)[i].indices[j] = cachedIndex;
}
}
}
delete[] indexCache;
}
|
#include "sarpch.h"
#include "OpenGLRendererAPI.h"
#include <glad/glad.h>
namespace Sarene
{
void OpenGLRendererAPI::SetClearColor(const glm::vec4& color)
{
glClearColor(color.r, color.g, color.b, color.a);
}
void OpenGLRendererAPI::Clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void OpenGLRendererAPI::DrawIndexed(const Ref<VertexArray>& vertexArray)
{
glDrawElements(GL_TRIANGLES, vertexArray->GetIndexBuffer()->GetCount(), GL_UNSIGNED_INT, nullptr);
}
}
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemResource_Wool_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass PrimalItemResource_Wool.PrimalItemResource_Wool_C
// 0x0000 (0x0AE0 - 0x0AE0)
class UPrimalItemResource_Wool_C : public UPrimalItemResource_PeltOrHair_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemResource_Wool.PrimalItemResource_Wool_C");
return ptr;
}
void ExecuteUbergraph_PrimalItemResource_Wool(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
#include "priv.h"
#include "bindcb.h"
#include "resource.h"
#include <vrsscan.h>
#include "iface.h"
#include "security.h"
#include <wintrust.h>
#include "iehelpid.h"
#include <shlwapi.h>
#include "inetreg.h"
#include <mluisupp.h>
#define MIME
#include "filetype.h"
#ifdef UNIX
#include "unixstuff.h"
#define ALLFILE_WILDCARD TEXT("*")
#else
#define ALLFILE_WILDCARD TEXT("*.*")
#endif
#define MAX_BYTES_STRLEN 64
#define CALC_NOW 5 // Recalcs Estimated time left every this many'th call to OnProgress
//
// Enable WinVerifyTrust
//
#define CALL_WVT
#ifdef CALL_WVT
#include "wvtp.h"
//
// Note that this is a global variable. It means we don't call LoadLibrary
// everytime we download an EXE (good), but the user need to reboot if
// WINTRUST.DLL is added later (bad). Since WINTRUST.DLL is part of IE 3.0,
// this is sufficient at this point.
//
Cwvt g_wvt;
HWND g_hDlgActive = NULL; // BUGBUG: get rid of this, not needed
//
// A named mutex is being used to determine if a critical operation exist, such as a file download.
// When we detect this we can prevent things like going offline while a download is in progress.
// To start the operation Create the named mutex. When the op is complete, close the handle.
// To see if any pending operations are in progress, Open the named mutex. Success/fail will indicate
// if any pending operations exist. This mechanism is being used to determine if a file download is
// in progress when the user attempts to go offline. If so, we prompt them to let them know that going
// offline will cancel the download(s).
HANDLE g_hCritOpMutex = NULL;
// SafeOpen dialog
// BUGBUG tonyci 5March97 We need to revise this fix post Beta1,
// since all this is not an extensivle list.
const LPCTSTR c_arszUnsafeExts[] =
{TEXT(".exe"), TEXT(".com"), TEXT(".bat"), TEXT(".lnk"), TEXT(".url"),
TEXT(".cmd"), TEXT(".inf"), TEXT(".reg"), TEXT(".isp"), TEXT(".bas"), TEXT(".pcd"),
TEXT(".mst"), TEXT(".pif"), TEXT(".scr"), TEXT(".hlp"), TEXT(".chm"), TEXT(".hta"), TEXT(".asp"),
TEXT(".js"), TEXT(".jse"), TEXT(".vbs"), TEXT(".vbe"), TEXT(".ws"), TEXT(".wsh"), TEXT(".msi")
};
const LPCTSTR c_arszExecutableExtns[] =
{TEXT(".exe"), TEXT(".com"), TEXT(".bat"), TEXT(".lnk"), TEXT(".cmd"), TEXT(".pif"),
TEXT(".scr"), TEXT(".js"), TEXT(".jse"), TEXT(".vbs"), TEXT(".vbe"), TEXT(".wsh")
};
UINT _VerifyTrust(HWND hwnd, LPCTSTR pszFileName, LPCWSTR pszStatusText);
#endif // CALL_WVT
// Do strong typechecking on the parameters
#ifdef SAFECAST
#undef SAFECAST
#endif
#define SAFECAST(_src, _type) (((_type)(_src)==(_src)?0:0), (_type)(_src))
// OpenUIURL is just a wrapper for OpenUI, calling CreateURLMoniker() if the
// caller only has an URL.
HRESULT
CDownLoad_OpenUIURL(
LPCWSTR pwszURL,
IBindCtx *pbc,
LPWSTR pwzHeaders,
BOOL fSync,
BOOL fSaveAs=FALSE,
BOOL fSafe=FALSE,
DWORD dwVerb=BINDVERB_GET,
DWORD grfBINDF=(BINDF_ASYNCHRONOUS | BINDF_PULLDATA),
BINDINFO* pbinfo=NULL,
LPCTSTR pszRedir=NULL,
UINT uiCP=CP_ACP
);
void
CDownLoad_OpenUI(
IMoniker* pmk,
IBindCtx *pbc,
BOOL fSync,
BOOL fSaveAs=FALSE,
BOOL fSafe=FALSE,
LPWSTR pwzHeaders = NULL,
DWORD dwVerb=BINDVERB_GET,
DWORD grfBINDF = (BINDF_ASYNCHRONOUS | BINDF_PULLDATA),
BINDINFO* pbinfo = NULL,
LPCTSTR pszRedir=NULL,
UINT uiCP=CP_ACP
);
extern HRESULT _GetRequestFlagFromPIB(IBinding *pib, DWORD *pdwOptions);
UINT IE_ErrorMsgBox(IShellBrowser* psb,
HWND hwnd, HRESULT hrError, LPCWSTR szError, LPCTSTR szURL,
UINT idResource, UINT wFlags);
BOOL IsAssociatedWithIE(LPCWSTR pszFileName);
extern "C" EXECUTION_STATE WINAPI pSetThreadExecutionState(EXECUTION_STATE esFlags); // Win2k+, Win98+ kernel32 API
#define DM_DOWNLOAD TF_SHDPROGRESS
#define DM_PROGRESS TF_SHDPROGRESS
#define DM_WVT TF_SHDPROGRESS
#define DWNLDMSG(psz, psz2) TraceMsg(DM_DOWNLOAD, "shd TR-DWNLD::%s %s", psz, psz2)
#define DWNLDMSG2(psz, x) TraceMsg(DM_DOWNLOAD, "shd TR-DWNLD::%s %x", psz, x)
#define DWNLDMSG3(psz, x, y) TraceMsg(DM_DOWNLOAD, "shd TR-DWNLD::%s %x %x", psz, x, y)
#define DWNLDMSG4(psz, x, y, z) TraceMsg(DM_DOWNLOAD, "shd TR-DWNLD::%s %x %x %x", psz, x, y, z)
#define SAFEMSG(psz, psz2) TraceMsg(0, "shd TR-SAFE::%s %s", psz, psz2)
#define SAFEMSG2(psz, x) TraceMsg(0, "shd TR-SAFE::%s %x", psz, x)
#define EXPMSG(psz, psz2) TraceMsg(0, "shd TR-EXP::%s %s", psz, psz2)
#define MDLGMSG(psz, x) TraceMsg(0, "shd TR-MODELESS::%s %x", psz, x)
#define MSGMSG(psz, x) TraceMsg(TF_SHDTHREAD, "ief MMSG::%s %x", psz, x)
#define PARKMSG(psz, x) TraceMsg(TF_SHDTHREAD, "ief MPARK::%s %x", psz, x)
// File name and 32 for the rest of the title string
#define TITLE_LEN (256 + 32)
#define MAX_DISPLAY_LEN 96
#define MAX_SCHEME_STRING 16
class CDownload : public IBindStatusCallback
, public IAuthenticate
, public IServiceProvider
, public IHttpNegotiate
{
public:
// *** IUnknown methods ***
virtual STDMETHODIMP QueryInterface(REFIID riid, void ** ppvObj);
virtual STDMETHODIMP_(ULONG) AddRef(void) ;
virtual STDMETHODIMP_(ULONG) Release(void);
// *** IAuthenticate ***
virtual STDMETHODIMP Authenticate(
HWND *phwnd,
LPWSTR *pszUsername,
LPWSTR *pszPassword);
// *** IServiceProvider ***
virtual STDMETHODIMP QueryService(REFGUID guidService,
REFIID riid, void **ppvObj);
// *** IBindStatusCallback ***
virtual STDMETHODIMP OnStartBinding(
/* [in] */ DWORD grfBSCOption,
/* [in] */ IBinding *pib);
virtual STDMETHODIMP GetPriority(
/* [out] */ LONG *pnPriority);
virtual STDMETHODIMP OnLowResource(
/* [in] */ DWORD reserved);
virtual STDMETHODIMP OnProgress(
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ ULONG ulStatusCode,
/* [in] */ LPCWSTR szStatusText);
virtual STDMETHODIMP OnStopBinding(
/* [in] */ HRESULT hresult,
/* [in] */ LPCWSTR szError);
virtual STDMETHODIMP GetBindInfo(
/* [out] */ DWORD *grfBINDINFOF,
/* [unique][out][in] */ BINDINFO *pbindinfo);
virtual STDMETHODIMP OnDataAvailable(
/* [in] */ DWORD grfBSCF,
/* [in] */ DWORD dwSize,
/* [in] */ FORMATETC *pformatetc,
/* [in] */ STGMEDIUM *pstgmed);
virtual STDMETHODIMP OnObjectAvailable(
/* [in] */ REFIID riid,
/* [iid_is][in] */ IUnknown *punk);
/* *** IHttpNegotiate *** */
virtual STDMETHODIMP BeginningTransaction(LPCWSTR szURL, LPCWSTR szHeaders,
DWORD dwReserved, LPWSTR *pszAdditionalHeaders);
virtual STDMETHODIMP OnResponse(DWORD dwResponseCode,
LPCWSTR szResponseHeaders,
LPCWSTR szRequestHeaders,
LPWSTR *pszAdditionalRequestHeaders);
protected:
LONG _cRef;
IBinding* _pib;
IBindCtx* _pbc;
HWND _hDlg;
HWND _hwndToolTips;
BOOL _fSaveAs : 1;
BOOL _fGotFile : 1;
BOOL _fFirstTickValid : 1;
BOOL _fEndDialogCalled : 1;
BOOL _fDontPostQuitMsg : 1; // Posts WM_QUIT message in destructor
BOOL _fCallVerifyTrust : 1;
BOOL _fStrsLoaded : 1;
BOOL _fSafe : 1; // no need to call IsSafe dialog
BOOL _fDownloadStarted : 1; // Have we started receiving data
BOOL _fDownloadCompleted : 1; // We have received BSCF_LASTDATANOTIFICATION
BOOL _fDeleteFromCache : 1; // Delete the file from cache when done
BOOL _fWriteHistory : 1; // Should it be written to history? (SECURITY)
BOOL _fDismissDialog : 1;
BOOL _fUTF8Enabled : 1;
DWORD _dwFirstTick;
DWORD _dwFirstSize;
DWORD _dwTotalSize; // Size of file downloaded so far
DWORD _dwFileSize; // Size of file to download
HICON _hicon;
TCHAR _szPath[MAX_PATH]; // ok with MAX_PATH
TCHAR _szSaveToFile[MAX_PATH]; // File to Save to
TCHAR _szEstimateTime[MAX_PATH]; // ok with MAX_PATH
TCHAR _szBytesCopied[MAX_PATH]; // ok with MAX_PATH
TCHAR _szTitlePercent[TITLE_LEN];
TCHAR _szTitleBytes[TITLE_LEN];
TCHAR _szTransferRate[TITLE_LEN];
TCHAR _szURL[MAX_URL_STRING];
TCHAR _szScheme[MAX_SCHEME_STRING];
TCHAR _szDisplay[MAX_DISPLAY_LEN]; // URL to be displayed
TCHAR _szDefDlgTitle[256];
TCHAR _szExt[10];
DWORD _grfBINDF;
BINDINFO* _pbinfo;
LPWSTR _pwzHeaders;
IMoniker* _pmk; // WARNING: No ref-count (only for modal)
LPWSTR _pwszDisplayName;
DWORD _dwVerb;
UINT _uiCP; // Code page
DWORD _dwOldEst;
ULONG _ulOldProgress;
DWORD _dwOldRate;
DWORD _dwOldPcent;
DWORD _dwOldCur;
void SetMoniker(IMoniker* pmk) { _pmk=pmk; }
BOOL _IsModal(void) { return (bool)_pmk; }
virtual ~CDownload();
friend INT_PTR CALLBACK DownloadDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
friend INT_PTR CALLBACK SafeOpenDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
UINT _MayAskUserIsFileSafeToOpen(void);
BOOL _GetSaveLocation(void);
BOOL _SaveFile(VOID);
VOID _DeleteFromCache(VOID);
HRESULT PerformVirusScan(LPCTSTR szFileName);
public:
CDownload(BOOL fSaveAs = FALSE, LPWSTR pwzHeaders = NULL,
DWORD grfBINDF = BINDF_ASYNCHRONOUS, BINDINFO* pbinfo = NULL,
BOOL fSafe = FALSE, DWORD dwVerb = BINDVERB_GET, LPCTSTR pszRedir=NULL, UINT uiCP=CP_ACP);
static void OpenUI(IMoniker* pmk, IBindCtx *pbc, BOOL fSaveAs = FALSE, BOOL fSafe = FALSE, LPWSTR pwzHeaders = NULL, DWORD dwVerb = BINDVERB_GET, DWORD grfBINDF = 0, BINDINFO* pbinfo = NULL, LPCTSTR pszRedir=NULL, UINT uiCP=CP_ACP);
HRESULT StartBinding(IMoniker* pmk, IBindCtx *pbc = NULL);
void EndDialogDLD(UINT id);
void ShowStats(void);
BOOL SetDismissDialogFlag(BOOL fDismiss) { return(_fDismissDialog = fDismiss); }
BOOL GetDismissDialogFlag(void) { return(_fDismissDialog); }
#ifdef USE_LOCKREQUEST
HRESULT LockRequestHandle(VOID);
#endif
};
CDownload::CDownload(BOOL fSaveAs, LPWSTR pwzHeaders, DWORD grfBINDF, BINDINFO* pbinfo, BOOL fSafe, DWORD dwVerb, LPCTSTR pszRedir, UINT uiCP)
: _cRef(1), _fSaveAs(fSaveAs), _fWriteHistory(1),
_grfBINDF(grfBINDF), _pbinfo(pbinfo), _fSafe(fSafe), _pwzHeaders(pwzHeaders), _dwVerb(dwVerb), _uiCP(uiCP)
{
ASSERT(_fStrsLoaded == FALSE);
ASSERT(_fDownloadStarted == FALSE);
ASSERT(_fDownloadCompleted == FALSE);
ASSERT(_fGotFile == FALSE);
ASSERT(_fUTF8Enabled == FALSE);
ASSERT(_hDlg == NULL);
ASSERT(_pwszDisplayName == NULL);
ASSERT(_dwTotalSize == 0);
ASSERT(_dwFileSize == 0);
ASSERT(_dwFirstTick == 0);
ASSERT(_ulOldProgress == 0);
ASSERT(_dwOldRate == 0);
ASSERT(_dwOldPcent == 0);
ASSERT(_dwOldCur == 0);
_dwOldEst = 0xffffffff;
if (pszRedir && lstrlen(pszRedir))
StrCpyN(_szURL, pszRedir, ARRAYSIZE(_szURL) - 1); // -1 ???
TraceMsg(TF_SHDLIFE, "CDownload::CDownload being constructed");
}
BOOL IsProgIDInList(LPCTSTR pszProgID, LPCTSTR pszExt, const LPCTSTR *arszList, UINT nExt)
{
TCHAR szClassName[MAX_PATH];
DWORD cbSize = SIZEOF(szClassName);
if ((!pszProgID || !*pszProgID) && (!pszExt || !*pszExt))
return FALSE;
if (!pszProgID || !*pszProgID)
{
if (ERROR_SUCCESS == SHGetValue(HKEY_CLASSES_ROOT, pszExt, NULL, NULL, szClassName, &cbSize))
pszProgID = szClassName;
else
return FALSE;
}
for (UINT n = 0; n < nExt; n++)
{
DWORD dwValueType;
TCHAR szTempID[MAX_PATH];
szTempID[0] = TEXT('\0');
ULONG cb = ARRAYSIZE(szTempID)*sizeof(TCHAR);
if (ERROR_SUCCESS == SHGetValue(HKEY_CLASSES_ROOT, arszList[n], NULL, &dwValueType, (PBYTE)szTempID, &cb))
if (!StrCmpI(pszProgID, szTempID))
return TRUE;
}
return FALSE;
}
void ProcessStartbindingError(HWND hWnd, LPTSTR pszTitle, LPTSTR pszText, UINT uiFlag, HRESULT hres)
{
if (E_ACCESSDENIED == hres)
{
pszText = MAKEINTRESOURCE(IDS_DOWNLOADDISALLOWED);
pszTitle = MAKEINTRESOURCE(IDS_SECURITYALERT);
uiFlag = MB_ICONWARNING;
}
MLShellMessageBox(hWnd, pszText, pszTitle,
MB_OK | MB_SETFOREGROUND | uiFlag );
if (IsValidHWND(hWnd))
FORWARD_WM_COMMAND(hWnd, IDCANCEL, NULL, 0, PostMessage);
}
HRESULT SelectPidlInSFV(IShellFolderViewDual *psfv, LPCITEMIDLIST pidl, DWORD dwOpts)
{
HRESULT hres = E_FAIL;
VARIANT var;
if (InitVariantFromIDList(&var, pidl))
{
hres = psfv->SelectItem(&var, dwOpts);
VariantClear(&var);
}
return hres;
}
void OpenFolderPidl(LPCITEMIDLIST pidl)
{
SHELLEXECUTEINFO shei = { 0 };
shei.cbSize = sizeof(shei);
shei.fMask = SEE_MASK_INVOKEIDLIST;
shei.nShow = SW_SHOWNORMAL;
shei.lpIDList = (LPITEMIDLIST)pidl;
ShellExecuteEx(&shei);
}
HRESULT OpenContainingFolderAndGetShellFolderView(HWND hwnd, LPCITEMIDLIST pidlFolder, IShellFolderViewDual **ppsfv)
{
HRESULT hres;
*ppsfv = NULL;
IWebBrowserApp *pauto;
hres = SHGetIDispatchForFolder(pidlFolder, &pauto);
if (SUCCEEDED(hres))
{
// We have IDispatch for window, now try to get one for
// the folder object...
HWND hwnd;
if (SUCCEEDED(pauto->get_HWND((LONG*)&hwnd)))
{
// Make sure we make this the active window
SetForegroundWindow(hwnd);
ShowWindow(hwnd, SW_SHOWNORMAL);
}
IDispatch * pautoDoc;
hres = pauto->get_Document(&pautoDoc);
if (SUCCEEDED(hres))
{
hres = pautoDoc->QueryInterface(IID_IShellFolderViewDual, (void **)ppsfv);
pautoDoc->Release();
}
pauto->Release();
}
return hres;
}
//
// Stolen (and modified) from shell\ext\mydocs2\prop.cpp which was from link.c in shell32.dll
//
void FindTarget(HWND hDlg, LPTSTR pPath)
{
USHORT uSave;
LPITEMIDLIST pidl = ILCreateFromPath( pPath );
if (!pidl)
return;
LPITEMIDLIST pidlLast = ILFindLastID(pidl);
// get the folder, special case for root objects (My Computer, Network)
// hack off the end if it is not the root item
if (pidl != pidlLast)
{
uSave = pidlLast->mkid.cb;
pidlLast->mkid.cb = 0;
}
else
uSave = 0;
LPITEMIDLIST pidlDesk;
if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOPDIRECTORY, &pidlDesk)))
{
BOOL fIsDesktopDir = pidlDesk && ILIsEqual(pidl, pidlDesk);
if (fIsDesktopDir || !uSave) // if it's in the desktop dir or pidl == pidlLast (uSave == 0 from above)
{
//
// It's on the desktop...
//
MLShellMessageBox(hDlg, (LPTSTR)IDS_ON_DESKTOP, (LPTSTR)IDS_FIND_TITLE,
MB_OK | MB_ICONINFORMATION | MB_APPLMODAL | MB_TOPMOST);
}
else
{
if (WhichPlatform() == PLATFORM_BROWSERONLY)
{
OpenFolderPidl(pidl);
}
else
{
IShellFolderViewDual *psfv;
if (SUCCEEDED(OpenContainingFolderAndGetShellFolderView(hDlg, uSave ? pidl : pidlDesk, &psfv)))
{
if (uSave)
pidlLast->mkid.cb = uSave;
SelectPidlInSFV(psfv, pidlLast, SVSI_SELECT | SVSI_FOCUSED | SVSI_DESELECTOTHERS | SVSI_ENSUREVISIBLE);
psfv->Release();
}
}
}
ILFree(pidlDesk);
}
ILFree(pidl);
}
BOOL SetExemptDelta(LPCTSTR pszURL, DWORD dwExemptDelta)
{
BOOL fRC;
INTERNET_CACHE_ENTRY_INFO icei;
icei.dwStructSize = SIZEOF(icei);
icei.dwExemptDelta = dwExemptDelta; // Number of seconds from last access time to keep entry
// Retry setting the exempt delta if it fails since wininet may have either not have created the
// entry yet or might have it locked.
for(int i = 0; i < 5; i++)
{
if (fRC = SetUrlCacheEntryInfo(pszURL, &icei, CACHE_ENTRY_EXEMPT_DELTA_FC))
break;
Sleep(1000);
}
return(fRC);
}
INT_PTR CALLBACK DownloadDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static fInBrowseDir = FALSE;
CDownload* pdld = (CDownload*) GetWindowLongPtr(hDlg, DWLP_USER);
DWORD dwExStyle = 0;
TCHAR szURL[MAX_URL_STRING]; // make copies since EndDialog will delete CDownload obj
BOOL fDownloadAborted;
#ifdef MAINWIN
dwExStyle |= WS_EX_MW_UNMANAGED_WINDOW;
#endif
DWNLDMSG4("DownloadDlgProc ", uMsg, wParam, lParam);
if((pdld == NULL) && (uMsg != WM_INITDIALOG))
{
RIPMSG(TRUE, "CDownload freed (pdld == NULL) && (uMsg != WM_INITDIALOG)");
return FALSE;
}
switch(uMsg) {
case WM_INITDIALOG:
{
TCHAR szYesNo[20];
DWORD dwType = REG_SZ;
DWORD dwSize = ARRAYSIZE(szYesNo);
if(lParam == NULL)
return FALSE;
SetWindowLongPtr(hDlg, DWLP_USER, lParam);
pdld = (CDownload*)lParam;
pdld->_hDlg = hDlg;
EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
EnableWindow(GetDlgItem(hDlg, IDD_OPENFILE), FALSE);
EnableWindow(GetDlgItem(hDlg, IDD_BROWSEDIR), FALSE);
// On BiDi Loc Win98 & NT5 mirroring will take care of that
// Need to fix only on BiBi Win95 Loc
if (g_bBiDiW95Loc)
{
SetWindowBits(GetDlgItem(hDlg, IDD_DIR), GWL_EXSTYLE, WS_EX_RTLREADING, WS_EX_RTLREADING);
}
MLLoadString(IDS_DEFDLGTITLE, pdld->_szDefDlgTitle, ARRAYSIZE(pdld->_szDefDlgTitle));
if (pdld->_hwndToolTips = CreateWindowEx(dwExStyle, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
hDlg, NULL, HINST_THISDLL, NULL))
{
TOOLINFO ti;
ti.cbSize = SIZEOF(ti);
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.hwnd = hDlg;
ti.uId = (UINT_PTR) GetDlgItem(hDlg, IDD_NAME);
ti.lpszText = LPSTR_TEXTCALLBACK;
ti.hinst = HINST_THISDLL;
GetWindowRect((HWND)ti.uId, &ti.rect);
SendMessage(pdld->_hwndToolTips, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti);
}
// make sure we support cross-lang platform
SHSetDefaultDialogFont(hDlg, IDD_NAME);
pdld->SetDismissDialogFlag(FALSE);
if ( SHRegGetUSValue( TEXT("Software\\Microsoft\\Internet Explorer\\Main"),
TEXT("NotifyDownloadComplete"),
&dwType, (LPVOID)szYesNo, &dwSize, FALSE, NULL, 0 ) == ERROR_SUCCESS )
{
pdld->SetDismissDialogFlag(!StrCmpI(szYesNo, TEXT("No")));
}
CheckDlgButton(hDlg, IDD_DISMISS, pdld->GetDismissDialogFlag());
DWNLDMSG("DownloadDlgProc", "Got WM_INITDIALOG");
Animate_OpenEx(GetDlgItem(hDlg, IDD_ANIMATE), HINST_THISDLL, MAKEINTRESOURCE(IDA_DOWNLOAD));
ShowWindow(GetDlgItem(hDlg, IDD_DOWNLOADICON), SW_HIDE);
g_hCritOpMutex = CreateMutexA(NULL, TRUE, "CritOpMutex");
// Automatically start binding if we are posting synchronously.
if (pdld->_IsModal())
{
HRESULT hres = pdld->StartBinding(pdld->_pmk);
ASSERT(pdld->_pmk);
if (FAILED(hres))
ProcessStartbindingError(hDlg, MAKEINTRESOURCE(IDS_DOWNLOADFAILED),
pdld->_szDisplay, MB_ICONWARNING, hres);
}
return TRUE;
}
case WM_SIZE:
if ((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))
SetWindowText(hDlg, pdld->_szDefDlgTitle);
break;
case WM_NOTIFY:
{
LPTOOLTIPTEXT lpTT = (LPTOOLTIPTEXT) lParam;
if (lpTT->hdr.code == TTN_NEEDTEXT)
{
lpTT->lpszText = pdld->_szURL;
lpTT->hinst = NULL;
}
}
break;
case WM_COMMAND:
DWNLDMSG2("DownloadDlgProc WM_COMMAND id =", GET_WM_COMMAND_ID(wParam, lParam));
switch (GET_WM_COMMAND_ID(wParam, lParam)) {
case IDD_SAVEAS:
if (pdld)
{
BOOL fSuccess = FALSE;
// Prevent someone from canceling dialog while the shell copy etc. is going on
EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
// If zone check fails or if we found virus, bail out and remove file from cache.
if (pdld->PerformVirusScan(pdld->_szPath) != S_OK)
{
pdld->_fDeleteFromCache = TRUE;
pdld->EndDialogDLD(IDCANCEL);
break;
}
fSuccess = pdld->_SaveFile();
AddUrlToUrlHistoryStg(pdld->_pwszDisplayName, NULL, NULL, pdld->_fWriteHistory, NULL, NULL, NULL);
// BUGBUG -- BharatS --- Only add to history if Visible ?
IEPlaySound(TEXT("SystemAsterisk"), TRUE);
if (fSuccess)
{
if (pdld->SetDismissDialogFlag(IsDlgButtonChecked(hDlg, IDD_DISMISS) == BST_CHECKED))
{
StrCpyN(szURL, pdld->_szURL, ARRAYSIZE(szURL));
pdld->EndDialogDLD(IDCANCEL);
SetExemptDelta(szURL, 0);
}
else
{
TCHAR szStr[MAX_PATH];
if (MLLoadString(IDS_CLOSE, szStr, ARRAYSIZE(szStr)))
{
SetWindowText(GetDlgItem(hDlg, IDCANCEL), szStr);
}
ShowWindow(GetDlgItem(hDlg, IDD_ANIMATE), SW_HIDE);
ShowWindow(GetDlgItem(hDlg, IDD_DNLDESTTIME), SW_HIDE);
ShowWindow(GetDlgItem(hDlg, IDD_DNLDCOMPLETEICON), SW_SHOW);
ShowWindow(GetDlgItem(hDlg, IDD_DNLDCOMPLETETEXT), SW_SHOW);
ShowWindow(GetDlgItem(hDlg, IDD_DNLDTIME), SW_SHOW);
MLLoadString(IDS_SAVED, szStr, ARRAYSIZE(szStr));
SetDlgItemText(hDlg, IDD_OPENIT, szStr);
MLLoadString(IDS_DOWNLOADCOMPLETE, szStr, ARRAYSIZE(szStr));
SetWindowText(hDlg, szStr);
EnableWindow(GetDlgItem(hDlg, IDD_OPENFILE), TRUE);
EnableWindow(GetDlgItem(hDlg, IDD_BROWSEDIR), TRUE);
pdld->ShowStats();
}
}
EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE);
}
break;
case IDCANCEL: // Cancel on abort, Close on dismiss
if (pdld && IsWindowEnabled(GetDlgItem(hDlg, IDCANCEL)))
{
fDownloadAborted = pdld->_fDownloadStarted && !pdld->_fDownloadCompleted;
StrCpyN(szURL, pdld->_szURL, ARRAYSIZE(szURL));
if (pdld->_pib)
{
HRESULT hresT;
hresT = pdld->_pib->Abort();
TraceMsg(DM_DOWNLOAD, "DownloadDlgProc::IDCANCEL: called _pib->Abort() hres=%x", pdld->_pib, hresT);
}
pdld->EndDialogDLD(IDCANCEL);
// Download was canceled. Increase exempt time to keep downloaded a bit in case download is resumed
SetExemptDelta(szURL, fDownloadAborted ?60*60*24 :0);
}
break;
case IDD_BROWSEDIR:
if (!fInBrowseDir)
{
fInBrowseDir = TRUE;
FindTarget(hDlg, pdld->_szSaveToFile);
// Since EndDialogDLD will probably release our structure...
HWND hwndToolTips = pdld->_hwndToolTips;
pdld->_hwndToolTips = NULL;
pdld->EndDialogDLD(IDOK);
if (IsWindow(hwndToolTips))
DestroyWindow(hwndToolTips);
fInBrowseDir = FALSE;
}
#if DEBUG
else
{
TraceMsg(DM_DOWNLOAD, "DownloadDlgProc rcvd IDD_BROWSEDIR msg while already processing IDD_BROWSEDIR");
}
#endif
break;
case IDD_OPENFILE:
StrCpyN(pdld->_szPath, pdld->_szSaveToFile, ARRAYSIZE(pdld->_szPath));
case IDOK:
ShowWindow(GetDlgItem(hDlg, IDD_DISMISS), SW_HIDE);
if (pdld)
{
if (pdld->_fGotFile)
{
// If zone check fails or if we found virus, bail out and remove file from cache.
if ( pdld->PerformVirusScan(pdld->_szPath) != S_OK )
{
pdld->_fDeleteFromCache = TRUE;
}
else
{
if ((GET_WM_COMMAND_ID(wParam, lParam) == IDD_OPENFILE) || !IsAssociatedWithIE(pdld->_szPath))
{
TCHAR szQuotedPath[MAX_PATH];
StrCpyN(szQuotedPath, pdld->_szPath, MAX_PATH);
if (PLATFORM_INTEGRATED == WhichPlatform())
PathQuoteSpaces(szQuotedPath);
SHELLEXECUTEINFO sei = { SIZEOF(SHELLEXECUTEINFO),
0, hDlg, NULL, szQuotedPath, NULL, NULL, SW_SHOWNORMAL, NULL};
#ifdef UNIX
// Without this mask shell execute trys to open the
// default context menu option. This is not fully
// working in shell32.
sei.fMask |= SEE_MASK_FORCENOIDLIST;
#endif
if (!ShellExecuteEx(&sei)) {
DWNLDMSG2("ShellExecute failed", GetLastError());
}
}
else
{
// BUGBUG: We won't hit this assert if URLMON tells us
// the right extension and we CoCreateInstance
// an HTML viewer correctly.
ASSERT(0);
}
}
}
if (!pdld->_fDeleteFromCache)
AddUrlToUrlHistoryStg(pdld->_pwszDisplayName, NULL, NULL, pdld->_fWriteHistory, NULL, NULL, NULL);
// BUGBUG-- BharatS Only Add to History if Visible ?
// Since EndDialogDLD will probably release our structure...
HWND hwndToolTips = pdld->_hwndToolTips;
pdld->_hwndToolTips = NULL;
StrCpyN(szURL, pdld->_szURL, ARRAYSIZE(szURL));
pdld->EndDialogDLD(!pdld->_fDeleteFromCache ?IDOK :IDCANCEL);
if (IsWindow(hwndToolTips))
DestroyWindow(hwndToolTips);
SetExemptDelta(szURL, 0);
}
break;
}
break;
case WM_ACTIVATE:
if (pdld && pdld->_IsModal())
return FALSE;
else {
// There can be race conditions here. If the WA_ACTIVATE messages came in reverse
// order, we might end up setting up the wrong hDlg as the active window. As of right now,
// the only thing g_hDlgActive is being used for is for the IsDialogMessage in
// CDownload_MayProcessMessage. And since there is only one tab-able control in this
// dialog, a wrong hDlg in the g_hDlgActive should not hurt.
ENTERCRITICAL;
if (LOWORD(wParam) == WA_INACTIVE)
{
if (g_hDlgActive == hDlg)
{
MDLGMSG(TEXT("being inactivated"), hDlg);
g_hDlgActive = NULL;
}
}
else
{
MDLGMSG(TEXT("being activated"), hDlg);
g_hDlgActive = hDlg;
}
LEAVECRITICAL;
}
break;
case WM_NCDESTROY:
MDLGMSG(TEXT("being destroyed"), hDlg);
ASSERT((pdld && pdld->_IsModal()) || (g_hDlgActive != hDlg));
SetWindowLongPtr(hDlg, DWLP_USER, NULL);
return FALSE;
case WM_DESTROY:
SHRemoveDefaultDialogFont(hDlg);
return FALSE;
default:
return FALSE;
}
return TRUE;
}
void CDownload::ShowStats(void)
{
TCHAR szStr[MAX_PATH];
TCHAR szBytes[MAX_BYTES_STRLEN];
TCHAR szTime[MAX_BYTES_STRLEN];
TCHAR *pszTime = szTime;
DWORD dwSpent = (GetTickCount() - _dwFirstTick);
SetDlgItemText(_hDlg, IDD_NAME, _szDisplay);
MLLoadString(IDS_BYTESTIME, _szBytesCopied, ARRAYSIZE(_szBytesCopied));
StrFromTimeInterval(szTime, ARRAYSIZE(szTime), (dwSpent < 1000) ?1000 :dwSpent, 3);
while(pszTime && *pszTime && *pszTime == TEXT(' '))
pszTime++;
_FormatMessage(_szBytesCopied, szStr, ARRAYSIZE(szStr),
StrFormatByteSize(_dwTotalSize, szBytes, MAX_BYTES_STRLEN), pszTime);
SetDlgItemText(_hDlg, IDD_TIMEEST, szStr);
// division below requires at least 1/2 second to have elapsed.
if(dwSpent < 500)
dwSpent = 500;
_FormatMessage(_szTransferRate, szStr, ARRAYSIZE(szStr),
StrFormatByteSize(_dwTotalSize / ((dwSpent+500)/1000), szBytes, MAX_BYTES_STRLEN));
SetDlgItemText(_hDlg, IDD_TRANSFERRATE, szStr);
SetForegroundWindow(_hDlg);
}
void CDownload::EndDialogDLD(UINT id)
{
ASSERT(!_fEndDialogCalled);
_fEndDialogCalled = TRUE;
DWNLDMSG2("EndDialogDLD cRef ==", _cRef);
TraceMsg(TF_SHDREF, "CDownload::EndDialogDLD called when _cRef=%d", _cRef);
_fDismissDialog = (IsDlgButtonChecked(_hDlg, IDD_DISMISS) == BST_CHECKED);
if (SHRegSetUSValue(TEXT("Software\\Microsoft\\Internet Explorer\\Main"),
TEXT("NotifyDownloadComplete"),
#ifndef UNIX
REG_SZ, _fDismissDialog ?TEXT("no") :TEXT("yes"), _fDismissDialog ?sizeof(TEXT("no")-sizeof(TCHAR)) :sizeof(TEXT("yes")-sizeof(TCHAR)), SHREGSET_FORCE_HKCU) != ERROR_SUCCESS)
#else
REG_SZ, _fDismissDialog ?TEXT("no") :TEXT("yes"), _fDismissDialog ?(sizeof(TEXT("no"))-sizeof(TCHAR)) :(sizeof(TEXT("yes"))-sizeof(TCHAR)), SHREGSET_FORCE_HKCU) != ERROR_SUCCESS)
#endif
{
DWNLDMSG2("SHRegSetUSValue NotifyDownloadComplete failed", GetLastError());
}
// HACK: USER does not send us WM_ACTIVATE when this dialog is
// being destroyed when it was activated. We need to work around
// this bug(?) by cleaning up g_hDlgActive.
if (g_hDlgActive == _hDlg)
{
MDLGMSG(TEXT("EndDialogDLD putting NULL in g_hDlgActive"), _hDlg);
g_hDlgActive = NULL;
}
DestroyWindow(_hDlg);
Release();
}
#ifdef UNIX
extern "C" LONG SHRegQueryValueExW(HKEY hKey,LPCTSTR lpValueName,LPDWORD lpReserved ,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData);
#endif
#define SZEXPLORERKEY TEXT("Software\\Microsoft\\Internet Explorer")
#define SZDOWNLOADDIRVAL TEXT("Download Directory")
// _GetSaveLocation
// - Tries to get the current download directory from the registry
// default is the Desktop
// - Shows the FileSave Dialog
// - If the user changed the download location, save that off into
// the registry for future downloads
// - _szSaveToFile is updated (this will be used by _SaveFile()
//
// Returns TRUE, if successfully done.
//
BOOL _GetSaveLocation(HWND hDlg, LPTSTR pszPath, LPTSTR pszExt, LPTSTR pszSaveToFile, UINT cchSaveToFile, BOOL fUTF8Enabled, UINT uiCP)
{
BOOL fRet = FALSE;
TCHAR * pszSaveTo = NULL;
HKEY hKey;
BOOL fRegFileType = FALSE;
TCHAR szDownloadDir[MAX_PATH];
TCHAR szBuffer[MAX_PATH];
TCHAR szTemp[40];
LPTSTR pszWalk = szBuffer;
int cchWalk = ARRAYSIZE(szBuffer);
int cch;
szDownloadDir[0] = 0;
// If we don't have a download directory in the registry, download to the desktop
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, SZEXPLORERKEY, 0, KEY_READ, &hKey))
{
DWORD dwType, cbData = SIZEOF(szDownloadDir);
#ifndef UNIX
RegQueryValueEx(hKey, SZDOWNLOADDIRVAL, NULL, &dwType, (LPBYTE)szDownloadDir, &cbData);
#else
SHRegQueryValueExW(hKey, SZDOWNLOADDIRVAL, NULL, &dwType, (LPBYTE)szDownloadDir, &cbData);
#endif //UNIX
RegCloseKey(hKey);
}
if (szDownloadDir[0] == 0)
SHGetSpecialFolderPath(NULL, szDownloadDir, CSIDL_DESKTOPDIRECTORY, FALSE);
// Get the file name. If there is no filename. create one called using the string resource in IDS_DOCUMENT
pszSaveTo = PathFindFileName(pszPath);
if (pszSaveTo)
{
DWORD cchData = cchSaveToFile;
// Unescape the filename suggested by wininet.
if(PrepareURLForDisplayUTF8(pszSaveTo, pszSaveToFile, &cchData, fUTF8Enabled) != S_OK)
StrCpyN(pszSaveToFile, pszSaveTo, cchSaveToFile);
// Strip out any path that may have been encoded
TCHAR * pszSaveToDst = pszSaveToFile;
pszSaveTo = PathFindFileName(pszSaveToFile);
if (pszSaveTo != pszSaveToFile)
{
while(*pszSaveTo)
*pszSaveToDst++ = *pszSaveTo++;
*pszSaveToDst = *pszSaveTo;
}
// Strip out the the cache's typical decoration of "(nn)"
PathUndecorate (pszSaveToFile);
}
else
MLLoadString(IDS_DOCUMENT, pszSaveToFile, cchSaveToFile);
if(!g_fRunningOnNT) // Win9x isn't able to deal with DBCS chars in edit controls when UI lang is non-native OS lang
{
CHAR szBufA[MAX_PATH*2];
int iRC = WideCharToMultiByte(CP_ACP, 0, pszSaveToFile, -1, szBufA,
ARRAYSIZE(szBufA), NULL, NULL);
if(iRC == 0) // If we are unable to convert using system code page
*pszSaveToFile = TEXT('\0'); // make suggested file name blank
}
OPENFILENAME OFN = {0};
OFN.lStructSize = sizeof(OPENFILENAME);
OFN.hwndOwner = hDlg;
OFN.nMaxFile = cchSaveToFile;
OFN.lpstrInitialDir = szDownloadDir;
OFN.lpstrFile = pszSaveToFile;
OFN.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER |
OFN_NOREADONLYRETURN | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
if (!pszExt || !*pszExt)
pszExt = PathFindExtension(pszPath);
if (pszExt && *pszExt)
OFN.lpstrDefExt = pszExt;
// Try to get the file type name from the registry. To add to the filter pair strings
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, pszExt, 0, KEY_READ, &hKey))
{
DWORD dwType, cbData = SIZEOF(szBuffer);
fRegFileType = (ERROR_SUCCESS == RegQueryValueEx(hKey, NULL, NULL, &dwType, (LPBYTE)szBuffer, &cbData));
RegCloseKey(hKey);
}
if (fRegFileType)
{
fRegFileType = FALSE;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, szBuffer, 0, KEY_READ, &hKey))
{
DWORD dwType, cbData = sizeof(szBuffer);
szBuffer[0] = 0;
fRegFileType = ERROR_SUCCESS == RegQueryValueEx(hKey, NULL, NULL, &dwType, (LPBYTE)szBuffer, &cbData);
if (fRegFileType)
{
// Now tack on the second part of the filter pair
int cchBuffer = lstrlen(szBuffer) + 1;
pszWalk = szBuffer + cchBuffer;
cchWalk = ARRAYSIZE(szBuffer) - cchBuffer;
StrCpyN(pszWalk, TEXT("*"), cchWalk);
StrCatBuff(pszWalk, pszExt, cchWalk);
}
RegCloseKey(hKey);
}
cch = lstrlen(pszWalk);
}
// There was no registry entry for the file type or the entry did not have a default value
// So create the file name type - "<file extension> DOCUMENT"
if (!fRegFileType || !(*szBuffer))
{
szBuffer[0] = 0;
pszWalk = szBuffer;
cchWalk = ARRAYSIZE(szBuffer);
MLLoadString(IDS_EXTDOCUMENT, szTemp, ARRAYSIZE(szTemp));
cch = wnsprintf(pszWalk, cchWalk, szTemp, pszExt, TEXT('\0'), pszExt);
}
// Add in the pair for "*.* All files"
pszWalk += (cch + 1);
cchWalk -= cch;
MLLoadString(IDS_ALLFILES, szTemp, ARRAYSIZE(szTemp));
StrCpyN(pszWalk, szTemp, cchWalk);
cch = lstrlen(pszWalk) + 1;
pszWalk += cch;
cchWalk -= cch;
StrCpyN(pszWalk, ALLFILE_WILDCARD, cchWalk);
cch = (lstrlen( ALLFILE_WILDCARD )+1); //Add the second NULL to the end of the string
pszWalk += cch;
cchWalk -= cch;
if (cchWalk > 0)
*pszWalk = 0; //because we had some garbage put after memset.
OFN.lpstrFilter = szBuffer;
if ((fRet = (!SHIsRestricted2W(hDlg, REST_NoSelectDownloadDir, NULL, 0)))
&& (fRet = GetSaveFileName(&OFN)))
{
// If the download location was changed, save that off to the registry
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, SZEXPLORERKEY, 0, KEY_WRITE, &hKey))
{
StrCpyN(szBuffer, pszSaveToFile, ARRAYSIZE(szBuffer));
PathRemoveFileSpec(szBuffer);
if (szBuffer[0])
RegSetValueEx(hKey, SZDOWNLOADDIRVAL, 0, REG_SZ, (LPBYTE)szBuffer, CbFromCch(lstrlen(szBuffer) + 1));
RegCloseKey(hKey);
}
}
return fRet;
}
BOOL CDownload::_GetSaveLocation()
{
return ::_GetSaveLocation(_hDlg, _szPath, _szExt, _szSaveToFile, ARRAYSIZE(_szSaveToFile), _fUTF8Enabled, _uiCP);
}
BOOL CDownload::_SaveFile()
{
SHFILEOPSTRUCT fo = { _hDlg, FO_COPY, _szPath, _szSaveToFile, FOF_NOCONFIRMATION | FOF_NOCOPYSECURITYATTRIBS};
#ifdef UNIX
if (!CheckForValidSourceFile( _hDlg, _szPath, _szDisplay ))
return FALSE;
#endif
// If the file is in the cache, we probably want to delete it from the
// cache to free up some disk space rather than wait for it to be scavenged.
// This is best done after _pib->Release called from ~CDownload.
_fDeleteFromCache = TRUE;
// Copy the file (which is locked, so can't move it) to its target destination.
return !SHFileOperation(&fo);
}
VOID CDownload::_DeleteFromCache()
{
INTERNET_CACHE_CONFIG_INFO CCInfo;
DWORD dwCCIBufSize = sizeof(CCInfo);
// Obtain the cache directory path.
if (!GetUrlCacheConfigInfo (&CCInfo, &dwCCIBufSize, CACHE_CONFIG_CONTENT_PATHS_FC))
{
ASSERT(FALSE);
}
else if (0 == StrCmpNI (_szPath,
CCInfo.CachePaths[0].CachePath,
lstrlen(CCInfo.CachePaths[0].CachePath)))
{
// Attempt to delete the file from the cache only if resides under
// the cache directory, otherwise we could in theory nuke a preinstalled
// or edited cache entry. Here a prefix match is also a string prefix
// match since .CachePath will have a trailing slash ('/')
DeleteUrlCacheEntry(_szURL);
}
}
void CDownload::OpenUI(IMoniker* pmk, IBindCtx *pbc, BOOL fSaveAs, BOOL fSafe, LPWSTR pwzHeaders, DWORD dwVerb, DWORD grfBINDF, BINDINFO* pbinfo, LPCTSTR pszRedir, UINT uiCP)
{
TraceMsg(DM_DOWNLOAD, "CDownLoad::OpenUI called with fSaveAs=%d, verb=%d", fSaveAs, dwVerb);
// CDownload will take ownership pbinfo.
CDownload* pdld = new CDownload(fSaveAs, pwzHeaders, grfBINDF, pbinfo, fSafe, dwVerb, pszRedir, uiCP);
if (pdld)
{
HWND hwnd = CreateDialogParamWrap(MLGetHinst(),
MAKEINTRESOURCE(DLG_DOWNLOADPROGRESS), NULL, DownloadDlgProc, (LPARAM)pdld);
pwzHeaders = NULL; // Owner is now CDownload
DWNLDMSG2("CDownLoad_OpenUI dialog created", hwnd);
if (hwnd)
{
HRESULT hres = pdld->StartBinding(pmk, pbc);
if (FAILED(hres))
ProcessStartbindingError(hwnd, MAKEINTRESOURCE(IDS_DOWNLOADFAILED),
pdld->_szDisplay, MB_ICONWARNING, hres);
else
ShowWindow(hwnd, SW_SHOWNORMAL);
}
}
if (pwzHeaders)
CoTaskMemFree(pwzHeaders);
}
BOOL CDownload_MayProcessMessage(MSG* pmsg)
{
if (g_hDlgActive)
return IsDialogMessage(g_hDlgActive, pmsg);
return FALSE; // not processed
}
class CDownloadThreadParam {
#ifdef DEBUG
const DWORD* _pdwSigniture;
static const DWORD s_dummy;
#endif
public:
DWORD _dwVerb;
DWORD _grfBINDF;
BINDINFO *_pbinfo;
LPWSTR _pszDisplayName;
LPWSTR _pwzHeaders;
BOOL _fSaveAs;
BOOL _fSafe;
IStream *_pStream;
TCHAR _szRedirURL[MAX_URL_STRING];
UINT _uiCP;
~CDownloadThreadParam()
{
OleFree(_pszDisplayName);
if (_pwzHeaders)
CoTaskMemFree(_pwzHeaders);
if (_pStream)
_pStream->Release();
// CDownload releases our _pbinfo.
}
CDownloadThreadParam(LPWSTR pszDisplayName, LPWSTR pwzHeaders, BOOL fSaveAs, BOOL fSafe=FALSE, DWORD dwVerb=BINDVERB_GET, DWORD grfBINDF = 0, BINDINFO* pbinfo = NULL, LPCTSTR pszRedir=NULL, UINT uiCP=CP_ACP )
: _pszDisplayName(pszDisplayName), _fSaveAs(fSaveAs), _fSafe(fSafe), _pwzHeaders(pwzHeaders), _pStream(NULL), _dwVerb(dwVerb), _grfBINDF(grfBINDF), _pbinfo(pbinfo), _uiCP(uiCP)
{
#ifdef DEBUG
_pdwSigniture = &s_dummy;
#endif
if (pszRedir && lstrlen(pszRedir))
StrCpyN(_szRedirURL, pszRedir, MAX_URL_STRING - 1);
// CDownload releases our _pbinfo.
}
void SetStream(IStream *pStm)
{
if (_pStream)
{
_pStream->Release();
}
_pStream = pStm;
if (_pStream)
{
_pStream->AddRef();
}
}
};
DWORD CALLBACK IEDownload_ThreadProc(void *pv)
{
CDownloadThreadParam* pdtp = (CDownloadThreadParam*)pv;
HRESULT hr;
DebugMemLeak(DML_TYPE_THREAD | DML_BEGIN);
CoInitialize(0);
IBindCtx *pbc = NULL;
if (pdtp->_pStream)
{
pdtp->_pStream->AddRef();
hr = pdtp->_pStream->Seek(c_li0,STREAM_SEEK_SET,0);
hr = CoGetInterfaceAndReleaseStream(pdtp->_pStream, IID_IBindCtx, (void **)&pbc);
pdtp->SetStream(NULL);
}
if (pbc == NULL)
CreateBindCtx(0, &pbc);
hr = CDownLoad_OpenUIURL(pdtp->_pszDisplayName, pbc, pdtp->_pwzHeaders, TRUE, pdtp->_fSaveAs, pdtp->_fSafe,
pdtp->_dwVerb, pdtp->_grfBINDF, pdtp->_pbinfo, pdtp->_szRedirURL, pdtp->_uiCP);
if (SUCCEEDED(hr))
{
pdtp->_pwzHeaders = NULL; // CDownload owns freeing headers now
pdtp->_pbinfo = NULL; // CDownload owns freeing pbinfo now.
}
delete pdtp;
if (pbc)
{
pbc->Release();
pbc = NULL;
}
while (1)
{
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
// Note that for IE 3.0, the parking thread is also
// the owner of all modeless download dialog.
if (CDownload_MayProcessMessage(&msg))
continue;
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
WaitMessage();
}
CoUninitialize();
DebugMemLeak(DML_TYPE_THREAD | DML_END);
return 0;
}
#ifdef DEBUG
extern void remove_from_memlist(void *pv);
#endif
void CDownLoad_OpenUI(IMoniker* pmk, IBindCtx *pbc, BOOL fSync, BOOL fSaveAs, BOOL fSafe, LPWSTR pwzHeaders, DWORD dwVerb, DWORD grfBINDF, BINDINFO* pbinfo, LPCTSTR pszRedir, UINT uiCP)
{
TraceMsg(DM_DOWNLOAD, "CDownLoad_OpenUI called with fSync=%d fSaveAs=%d", fSync, fSaveAs);
ASSERT(dwVerb == BINDVERB_GET || dwVerb == BINDVERB_POST);
#ifdef UNIX
BOOL bReadOnly = FALSE;
unixGetWininetCacheLockStatus ( &bReadOnly, NULL );
if ( bReadOnly )
return;
#endif
if (fSync)
{
CDownload::OpenUI(pmk, pbc, fSaveAs, fSafe, pwzHeaders, dwVerb, grfBINDF, pbinfo, pszRedir, uiCP);
pwzHeaders = NULL; // CDownload now owns headers
return;
}
HRESULT hres = NOERROR;
if (pbc == NULL)
{
hres = CreateBindCtx(0, &pbc);
}
else
{
pbc->AddRef();
}
if (SUCCEEDED(hres))
{
LPWSTR pszDisplayName = NULL;
hres = pmk->GetDisplayName(pbc, NULL, &pszDisplayName);
if (SUCCEEDED(hres))
{
CDownloadThreadParam* pdtp = new CDownloadThreadParam(pszDisplayName, pwzHeaders, fSaveAs, fSafe, dwVerb, grfBINDF, pbinfo, pszRedir, uiCP);
if (pdtp)
{
pwzHeaders = NULL; // ownership is to CDTP
{
// Note: IAsyncBindCtx has identicial interface as IBindCtx
IBindCtx *pbcAsync = NULL;
HRESULT hr;
hr = pbc->QueryInterface(IID_IAsyncBindCtx, (void **)&pbcAsync);
if (SUCCEEDED(hr))
{
ASSERT(pbcAsync);
IStream *pStm = NULL;
hr = CoMarshalInterThreadInterfaceInStream(IID_IBindCtx, pbcAsync, &pStm);
#if defined(MAINWIN)
// This API is not yet implemented by MAINSOFT
// so it return NOERROR but no interface pointer.
// We need to put an extra check for this on UNIX
if (hr == NOERROR && pStm)
#else
if (hr == NOERROR)
#endif
{
pdtp->SetStream(pStm);
pStm->Release();
}
pbcAsync->Release();
}
}
if (SHCreateThread(IEDownload_ThreadProc, pdtp, CTF_PROCESS_REF, NULL))
{
remove_from_memlist(pdtp);
}
else
{
delete pdtp;
}
}
else
{
OleFree(pszDisplayName);
}
}
pbc->Release();
}
if (pwzHeaders)
CoTaskMemFree(pwzHeaders);
}
HRESULT CDownLoad_OpenUIURL(LPCWSTR pwszURL, IBindCtx *pbc, LPWSTR pwzHeaders, BOOL fSync,BOOL fSaveAs, BOOL fSafe, DWORD dwVerb, DWORD grfBINDF, BINDINFO* pbinfo, LPCTSTR pszRedir, UINT uiCP)
{
HRESULT hres;
ASSERT(pwszURL);
if (pwszURL)
{
IMoniker* pmk = NULL;
hres = CreateURLMoniker(NULL, pwszURL, &pmk);
if (SUCCEEDED(hres))
{
CDownLoad_OpenUI(pmk, pbc, fSync, fSaveAs, fSafe, pwzHeaders, dwVerb, grfBINDF, pbinfo, pszRedir, uiCP);
pwzHeaders = NULL; // CDownload now owns headers
pmk->Release();
hres = S_OK;
}
if (pwzHeaders)
CoTaskMemFree(pwzHeaders);
}
else
hres = E_INVALIDARG;
return hres;
}
HRESULT CDownload::StartBinding(IMoniker* pmk, IBindCtx *pbc)
{
ASSERT(_pbc==NULL);
HRESULT hres = NOERROR;
if (pbc == NULL)
{
hres = CreateBindCtx(0, &_pbc);
}
else
{
_pbc = pbc;
_pbc->AddRef();
}
if (SUCCEEDED(hres)){
hres = RegisterBindStatusCallback(_pbc, this, 0, 0);
if (SUCCEEDED(hres)) {
HRESULT hresT = pmk->GetDisplayName(_pbc, NULL, &_pwszDisplayName);
if (SUCCEEDED(hresT)){
TCHAR szBuf[MAX_PATH];
DWORD dwSize = ARRAYSIZE(szBuf);
int cch;
DWORD dwPolicy = 0, dwContext = 0;
if (!(cch = lstrlen(_szURL)))
{
SHUnicodeToTChar(_pwszDisplayName, _szURL, ARRAYSIZE(_szURL));
}
TraceMsg(TF_SHDNAVIGATE, "CDld::StartBinding SHUnicodeToTChar returns %d (%s)", cch, _szURL);
// The URL from GetDisplayName() is always fully
// canonicalized and escaped. Prepare it for display.
if (PrepareURLForDisplay(_szURL, szBuf, &dwSize))
FormatUrlForDisplay(szBuf, _szDisplay, ARRAYSIZE(_szDisplay), TRUE, _uiCP);
else
FormatUrlForDisplay(_szURL, _szDisplay, ARRAYSIZE(_szDisplay), TRUE, _uiCP);
SetWindowText(GetDlgItem(_hDlg, IDD_NAME), _szDisplay);
ZoneCheckUrlEx(_szURL, &dwPolicy, SIZEOF(dwPolicy), &dwContext, SIZEOF(dwContext),
URLACTION_SHELL_FILE_DOWNLOAD, PUAF_NOUI, NULL);
dwPolicy = GetUrlPolicyPermissions(dwPolicy);
if ((dwPolicy == URLPOLICY_ALLOW) || (dwPolicy == URLPOLICY_QUERY)) {
IUnknown* punk = NULL;
hres = pmk->BindToStorage(_pbc, NULL, IID_IUnknown, (VOID**)&punk);
DWNLDMSG3("StartBinding pmk->BindToStorage returned", hres, punk);
if (SUCCEEDED(hres) || hres==E_PENDING){
hres = S_OK;
if (punk){
// BUGBUG: implement
ASSERT(0);
punk->Release();
}
} else {
TraceMsg(DM_ERROR, "CDld::StartBinding pmk->BindToStorage failed %x", hres);
}
} else {
hres = E_ACCESSDENIED;
TraceMsg(DM_ERROR, "CDld::StartBinding: Zone does not allow file download");
}
} else {
TraceMsg(DM_ERROR, "CDld::StartBinding pmk->GetDisplayName failed %x", hres);
}
} else {
TraceMsg(DM_ERROR, "CDld::StartBinding RegisterBSC failed %x", hres);
}
} else {
TraceMsg(DM_ERROR, "CDld::StartBinding CreateBindCtx failed %x", hres);
}
return hres;
}
HRESULT CDownload::QueryInterface(REFIID riid, void ** ppvObj)
{
static const QITAB qit[] = {
QITABENT(CDownload, IBindStatusCallback), // IID_IBindStatusCallback
QITABENT(CDownload, IAuthenticate), // IID_IAuthenticate
QITABENT(CDownload, IServiceProvider), // IID_IServiceProvider
QITABENT(CDownload, IHttpNegotiate), // IID_IHttpNegotiate
{ 0 },
};
return QISearch(this, qit, riid, ppvObj);
}
ULONG CDownload::AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG CDownload::Release()
{
DWNLDMSG2("CDownload::Release cRef=", _cRef);
if (InterlockedDecrement(&_cRef))
return _cRef;
CDownload* pdld = (CDownload*) GetWindowLongPtr(_hDlg, DWLP_USER);
if(pdld == this)
SetWindowLongPtr(_hDlg, DWLP_USER, NULL);
DWNLDMSG3("CDownload::Release delete this", pdld, this);
delete this;
return 0;
}
CDownload::~CDownload()
{
if (_pbinfo) {
ReleaseBindInfo(_pbinfo);
LocalFree(_pbinfo);
}
if (_pib) {
_pib->Release();
}
if (_pbc) {
_pbc->Release();
}
if (_hicon) {
DestroyIcon(_hicon);
}
if (_pwszDisplayName)
OleFree(_pwszDisplayName);
if (_fDeleteFromCache)
_DeleteFromCache();
if ( _pwzHeaders )
CoTaskMemFree( _pwzHeaders );
TraceMsg(TF_SHDLIFE, "CDownload::~CDownload being destructed");
TraceMsg(TF_SHDTHREAD, "CDownload::EndDialogDLD calling PostQuitMessage");
// Post the quit message ONLY if this flag is set. The constructor for the
// derived class CDownloadURL resets the flag to FALSE because it doesn't
// need any quit messages.
if (!_fDontPostQuitMsg)
PostQuitMessage(0);
}
#ifdef USE_LOCKREQUEST
HRESULT CDownload::LockRequestHandle(VOID)
{
HRESULT hres = E_FAIL;
HANDLE hLock;
if (_pib)
{
IWinInetInfo* pwinet;
hres = _pib->QueryInterface(IID_IWinInetInfo, (LPVOID*)&pwinet);
if (SUCCEEDED(hres))
{
DWORD cbSize = SIZEOF(HANDLE);
hres = pwinet->QueryOption(WININETINFO_OPTION_LOCK_HANDLE, &hLock, &cbSize);
pwinet->Release();
}
}
return hres;
}
#endif
HRESULT CDownload::OnStartBinding(
DWORD grfBSCOption, IBinding *pib)
{
DWNLDMSG3("OnStartBinding", _pib, pib);
if (_pib) {
_pib->Release();
}
_pib = pib;
if (_pib) {
_pib->AddRef();
}
SetQueryNetSessionCount(SESSION_INCREMENT);
_fUTF8Enabled = UTF8Enabled();
return S_OK;
}
HRESULT CDownload::GetPriority(LONG *pnPriority)
{
DWNLDMSG("GetPriority", "called");
*pnPriority = NORMAL_PRIORITY_CLASS;
return S_OK;
}
HRESULT CDownload::OnLowResource(DWORD reserved)
{
DWNLDMSG("OnLowResource", "called");
return S_OK;
}
#ifdef BETA1_DIALMON_HACK
#define AUTODIAL_MONITOR_CLASS_NAME TEXT("MS_AutodialMonitor")
#define WEBCHECK_MONITOR_CLASS_NAME TEXT("MS_WebcheckMonitor")
#define WM_DIALMON_FIRST WM_USER+100
// message sent to dial monitor app window indicating that there has been
// winsock activity and dial monitor should reset its idle timer
#define WM_WINSOCK_ACTIVITY WM_DIALMON_FIRST + 0
static const TCHAR szAutodialMonitorClass[] = AUTODIAL_MONITOR_CLASS_NAME;
static const TCHAR szWebcheckMonitorClass[] = WEBCHECK_MONITOR_CLASS_NAME;
#define MIN_ACTIVITY_MSG_INTERVAL 15000
VOID IndicateWinsockActivity(VOID)
{
// if there is an autodisconnect monitor, send it an activity message
// so that we don't get disconnected during long downloads. For perf's sake,
// don't send a message any more often than once every MIN_ACTIVITY_MSG_INTERVAL
// milliseconds (15 seconds). Use GetTickCount to determine interval;
// GetTickCount is very cheap.
DWORD dwTickCount = GetTickCount();
// Sharing this among multiple threads is OK
static DWORD dwLastActivityMsgTickCount = 0;
DWORD dwElapsed = dwTickCount - dwLastActivityMsgTickCount;
// have we sent an activity message recently?
if (dwElapsed > MIN_ACTIVITY_MSG_INTERVAL) {
HWND hwndMonitorApp = FindWindow(szAutodialMonitorClass,NULL);
if (hwndMonitorApp) {
PostMessage(hwndMonitorApp,WM_WINSOCK_ACTIVITY,0,0);
}
hwndMonitorApp = FindWindow(szWebcheckMonitorClass,NULL);
if (hwndMonitorApp) {
PostMessage(hwndMonitorApp,WM_WINSOCK_ACTIVITY,0,0);
}
// record the tick count of the last time we sent an
// activity message
dwLastActivityMsgTickCount = dwTickCount;
}
}
#endif
#define MAXCALCCNT 5
HRESULT CDownload::OnProgress(
ULONG ulProgress,
ULONG ulProgressMax,
ULONG ulStatusCode,
LPCWSTR pwzStatusText)
{
DWNLDMSG4("OnProgress", ulProgress, ulProgressMax, ulStatusCode);
TCHAR szBytes[MAX_BYTES_STRLEN];
TCHAR szBytesMax[MAX_BYTES_STRLEN];
TCHAR szBuf[MAX_PATH]; // OK with MAX_PATH
LPTSTR pszFileName = NULL;
HWND hwndShow;
DWORD dwCur;
switch(ulStatusCode)
{
case BINDSTATUS_BEGINDOWNLOADDATA:
hwndShow = GetDlgItem(_hDlg, ulProgressMax ? IDD_PROBAR : IDD_NOFILESIZE);
if (!IsWindowVisible(hwndShow))
{
ShowWindow(GetDlgItem(_hDlg, ulProgressMax ? IDD_NOFILESIZE : IDD_PROBAR), SW_HIDE);
ShowWindow(hwndShow, SW_SHOW);
}
_ulOldProgress = ulProgress;
// fall thru
case BINDSTATUS_DOWNLOADINGDATA:
case BINDSTATUS_ENDDOWNLOADDATA:
// Prevent machines with APM enabled from suspending during download
_SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
_dwFileSize = max(ulProgressMax, ulProgress);
//BUGBUG JEFFWE 4/15/96 Beta 1 Hack - every once in a while, send message
//BUGBUG to the hidden window that detects inactivity so that it doesn't
//BUGBUG think we are inactive during a long download
#ifdef BETA1_DIALMON_HACK
IndicateWinsockActivity();
#endif
// Sometimes OnProgress is called by folks who do not create a dialog
if (_hDlg )
{
if (!_fStrsLoaded)
{
MLLoadString(IDS_TITLEPERCENT, _szTitlePercent, ARRAYSIZE(_szTitlePercent));
MLLoadString(IDS_ESTIMATE, _szEstimateTime, ARRAYSIZE(_szEstimateTime));
MLLoadString(IDS_TITLEBYTES, _szTitleBytes, ARRAYSIZE(_szTitleBytes));
MLLoadString(IDS_BYTESCOPIED, _szBytesCopied, ARRAYSIZE(_szBytesCopied));
MLLoadString(IDS_TRANSFERRATE, _szTransferRate, ARRAYSIZE(_szTransferRate));
_fStrsLoaded = TRUE;
}
// Get the file name of the file being downloaded
pszFileName = PathFindFileName(_szURL);
dwCur = GetTickCount();
if(_dwOldCur == 0) // Allow the download to get started before displaying stats
_dwOldCur = dwCur;
if ((ulProgressMax > 0) && _fDownloadStarted)
{
if (_hDlg)
{
SendMessage(GetDlgItem(_hDlg, IDD_PROBAR), PBM_SETRANGE32, 0, _dwFileSize);
SendMessage(GetDlgItem(_hDlg, IDD_PROBAR), PBM_SETPOS, ulProgress, 0);
}
if (!_fFirstTickValid)
{
_dwFirstSize = ulProgress;
_fFirstTickValid = TRUE;
SetWindowText(GetDlgItem(_hDlg, IDD_NAME), _szDisplay);
}
else
{
if ((ulProgress - _dwFirstSize) && _hDlg)
{
// Recompute and display stats at least every second
if ((dwCur - _dwOldCur) >= 1000)
{
_dwOldCur = dwCur; // Save current tick count
TCHAR szTime[32];
DWORD dwSpent = ((dwCur - _dwFirstTick)+500) / 1000;
ULONG ulLeft = _dwFileSize - ulProgress;
DWORD dwRate = _dwOldRate;
dwRate = (ulProgress - _ulOldProgress) / (dwSpent ? dwSpent : 1);
TraceMsg(DM_PROGRESS, "OnProgress ulProgress=%d ulGot=%d dwSpent=%d ulLeft=%d", ulProgress, (ulProgress - _dwFirstSize), dwSpent, ulLeft);
// Compute & display estimated time left to download, bytes so far, total bytes
DWORD dwEst;
if (ulLeft > 0x100000L) // To avoid overflow, use KB for >1MB file.
dwEst = (ulLeft >> 10) / ((dwRate >> 10) ?(dwRate >> 10) :1);
else
dwEst = ulLeft / (dwRate ?dwRate :1);
if(dwEst == 0)
dwEst = 1;
TraceMsg(DM_PROGRESS, "OnProgress Estimated time left = %d", dwEst);
StrFromTimeInterval(szTime, ARRAYSIZE(szTime), dwEst * 1000, 3);
_FormatMessage(_szEstimateTime, szBuf, ARRAYSIZE(szBuf), szTime,
StrFormatByteSize(ulProgress, szBytes, MAX_BYTES_STRLEN),
StrFormatByteSize(_dwFileSize, szBytesMax, MAX_BYTES_STRLEN));
TraceMsg(DM_PROGRESS, "OnProgress Estimated string = %s", szBuf);
SetDlgItemText(_hDlg, IDD_TIMEEST, szBuf);
_dwOldEst = dwEst;
// Compute & display transfer rate
if(dwRate != _dwOldRate)
{
_dwOldRate = dwRate;
_FormatMessage(_szTransferRate, szBuf, ARRAYSIZE(szBuf), StrFormatByteSize(dwRate, szBytes, MAX_BYTES_STRLEN));
SetDlgItemText(_hDlg, IDD_TRANSFERRATE, szBuf);
}
}
// Compute & display percentage of download completed
DWORD dwPcent = (100 - MulDiv(_dwFileSize - ulProgress, 100, _dwFileSize));
if(dwPcent != _dwOldPcent)
{
_dwOldPcent = dwPcent;
if(dwPcent == 100) // Don't peg the meter until we've completed
dwPcent = 99;
TCHAR szBuf2[MAX_PATH];
DWORD dwSize = ARRAYSIZE(szBuf2);
if (PrepareURLForDisplay(pszFileName, szBuf2, &dwSize))
_FormatMessage(_szTitlePercent, szBuf, ARRAYSIZE(szBuf), (UINT)dwPcent, szBuf2);
else
_FormatMessage(_szTitlePercent, szBuf, ARRAYSIZE(szBuf), (UINT)dwPcent, pszFileName);
SetWindowText(_hDlg, szBuf);
}
}
}
}
else if (_hDlg && _fDownloadStarted) // Unknown file size, just show bytes and rate
{
// Recompute and display stats at most every second
if ((dwCur - _dwOldCur) >= 1000)
{
_dwOldCur = dwCur; // Save current tick count
DWORD dwSpent = ((dwCur - _dwFirstTick)+500) / 1000;
DWORD dwRate = ulProgress / (dwSpent ? dwSpent : 1);
_FormatMessage(_szBytesCopied, szBuf, ARRAYSIZE(szBuf),
StrFormatByteSize(ulProgress, szBytes, MAX_BYTES_STRLEN));
TraceMsg(DM_PROGRESS, "OnProgress string = %s", szBuf);
SetDlgItemText(_hDlg, IDD_TIMEEST, szBuf);
_FormatMessage(_szTransferRate, szBuf, ARRAYSIZE(szBuf), StrFormatByteSize(dwRate, szBytes, MAX_BYTES_STRLEN));
SetDlgItemText(_hDlg, IDD_TRANSFERRATE, szBuf);
{
TCHAR szBuf2[MAX_PATH];
DWORD dwSize = ARRAYSIZE(szBuf2);
if (PrepareURLForDisplay (pszFileName, szBuf2, &dwSize))
_FormatMessage(_szTitleBytes, szBuf, ARRAYSIZE(szBuf),
StrFormatByteSize(ulProgress, szBytes, MAX_BYTES_STRLEN),szBuf2);
else
_FormatMessage(_szTitleBytes, szBuf, ARRAYSIZE(szBuf),
StrFormatByteSize(ulProgress, szBytes, MAX_BYTES_STRLEN), pszFileName);
SetWindowText(_hDlg, szBuf);
}
}
}
}
break;
default: // ulStatusCode
break;
}
return S_OK;
}
HRESULT CDownload::OnStopBinding(HRESULT hrError,
LPCWSTR szError)
{
TraceMsg(DM_DOWNLOAD, "OnStopBinding called with hrError==%x", hrError);
HRESULT hrDisplay = hrError;
AddRef(); // Guard against last Release by _RevokeObjectParam
HRESULT hres = RevokeBindStatusCallback(_pbc, this);
AssertMsg(SUCCEEDED(hres), TEXT("URLMON bug??? RevokeBindStatusCallback failed %x"), hres);
if (_pib)
{
CLSID clsid;
LPWSTR pwszError = NULL;
HRESULT hresT = _pib->GetBindResult(&clsid, (DWORD *)&hrDisplay, &pwszError, NULL);
TraceMsg(TF_SHDBINDING, "DLD::OnStopBinding called GetBindResult %x->%x (%x)", hrError, hrDisplay, hresT);
if (SUCCEEDED(hresT))
{
//
// BUGBUG: URLMON returns a native Win32 error.
//
if (hrDisplay && SUCCEEDED(hrDisplay))
hrDisplay = HRESULT_FROM_WIN32(hrDisplay);
if (pwszError)
OleFree(pwszError);
}
// We don't call IBinding::Release until ~CDownload
// because we need to guarantee the download file
// exists until we have copied or executed it.
}
#ifdef DEBUG
if (hrError==S_OK && GetKeyState(VK_CONTROL) < 0)
{
hrError = E_FAIL;
}
#endif
if (FAILED(hrError) && hrError != E_ABORT)
{
IE_ErrorMsgBox(NULL, _hDlg, hrDisplay, szError,_szDisplay, IDS_CANTDOWNLOAD, MB_OK|MB_ICONSTOP);
}
CloseHandle(g_hCritOpMutex);
SetQueryNetSessionCount(SESSION_DECREMENT);
if (!_fGotFile || !_fDownloadCompleted)
{
AssertMsg(FAILED(hrError), TEXT("CDownload::OnStopBinding is called, but we've never got a file -- URLMON bug"));
if (!_fEndDialogCalled)
{
FORWARD_WM_COMMAND(_hDlg, IDCANCEL, NULL, 0, PostMessage);
}
}
Release(); // Guard against last Release by _RevokeObjectParam
return S_OK;
}
HRESULT CDownload::GetBindInfo(
DWORD* grfBINDINFOF,
BINDINFO *pbindinfo)
{
TraceMsg(DM_DOWNLOAD, "DWNLD::GetBindInfo called when _pbinfo==%x", _pbinfo);
if ( !grfBINDINFOF || !pbindinfo || !pbindinfo->cbSize )
return E_INVALIDARG;
if (_pbinfo) {
// Give the ownership to URLMON... shallow copy; don't use CopyBindInfo().
// Don't forget to keep pbindinfo cbSize!
DWORD cbSize = pbindinfo->cbSize;
CopyMemory( pbindinfo, _pbinfo, min(_pbinfo->cbSize, cbSize) );
pbindinfo->cbSize = cbSize;
if (pbindinfo->cbSize > _pbinfo->cbSize)
{
ZeroMemory((BYTE *)pbindinfo + _pbinfo->cbSize, pbindinfo->cbSize - _pbinfo->cbSize);
}
LocalFree(_pbinfo);
_pbinfo = NULL;
} else {
// We don't have a BINDINFO our selves so
// clear BINDINFO except cbSize
DWORD cbSize = pbindinfo->cbSize;
ZeroMemory( pbindinfo, cbSize );
pbindinfo->cbSize = cbSize;
if(UTF8Enabled())
pbindinfo->dwOptions = BINDINFO_OPTIONS_ENABLE_UTF8;
}
// #52524. With post build ~1100, If we do not return the following flags when URLMon calls
// GetBindInfo(), It will bind to the storage synchronously. (judej, danpoz)
*grfBINDINFOF = _grfBINDF | BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
return S_OK;
}
HRESULT CDownload::OnDataAvailable(
/* [in] */ DWORD grfBSC,
/* [in] */ DWORD dwSize,
/* [in] */ FORMATETC *pformatetc,
/* [in] */ STGMEDIUM *pstgmed)
{
DWORD dwOptions = 0;
DWNLDMSG3("OnDataAvailable (grf,pstg)", grfBSC, pstgmed);
_dwTotalSize = dwSize; // keep track of number of bytes downloaded
if (SUCCEEDED(_GetRequestFlagFromPIB(_pib, &dwOptions)) && (dwOptions & INTERNET_REQFLAG_CACHE_WRITE_DISABLED)) {
_fWriteHistory = FALSE;
}
//
// This code gets the file name from pstgmed, when it became
// available. URLMon is supposed to pass it even though the file
// is not completely ready yet.
//
if (!_fGotFile && pstgmed)
{
Animate_Stop(GetDlgItem(_hDlg, IDD_ANIMATE));
if (pstgmed->tymed == TYMED_FILE)
{
TCHAR szBuf[MAX_PATH]; // ok with MAX_PATH (because we truncate)
SHUnicodeToTChar(pstgmed->lpszFileName, _szPath, ARRAYSIZE(_szPath));
// Get the URL scheme
DWORD dwLen;
URL_COMPONENTS urlComp;
TCHAR rgchScheme[16];
TCHAR rgchHostName[INTERNET_MAX_HOST_NAME_LENGTH];
TCHAR rgchUrlPath[MAX_PATH];
TCHAR rgchCanonicalUrl[MAX_URL_STRING];
HRESULT hr;
dwLen = ARRAYSIZE(rgchCanonicalUrl);
hr = UrlCanonicalize(_szURL, rgchCanonicalUrl, &dwLen, 0);
if (SUCCEEDED(hr))
{
ZeroMemory(&urlComp, sizeof(urlComp));
urlComp.dwStructSize = sizeof(urlComp);
urlComp.lpszHostName = rgchHostName;
urlComp.dwHostNameLength = ARRAYSIZE(rgchHostName);
urlComp.lpszUrlPath = rgchUrlPath;
urlComp.dwUrlPathLength = ARRAYSIZE(rgchUrlPath);
urlComp.lpszScheme = rgchScheme;
urlComp.dwSchemeLength = ARRAYSIZE(rgchScheme);
hr = InternetCrackUrl(rgchCanonicalUrl, lstrlen(rgchCanonicalUrl), 0, &urlComp);
if (SUCCEEDED(hr))
{
StrCpyN(_szScheme, rgchScheme, ARRAYSIZE(_szScheme));
}
}
// Because of redirection the _szURL could be http://.../redir.dll or query.exe.
// Whereas the actual filename would be something else. The Cache filename is generated
// by wininet after it has figured out what the real filename is. However, it might contain
// a "(1)" or a "(2)" at the end of the file name.
TCHAR szURL[MAX_URL_STRING];
StrCpyN(szURL, _szURL, ARRAYSIZE(szURL));
TCHAR * pszURLFName = PathFindFileName(szURL);
TCHAR * pszCacheFName = PathFindFileName(_szPath);
// Unescape the filename suggested by wininet.
DWORD cch = ARRAYSIZE(szBuf);
if(PrepareURLForDisplayUTF8(pszCacheFName, szBuf, &cch, _fUTF8Enabled) != S_OK)
StrCpyN(szBuf, pszCacheFName, ARRAYSIZE(szBuf));
// Strip out any path that may have been encoded
pszCacheFName = szBuf;
TCHAR *pszSrc = PathFindFileName(szBuf);
if (pszSrc != szBuf)
{
while(*pszSrc)
*pszCacheFName++ = *pszSrc++;
*pszCacheFName = *pszSrc;
}
// Use the Cache name. pszURLFName point to the file name in szURL. Just overwrite it
if (pszURLFName && szBuf)
{
StrCpyN(pszURLFName, szBuf, ARRAYSIZE(szURL) - ((int)(pszURLFName-szURL)/sizeof(TCHAR)));
FormatUrlForDisplay(szURL, _szDisplay, ARRAYSIZE(_szDisplay), TRUE, _uiCP);
}
DWNLDMSG("OnDataAvailable got TYMED_FILE", _szPath);
_fGotFile = TRUE;
TCHAR szMime[MAX_PATH];
if (GetClipboardFormatName(pformatetc->cfFormat, szMime, sizeof(szMime)))
{
MIME_GetExtension(szMime, (LPTSTR) _szExt, SIZECHARS(_szExt));
}
SetWindowText(GetDlgItem(_hDlg, IDD_NAME), _szDisplay);
UINT uRet = _MayAskUserIsFileSafeToOpen();
switch(uRet) {
case IDOK:
MLLoadString(IDS_OPENING, szBuf, ARRAYSIZE(szBuf));
break;
case IDD_SAVEAS:
_fSaveAs = TRUE;
_fCallVerifyTrust = FALSE;
MLLoadString(IDS_SAVING, szBuf, ARRAYSIZE(szBuf));
break;
case IDCANCEL:
FORWARD_WM_COMMAND(_hDlg, IDCANCEL, NULL, 0, PostMessage);
//
// HACK: Under a certain condition, we receive one more
// OnDataAvailable from URLMON with BSCF_LASTDATANOTIFICATION
// before this posted message is dispatched. It causes
// WinVerifyTrust call, which is wrong. To prevent it,
// we unset this flag.
//
// BUGBUG:
// We still assumes that OnStopBinding will not happen before
// this message is dispatched. In IE 4.0, we should introduce
// another flag (_fCancelled) to make it more robust.
//
_fCallVerifyTrust = FALSE;
return S_OK;
}
SetDlgItemText(_hDlg, IDD_OPENIT, szBuf);
if (_fSaveAs)
{
if (!_GetSaveLocation())
{
FORWARD_WM_COMMAND(_hDlg, IDCANCEL, NULL, 0, PostMessage);
return S_OK;
}
StrCpyN(szBuf, _szSaveToFile, ARRAYSIZE(szBuf));
RECT rect;
GetClientRect(GetDlgItem(_hDlg, IDD_DIR), &rect);
PathCompactPath(NULL, szBuf, rect.right);
}
else
MLLoadString(IDS_DOWNLOADTOCACHE, szBuf, ARRAYSIZE(szBuf));
SetDlgItemText(_hDlg, IDD_DIR, szBuf);
Animate_Play(GetDlgItem(_hDlg, IDD_ANIMATE),0, -1, -1);
if(_dwFirstTick == 0) // Start the timer
_dwFirstTick = GetTickCount();
}
else
{
TraceMsg(DM_WARNING, "CDownload::OnDataAvailable pstgmed->tymed (%d) != TYMED_FILE", pstgmed->tymed);
}
_fDownloadStarted = TRUE;
}
if (grfBSC & BSCF_LASTDATANOTIFICATION)
{
_fDownloadCompleted = TRUE;
#ifdef CALL_WVT
if (_fCallVerifyTrust)
{
ShowWindow(_hDlg, SW_HIDE);
UINT uRet = _VerifyTrust(_hDlg, _szPath, _szDisplay);
switch (uRet) {
case IDOK:
break;
default:
// We assume _VerifyTrust always is able to open the file
// passed from URLMON. If it fails, we bail with no UI.
ASSERT(0);
// Fall through
case IDCANCEL:
_fDeleteFromCache = TRUE;
FORWARD_WM_COMMAND(_hDlg, IDCANCEL, NULL, 0, PostMessage);
return S_OK;
}
}
#endif // CALL_WVT
DWNLDMSG3("OnDataAvailable calling Animate_Stop", _hDlg, GetDlgItem(_hDlg, IDD_ANIMATE));
Animate_Stop(GetDlgItem(_hDlg, IDD_ANIMATE));
SendMessage(GetDlgItem(_hDlg, IDD_PROBAR), PBM_SETRANGE32, 0, 100);
SendMessage(GetDlgItem(_hDlg, IDD_PROBAR), PBM_SETPOS, 100, 0);
if (_fSaveAs) {
FORWARD_WM_COMMAND(_hDlg, IDD_SAVEAS, NULL, 0, PostMessage);
} else {
#ifdef USE_LOCKREQUEST
LockRequestHandle(); // Tell wininet that we want the file locked to allow the app to open it.
// This prevents wininet from deleting the file from the cache before the
// app gets a chance to use it. When wininet sees this file is locked, it
// will add the file to the scavenger leak list and attempt to delete the
// file in the future.
#endif
FORWARD_WM_COMMAND(_hDlg, IDOK, NULL, 0, PostMessage);
}
}
return S_OK;
}
HRESULT CDownload::OnObjectAvailable(
/* [in] */ REFIID riid,
/* [iid_is][in] */ IUnknown *punk)
{
DWORD dwOptions = 0;
DWNLDMSG3("OnObjectAvailable (riid,punk)", riid, punk);
if (SUCCEEDED(_GetRequestFlagFromPIB(_pib, &dwOptions)) && (dwOptions & INTERNET_REQFLAG_CACHE_WRITE_DISABLED)) {
_fWriteHistory = FALSE;
}
return S_OK;
}
/* *** IHttpNegotiate *** */
HRESULT CDownload::BeginningTransaction(LPCWSTR szURL, LPCWSTR szHeaders,
DWORD dwReserved, LPWSTR *pszAdditionalHeaders)
{
LPWSTR pwzHeaders = NULL;
DWORD cbHeaders = 0;
if ((!_pwzHeaders) || (!pszAdditionalHeaders))
return S_OK;
cbHeaders = (lstrlenW(_pwzHeaders)+1)*sizeof(WCHAR);
pwzHeaders = (LPWSTR)CoTaskMemAlloc(cbHeaders+sizeof(WCHAR));
if (pwzHeaders)
{
memcpy (pwzHeaders, _pwzHeaders, cbHeaders);
*pszAdditionalHeaders = pwzHeaders;
}
// Caller owns freeing *pszAdditionalHeaders
return S_OK;
}
HRESULT CDownload::OnResponse(DWORD dwResponseCode,
LPCWSTR szResponseHeaders,
LPCWSTR szRequestHeaders,
LPWSTR *pszAdditionalRequestHeaders)
{
return S_OK;
}
BOOL _RememberFileIsSafeToOpen(LPCTSTR szFileClass)
{
DWORD dwValueType, dwEditFlags;
ULONG cb = SIZEOF(dwEditFlags);
if (SHGetValue(HKEY_CLASSES_ROOT, szFileClass, TEXT("EditFlags"),
&dwValueType, (PBYTE)&dwEditFlags, &cb) == ERROR_SUCCESS &&
(dwValueType == REG_BINARY || dwValueType == REG_DWORD))
{
dwEditFlags &= ~FTA_NoEdit;
dwEditFlags |= FTA_OpenIsSafe;
} else {
dwEditFlags = FTA_OpenIsSafe;
}
return (SHSetValue(HKEY_CLASSES_ROOT, szFileClass, TEXT("EditFlags"),
REG_BINARY, (BYTE*)&dwEditFlags,
sizeof(dwEditFlags)) == ERROR_SUCCESS);
}
struct SAFEOPENDLGPARAM {
LPCTSTR pszFileClass;
LPCTSTR pszFriendlyURL;
LPCTSTR pszURL;
HWND hwndTT;
TCHAR* pszTTText;
LPCTSTR pszCacheFile;
DWORD uiCP;
};
INT_PTR CALLBACK SafeOpenDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
UINT id;
SAFEOPENDLGPARAM* param = (SAFEOPENDLGPARAM*) GetWindowLongPtr(hDlg, DWLP_USER);
if((param == NULL) && (uMsg != WM_INITDIALOG))
return FALSE;
switch(uMsg) {
case WM_INITDIALOG:
{
BOOL fChangeText = FALSE;
BOOL fDisableCheckBox = FALSE;
TCHAR * pszDisplay = NULL;
TCHAR szDisplay[MAX_DISPLAY_LEN] = {TEXT('\0')};
TCHAR szProcessedURL[MAX_URL_STRING] = {TEXT('\0')};
DWORD dwSize = ARRAYSIZE(szProcessedURL);
if(lParam == NULL)
return FALSE;
SetWindowLongPtr(hDlg, DWLP_USER, lParam);
param = (SAFEOPENDLGPARAM*)lParam;
// Determine whether or not to gray out the Always ask checkbox. We wil gray out in the following cases
// 1. If we were not told what the file class is
// 2. If the file class is in the unsafe extensions list
// 3. if the file extension in the URL is in the unsafe extensions list
// 4. if the cache file extension is in the unsafe extensions list (if we are redirected)
if (param->pszFileClass && *param->pszFileClass)
{
TCHAR * pszExt = NULL;
TCHAR * pszCacheExt = NULL;
if (param->pszURL)
pszExt = PathFindExtension(param->pszURL);
if (param->pszCacheFile)
pszCacheExt = PathFindExtension(param->pszCacheFile);
if (IsProgIDInList(param->pszFileClass, NULL, c_arszUnsafeExts, ARRAYSIZE(c_arszUnsafeExts)))
fDisableCheckBox = TRUE;
else if (IsProgIDInList(NULL, pszExt, c_arszUnsafeExts, ARRAYSIZE(c_arszUnsafeExts)))
fDisableCheckBox = TRUE;
else if (IsProgIDInList(NULL, pszCacheExt, c_arszUnsafeExts, ARRAYSIZE(c_arszUnsafeExts)))
fDisableCheckBox = TRUE;
if (!IsProgIDInList(param->pszFileClass, NULL, c_arszExecutableExtns, ARRAYSIZE(c_arszExecutableExtns)))
fChangeText = TRUE;
}
else
{
fDisableCheckBox = TRUE;
fChangeText = TRUE;
}
if (fDisableCheckBox || SHRestricted2(REST_AlwaysPromptWhenDownload, NULL, 0))
EnableWindow(GetDlgItem(hDlg, IDC_SAFEOPEN_ALWAYS), FALSE);
#ifdef UNIX
if (fDisableCheckBox)
{
EndDialog(hDlg,IDD_SAVEAS);
break;
}
#endif
// The check box is always checked by default
CheckDlgButton(hDlg, IDC_SAFEOPEN_ALWAYS, TRUE);
// Change the Save/Open to be Save/Run in the dialog.
if (fChangeText)
{
TCHAR szTemp[MAX_PATH];
if (MLLoadString(IDS_OPENFROMINTERNET, szTemp, ARRAYSIZE(szTemp)))
SetDlgItemText(hDlg, IDC_SAFEOPEN_AUTOOPEN, szTemp);
if (MLLoadString(IDS_SAVEFILETODISK, szTemp, ARRAYSIZE(szTemp)))
SetDlgItemText(hDlg, IDC_SAFEOPEN_AUTOSAVE, szTemp);
}
// Check the save as by default
CheckDlgButton(hDlg, IDC_SAFEOPEN_AUTOSAVE, TRUE);
// cross-lang platform support
SHSetDefaultDialogFont(hDlg, IDC_SAFEOPEN_EXPL);
// Get the URL for the tooltip. Also get URL for the display string if we weren't passed one
if (param->pszURL)
{
if (!PrepareURLForDisplay(param->pszURL, szProcessedURL, &dwSize))
{
dwSize = ARRAYSIZE(szProcessedURL);
StrCpyN(szProcessedURL, param->pszURL, dwSize);
}
}
// Now figure out what we want to display
// By default we use the Friendly string that was passed to us. If we were not passed a string
// generate it from the URL.
pszDisplay = (TCHAR*)param->pszFriendlyURL;
if (!pszDisplay || !lstrlen(pszDisplay))
{
FormatUrlForDisplay(szProcessedURL, szDisplay, ARRAYSIZE(szDisplay), TRUE, param->uiCP);
pszDisplay = szDisplay;
}
SetDlgItemText(hDlg, IDC_SAFEOPEN_EXPL, pszDisplay);
int cch = lstrlen(szProcessedURL) + 1;
param->pszTTText = (TCHAR*)LocalAlloc(LPTR, cch * SIZEOF(TCHAR));
if (param->pszTTText)
{
StrCpyN(param->pszTTText, szProcessedURL, cch);
if (param->hwndTT = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
hDlg, NULL, HINST_THISDLL, NULL))
{
TOOLINFO ti;
ti.cbSize = SIZEOF(ti);
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.hwnd = hDlg;
ti.uId = (UINT_PTR) GetDlgItem(hDlg, IDC_SAFEOPEN_EXPL);
ti.lpszText = LPSTR_TEXTCALLBACK;
ti.hinst = HINST_THISDLL;
GetWindowRect((HWND)ti.uId, &ti.rect);
SendMessage(param->hwndTT, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti);
SendMessage(param->hwndTT, TTM_SETMAXTIPWIDTH, 0, 300);
}
}
return TRUE;
}
case WM_NOTIFY:
{
LPTOOLTIPTEXT lpTT = (LPTOOLTIPTEXT) lParam;
if (lpTT->hdr.code == TTN_NEEDTEXT)
{
lpTT->lpszText = param->pszTTText;
lpTT->hinst = NULL;
}
break;
}
case WM_DESTROY:
SHRemoveDefaultDialogFont(hDlg);
// clean up the icon
if (param->pszFileClass)
{
#if 0
// Er... This is dead code since no such IDC_SAFEOPEN_ICON exists
// in the template... This just leaks and rips in debug.
HICON hIcon = (HICON)SendDlgItemMessage(hDlg, IDC_SAFEOPEN_ICON, STM_GETICON, 0, 0);
if (hIcon)
DestroyIcon(hIcon);
#endif
}
if (IsWindow(param->hwndTT))
DestroyWindow(param->hwndTT);
if (param->pszTTText)
LocalFree(param->pszTTText);
return FALSE;
case WM_COMMAND:
id = GET_WM_COMMAND_ID(wParam, lParam);
switch (id) {
case IDM_MOREINFO:
#ifndef UNIX
SHHtmlHelpOnDemandWrap(hDlg, TEXT("iexplore.chm > iedefault"), HH_DISPLAY_TOPIC, (DWORD_PTR) TEXT("filedown.htm"), ML_CROSSCODEPAGE);
#endif
break;
case IDOK:
if (param->pszFileClass && !IsDlgButtonChecked(hDlg, IDC_SAFEOPEN_ALWAYS))
{
_RememberFileIsSafeToOpen(param->pszFileClass);
// Now save EditFlags at the key value value that the filetypes dialog will get/set.
TCHAR * pszExt = NULL;
DWORD dwValueType;
TCHAR szFileClass[MAX_PATH];
ULONG cb = SIZEOF(szFileClass);
if (param->pszURL)
pszExt = PathFindExtension(param->pszURL);
if (*pszExt)
{
*szFileClass = TEXT('\0');
SHGetValue(HKEY_CLASSES_ROOT, pszExt, NULL, &dwValueType, (PBYTE)&szFileClass, &cb);
if (*szFileClass)
_RememberFileIsSafeToOpen(szFileClass);
}
}
if (IsDlgButtonChecked(hDlg, IDC_SAFEOPEN_AUTOSAVE ))
{
id = IDD_SAVEAS;
}
// fall through
case IDCANCEL:
EndDialog(hDlg, id);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
UINT OpenSafeOpenDialog(HWND hwnd, UINT idRes, LPCTSTR pszFileClass, LPCTSTR pszURL, LPCTSTR pszRedirURL, LPCTSTR pszCacheName, LPCTSTR pszDisplay, UINT uiCP)
{
LPCTSTR pszTemp = pszURL;
if (pszRedirURL && lstrlen(pszRedirURL))
pszTemp = pszRedirURL;
SAFEOPENDLGPARAM param = { pszFileClass, pszDisplay, pszTemp, 0, 0, pszCacheName, uiCP};
return (BOOL) DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(idRes),
hwnd, SafeOpenDlgProc, (LPARAM)¶m);
}
BOOL _OpenIsSafe(HKEY hk, LPCTSTR pszClass)
{
DWORD dwValueType, dwEditFlags;
ULONG cb = SIZEOF(dwEditFlags);
return (ERROR_SUCCESS == SHGetValue(hk, pszClass, TEXT("EditFlags"), &dwValueType, (PBYTE)&dwEditFlags, &cb)
&& (dwValueType == REG_BINARY || dwValueType == REG_DWORD)
&& (dwEditFlags & FTA_OpenIsSafe));
}
UINT MayOpenSafeOpenDialog(HWND hwnd, LPCTSTR pszFileClass, LPCTSTR pszURL, LPCTSTR pszCacheName, LPCTSTR pszDisplay, UINT uiCP)
{
// Has some association
UINT uiRet = IDOK;
const LPCTSTR c_szExcluded[] = {TEXT(".ins"),TEXT(".isp")};
const LPCTSTR c_szNoZoneCheckExtns[] = {TEXT(".cdf")};
BOOL fSafe = (*pszFileClass && _OpenIsSafe(HKEY_CLASSES_ROOT, pszFileClass));
if (fSafe)
{
//
// BUGBUGREVIEW - changing in the file associations doesnt work correctly - ZekeL - 29-JUN-98
// it turns out that if you use the file associations dialog to mark
// a file type as prompt to open, it will not always work.
// this is because we actually dont always get back the same progid from
// urlmon that we would get from the extension. so to make it fair
// we will also check the extension's progid editflags, and thus
// error on the side of prompting to often rather, than not enough
//
HKEY hkey;
ASSERT(pszURL || pszCacheName);
LPCTSTR pszExt = PathFindFileName(pszCacheName ? pszCacheName : pszURL);
pszExt = PathFindExtension(pszExt);
if (S_OK == AssocQueryKey(0, ASSOCKEY_SHELLEXECCLASS, pszExt, NULL, &hkey))
{
fSafe = _OpenIsSafe(hkey, NULL);
RegCloseKey(hkey);
}
}
// We will not do Zone check on CDF files..#56297.
if (!IsProgIDInList(pszFileClass, NULL, c_szNoZoneCheckExtns, ARRAYSIZE(c_szNoZoneCheckExtns)))
{
DWORD dwPolicy = 0, dwContext = 0;
ZoneCheckUrlEx(pszURL, &dwPolicy, SIZEOF(dwPolicy), &dwContext, SIZEOF(dwContext),
URLACTION_SHELL_FILE_DOWNLOAD, PUAF_NOUI, NULL);
dwPolicy = GetUrlPolicyPermissions(dwPolicy);
if ((dwPolicy != URLPOLICY_ALLOW) && (dwPolicy != URLPOLICY_QUERY))
{
ProcessStartbindingError(NULL, NULL, NULL, MB_ICONWARNING, E_ACCESSDENIED);
return IDCANCEL;
}
}
// Always ask for certain the types that we know to be unsafe. We will allow .ins and .isp
// files through for the ICW folks.
if (IsProgIDInList(pszFileClass, NULL, c_arszUnsafeExts, ARRAYSIZE(c_arszUnsafeExts)) &&
!IsProgIDInList(pszFileClass, NULL, c_szExcluded, ARRAYSIZE(c_szExcluded)))
fSafe = FALSE;
if (!fSafe || SHRestricted2(REST_AlwaysPromptWhenDownload, NULL,0))
uiRet = OpenSafeOpenDialog(hwnd, DLG_SAFEOPEN, pszFileClass, pszURL, NULL, pszCacheName, pszDisplay, uiCP);
if (uiRet != IDOK && uiRet != IDD_SAVEAS)
DeleteUrlCacheEntry(pszURL);
return(uiRet);
}
#ifdef CALL_WVT
// Returns:
//
// IDOK -- If it's trusted
// IDNO -- If it's not known (warning dialog requried)
// IDCANCEL -- We need to stop download it
//
UINT _VerifyTrust(HWND hwnd, LPCTSTR pszFileName, LPCWSTR pszStatusText)
{
UINT uRet = IDNO; // assume unknown
HANDLE hFile;
if ( (hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0)) != INVALID_HANDLE_VALUE)
{
HRESULT hres;
hres = g_wvt.VerifyTrust(hFile, hwnd, pszStatusText);
TraceMsg(DM_WVT, "_VerifyTrust WVT returned %x", hres);
if (SUCCEEDED(hres)) {
uRet = IDOK;
} else {
ASSERT((hres != HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)) &&
(hres != HRESULT_FROM_WIN32(ERROR_DLL_NOT_FOUND)));
uRet = IDCANCEL;
}
CloseHandle(hFile);
} else {
TraceMsg(DM_WARNING, "_VerifyTrust CreateFile failed %x", GetLastError());
}
TraceMsg(DM_WVT, "_VerifyTrust returning %d", uRet);
return uRet;
}
#endif // CALL_WVT
//
// Returns:
// IDOK: Continue download and open it
// IDD_SAVEAS: Save it as a file
// IDCANCEL: Stop downloading
//
UINT CDownload::_MayAskUserIsFileSafeToOpen()
{
if (_fSaveAs || _fSafe) {
return (_fSaveAs ? IDD_SAVEAS : IDOK); // no need to ask
}
// Force save as dialog if we are using SSL and
// HKCU\software\microsoft\windows\currentversion\internet settings\DisableCachingOfSSLPages is set
DWORD dwValue;
DWORD dwDefault = 0;
DWORD dwSize;
dwSize = SIZEOF(dwValue);
SHRegGetUSValue(TSZWININETPATH, TEXT("DisableCachingOfSSLPages"), NULL, (LPBYTE)&dwValue, &dwSize, FALSE, (LPVOID) &dwDefault, SIZEOF(dwDefault));
if (dwValue != 0)
{
// See if we are using SSL - BUGBUG see if there is a better way to get this
URL_COMPONENTS urlComp;
TCHAR rgchCanonicalUrl[MAX_URL_STRING];
DWORD dwLen;
HRESULT hr;
dwLen = ARRAYSIZE(rgchCanonicalUrl);
ZeroMemory(rgchCanonicalUrl, dwLen);
hr = UrlCanonicalize(_szURL, rgchCanonicalUrl, &dwLen, 0);
if (SUCCEEDED(hr))
{
ZeroMemory(&urlComp, sizeof(urlComp));
urlComp.dwStructSize = sizeof(urlComp);
hr = InternetCrackUrl(rgchCanonicalUrl, lstrlen(rgchCanonicalUrl) + 1, 0, &urlComp);
if (SUCCEEDED(hr))
{
if (urlComp.nScheme == INTERNET_SCHEME_HTTPS)
{
return(IDD_SAVEAS);
}
}
}
}
BOOL fUnknownType = TRUE;
UINT uRet = IDNO; // assume no extension or no association
LPTSTR pszExt = PathFindExtension(_szPath);
TCHAR szFileClass[MAX_PATH];
memset(szFileClass, 0, ARRAYSIZE(szFileClass));
// if we have a better extension from
// the mime type, use that instead
if (*pszExt)
{
#ifdef CALL_WVT
//
// If this is an EXE and we have WINTRUST ready to call,
// don't popup any UI here at this point.
if ((StrCmpI(pszExt, TEXT(".exe"))==0) && SUCCEEDED(g_wvt.Init()))
{
TraceMsg(DM_WVT, "_MayAskUIFSTO this is EXE, we call _VerifyTrust later");
_fCallVerifyTrust = TRUE;
}
#endif // CALL_WVT
ULONG cb = SIZEOF(szFileClass);
if ((RegQueryValue(HKEY_CLASSES_ROOT, pszExt, szFileClass, (LONG*)&cb)
== ERROR_SUCCESS) && * szFileClass)
{
fUnknownType = FALSE;
uRet = MayOpenSafeOpenDialog(_hDlg, szFileClass, _szURL, _szPath, _szDisplay, _uiCP);
}
}
if (fUnknownType) {
uRet = OpenSafeOpenDialog(_hDlg, DLG_SAFEOPEN, NULL, _szURL, NULL, _szPath, _szDisplay, _uiCP);
}
return uRet;
}
// *** IAuthenticate ***
HRESULT CDownload::Authenticate(HWND *phwnd, LPWSTR *pszUsername, LPWSTR *pszPassword)
{
if (!phwnd || !pszUsername || !pszPassword)
return E_POINTER;
*phwnd = _hDlg;
*pszUsername = NULL;
*pszPassword = NULL;
return S_OK;
}
// *** IServiceProvider ***
HRESULT CDownload::QueryService(REFGUID guidService, REFIID riid, void **ppvObj)
{
*ppvObj = NULL;
if (IsEqualGUID(guidService, IID_IAuthenticate))
{
return QueryInterface(riid, ppvObj);
}
return E_FAIL;
}
#ifndef POSTPOSTSPLIT
// create objects from registered under a key value, uses the per user per machine
// reg services to do this.
HRESULT CreateFromRegKey(LPCTSTR pszKey, LPCTSTR pszValue, REFIID riid, void **ppv)
{
HRESULT hres = E_FAIL;
TCHAR szCLSID[MAX_PATH];
DWORD cbSize = SIZEOF(szCLSID);
if (SHRegGetUSValue(pszKey, pszValue, NULL, (LPVOID)szCLSID, &cbSize, FALSE, NULL, 0) == ERROR_SUCCESS)
{
CLSID clsid;
hres = SHCLSIDFromString(szCLSID, &clsid);
if (SUCCEEDED(hres))
{
hres = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, riid, ppv);
}
}
return hres;
}
#endif
// S_OK : continue with operation
// S_FALSE : cancel operation.
HRESULT CDownload::PerformVirusScan(LPCTSTR szFileName)
{
HRESULT hr = S_OK; // default to accepting the file
IVirusScanner *pvs;
if (SUCCEEDED(CreateFromRegKey(TSZIEPATH, TEXT("VirusScanner"), IID_IVirusScanner, (void **)&pvs)))
{
STGMEDIUM stg;
WCHAR wszFileName[MAX_PATH];
VIRUSINFO vi;
vi.cbSize = sizeof(VIRUSINFO);
//
// VIRUSINFO lpszFileName is not defined as 'const' so we need to copy
// szFileName into a buffer. If it really should be const get rid of
// this copy and use a cast.
//
StrCpyN(wszFileName, szFileName, ARRAYSIZE(wszFileName));
stg.tymed = TYMED_FILE;
stg.lpszFileName = wszFileName;
stg.pUnkForRelease = NULL;
hr = pvs->ScanForVirus(_hDlg, &stg, _pwszDisplayName, SFV_DELETE, &vi);
switch(hr) {
case S_OK:
break;
case VSCAN_E_NOPROVIDERS: //No virus scanning providers
case VSCAN_E_CHECKPARTIAL: //Atleast one of providers didn't work.
case VSCAN_E_CHECKFAIL: //No providers worked.
hr = S_OK;
break;
case VSCAN_E_DELETEFAIL: //Tried to delete virus file but failed.
case S_FALSE: // Virus found.
hr = E_FAIL;
break;
// If some bizarre result, continue on.
default:
hr = S_OK;
break;
}
pvs->Release();
}
return hr;
}
/*******************************************************************
NAME: DoFileDownload
SYNOPSIS: Starts a download of a file in its own window.
NOTES: This function is exported and called by HTML doc object.
Someday we probably want to put this in a COM interface.
Currently it just calls the internal function
CDownLoad_OpenUIURL.
********************************************************************/
STDAPI DoFileDownload(LPCWSTR pwszURL)
{
return CDownLoad_OpenUIURL(pwszURL, NULL, NULL, FALSE,TRUE);
}
/*******************************************************************
NAME: DoFileDownloadEx
********************************************************************/
STDAPI DoFileDownloadEx(LPCWSTR pwszURL, BOOL fSaveAs)
{
return CDownLoad_OpenUIURL(pwszURL, NULL, NULL, FALSE, fSaveAs);
}
#ifdef DEBUG
const DWORD CDownloadThreadParam::s_dummy = 0;
#endif
|
/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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
https://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 "itktubeRidgeFFTFeatureVectorGenerator.h"
int itktubeRidgeFFTFeatureVectorGeneratorTest( int argc, char * argv[] )
{
if( argc != 4 )
{
std::cerr << "Missing arguments." << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImage outputF0Image outputF1Image"
<< std::endl;
return EXIT_FAILURE;
}
// Define the dimension of the images
enum { Dimension = 2 };
// Define the pixel type
typedef float PixelType;
// Declare the types of the images
typedef itk::Image<PixelType, Dimension> ImageType;
// Declare the reader and writer
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
// Declare the type for the Filter
typedef itk::tube::RidgeFFTFeatureVectorGenerator< ImageType > FilterType;
// Create the reader and writer
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch( itk::ExceptionObject & e )
{
std::cerr << "Exception caught during input read:" << std::endl << e;
return EXIT_FAILURE;
}
ImageType::Pointer inputImage = reader->GetOutput();
FilterType::Pointer filter = FilterType::New();
filter->SetInput( inputImage );
FilterType::RidgeScalesType scales( 2 );
scales[0] = 0.4;
scales[1] = 1.0;
filter->SetScales( scales );
std::cout << filter << std::endl;
filter->SetUpdateWhitenStatisticsOnUpdate( true );
filter->Update();
WriterType::Pointer imageFeature0Writer = WriterType::New();
imageFeature0Writer->SetFileName( argv[2] );
imageFeature0Writer->SetUseCompression( true );
imageFeature0Writer->SetInput( filter->GetFeatureImage( 0 ) );
try
{
imageFeature0Writer->Update();
}
catch( itk::ExceptionObject & e )
{
std::cerr << "Exception caught during write:" << std::endl << e;
return EXIT_FAILURE;
}
WriterType::Pointer imageFeature1Writer = WriterType::New();
imageFeature1Writer->SetFileName( argv[3] );
imageFeature1Writer->SetUseCompression( true );
imageFeature1Writer->SetInput( filter->GetFeatureImage( 6 ) );
try
{
imageFeature1Writer->Update();
}
catch ( itk::ExceptionObject& e )
{
std::cerr << "Exception caught during write:" << std::endl << e;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
#line 1 "flex_lexer.cpp"
#line 3 "flex_lexer.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
#ifdef yy_create_buffer
#define hsql__create_buffer_ALREADY_DEFINED
#else
#define yy_create_buffer hsql__create_buffer
#endif
#ifdef yy_delete_buffer
#define hsql__delete_buffer_ALREADY_DEFINED
#else
#define yy_delete_buffer hsql__delete_buffer
#endif
#ifdef yy_scan_buffer
#define hsql__scan_buffer_ALREADY_DEFINED
#else
#define yy_scan_buffer hsql__scan_buffer
#endif
#ifdef yy_scan_string
#define hsql__scan_string_ALREADY_DEFINED
#else
#define yy_scan_string hsql__scan_string
#endif
#ifdef yy_scan_bytes
#define hsql__scan_bytes_ALREADY_DEFINED
#else
#define yy_scan_bytes hsql__scan_bytes
#endif
#ifdef yy_init_buffer
#define hsql__init_buffer_ALREADY_DEFINED
#else
#define yy_init_buffer hsql__init_buffer
#endif
#ifdef yy_flush_buffer
#define hsql__flush_buffer_ALREADY_DEFINED
#else
#define yy_flush_buffer hsql__flush_buffer
#endif
#ifdef yy_load_buffer_state
#define hsql__load_buffer_state_ALREADY_DEFINED
#else
#define yy_load_buffer_state hsql__load_buffer_state
#endif
#ifdef yy_switch_to_buffer
#define hsql__switch_to_buffer_ALREADY_DEFINED
#else
#define yy_switch_to_buffer hsql__switch_to_buffer
#endif
#ifdef yypush_buffer_state
#define hsql_push_buffer_state_ALREADY_DEFINED
#else
#define yypush_buffer_state hsql_push_buffer_state
#endif
#ifdef yypop_buffer_state
#define hsql_pop_buffer_state_ALREADY_DEFINED
#else
#define yypop_buffer_state hsql_pop_buffer_state
#endif
#ifdef yyensure_buffer_stack
#define hsql_ensure_buffer_stack_ALREADY_DEFINED
#else
#define yyensure_buffer_stack hsql_ensure_buffer_stack
#endif
#ifdef yylex
#define hsql_lex_ALREADY_DEFINED
#else
#define yylex hsql_lex
#endif
#ifdef yyrestart
#define hsql_restart_ALREADY_DEFINED
#else
#define yyrestart hsql_restart
#endif
#ifdef yylex_init
#define hsql_lex_init_ALREADY_DEFINED
#else
#define yylex_init hsql_lex_init
#endif
#ifdef yylex_init_extra
#define hsql_lex_init_extra_ALREADY_DEFINED
#else
#define yylex_init_extra hsql_lex_init_extra
#endif
#ifdef yylex_destroy
#define hsql_lex_destroy_ALREADY_DEFINED
#else
#define yylex_destroy hsql_lex_destroy
#endif
#ifdef yyget_debug
#define hsql_get_debug_ALREADY_DEFINED
#else
#define yyget_debug hsql_get_debug
#endif
#ifdef yyset_debug
#define hsql_set_debug_ALREADY_DEFINED
#else
#define yyset_debug hsql_set_debug
#endif
#ifdef yyget_extra
#define hsql_get_extra_ALREADY_DEFINED
#else
#define yyget_extra hsql_get_extra
#endif
#ifdef yyset_extra
#define hsql_set_extra_ALREADY_DEFINED
#else
#define yyset_extra hsql_set_extra
#endif
#ifdef yyget_in
#define hsql_get_in_ALREADY_DEFINED
#else
#define yyget_in hsql_get_in
#endif
#ifdef yyset_in
#define hsql_set_in_ALREADY_DEFINED
#else
#define yyset_in hsql_set_in
#endif
#ifdef yyget_out
#define hsql_get_out_ALREADY_DEFINED
#else
#define yyget_out hsql_get_out
#endif
#ifdef yyset_out
#define hsql_set_out_ALREADY_DEFINED
#else
#define yyset_out hsql_set_out
#endif
#ifdef yyget_leng
#define hsql_get_leng_ALREADY_DEFINED
#else
#define yyget_leng hsql_get_leng
#endif
#ifdef yyget_text
#define hsql_get_text_ALREADY_DEFINED
#else
#define yyget_text hsql_get_text
#endif
#ifdef yyget_lineno
#define hsql_get_lineno_ALREADY_DEFINED
#else
#define yyget_lineno hsql_get_lineno
#endif
#ifdef yyset_lineno
#define hsql_set_lineno_ALREADY_DEFINED
#else
#define yyset_lineno hsql_set_lineno
#endif
#ifdef yyget_column
#define hsql_get_column_ALREADY_DEFINED
#else
#define yyget_column hsql_get_column
#endif
#ifdef yyset_column
#define hsql_set_column_ALREADY_DEFINED
#else
#define yyset_column hsql_set_column
#endif
#ifdef yywrap
#define hsql_wrap_ALREADY_DEFINED
#else
#define yywrap hsql_wrap
#endif
#ifdef yyget_lval
#define hsql_get_lval_ALREADY_DEFINED
#else
#define yyget_lval hsql_get_lval
#endif
#ifdef yyset_lval
#define hsql_set_lval_ALREADY_DEFINED
#else
#define yyset_lval hsql_set_lval
#endif
#ifdef yyget_lloc
#define hsql_get_lloc_ALREADY_DEFINED
#else
#define yyget_lloc hsql_get_lloc
#endif
#ifdef yyset_lloc
#define hsql_set_lloc_ALREADY_DEFINED
#else
#define yyset_lloc hsql_set_lloc
#endif
#ifdef yyalloc
#define hsql_alloc_ALREADY_DEFINED
#else
#define yyalloc hsql_alloc
#endif
#ifdef yyrealloc
#define hsql_realloc_ALREADY_DEFINED
#else
#define yyrealloc hsql_realloc
#endif
#ifdef yyfree
#define hsql_free_ALREADY_DEFINED
#else
#define yyfree hsql_free
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767 - 1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647 - 1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
/* begin standard C++ headers. */
/* TODO: this is always defined, so inline it */
#define yyconst const
#if defined(__GNUC__) && __GNUC__ >= 3
#define yynoreturn __attribute__((__noreturn__))
#else
#define yynoreturn
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an
* integer in range [0..255] for use as an array index.
*/
#define YY_SC_TO_UI(c) ((YY_CHAR)(c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
/* For convenience, these vars (plus the bison vars far below)
are macros in the reentrant scanner. */
#define yyin yyg->yyin_r
#define yyout yyg->yyout_r
#define yyextra yyg->yyextra_r
#define yyleng yyg->yyleng_r
#define yytext yyg->yytext_r
#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
#define yy_flex_debug yyg->yy_flex_debug_r
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin, yyscanner)
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state* YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
#define YY_LINENO_REWIND_TO(ptr)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do { \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg); \
*yy_cp = yyg->yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} while (0)
#define unput(c) yyunput(c, yyg->yytext_ptr, yyscanner)
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state {
FILE* yy_input_file;
char* yy_ch_buf; /* input buffer */
char* yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
int yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER (yyg->yy_buffer_stack ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] : NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
void yyrestart(FILE* input_file, yyscan_t yyscanner);
void yy_switch_to_buffer(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner);
YY_BUFFER_STATE yy_create_buffer(FILE* file, int size, yyscan_t yyscanner);
void yy_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner);
void yy_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner);
void yypush_buffer_state(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner);
void yypop_buffer_state(yyscan_t yyscanner);
static void yyensure_buffer_stack(yyscan_t yyscanner);
static void yy_load_buffer_state(yyscan_t yyscanner);
static void yy_init_buffer(YY_BUFFER_STATE b, FILE* file, yyscan_t yyscanner);
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER, yyscanner)
YY_BUFFER_STATE yy_scan_buffer(char* base, yy_size_t size, yyscan_t yyscanner);
YY_BUFFER_STATE yy_scan_string(const char* yy_str, yyscan_t yyscanner);
YY_BUFFER_STATE yy_scan_bytes(const char* bytes, int len, yyscan_t yyscanner);
void* yyalloc(yy_size_t, yyscan_t yyscanner);
void* yyrealloc(void*, yy_size_t, yyscan_t yyscanner);
void yyfree(void*, yyscan_t yyscanner);
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if (!YY_CURRENT_BUFFER) { \
yyensure_buffer_stack(yyscanner); \
YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if (!YY_CURRENT_BUFFER) { \
yyensure_buffer_stack(yyscanner); \
YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define hsql_wrap(yyscanner) (/*CONSTCOND*/ 1)
#define YY_SKIP_YYWRAP
typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
static yy_state_type yy_get_previous_state(yyscan_t yyscanner);
static yy_state_type yy_try_NUL_trans(yy_state_type current_state, yyscan_t yyscanner);
static int yy_get_next_buffer(yyscan_t yyscanner);
static void yynoreturn yy_fatal_error(const char* msg, yyscan_t yyscanner);
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yyg->yytext_ptr = yy_bp; \
yyleng = (int)(yy_cp - yy_bp); \
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 170
#define YY_END_OF_BUFFER 171
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info {
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static const flex_int16_t yy_accept[1192] = {
0, 0, 0, 167, 167, 2, 2, 171, 169, 4, 4, 169, 169, 158, 165, 158, 158, 162, 158, 158, 158, 164, 164,
164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 158,
167, 168, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 153, 0, 1, 0, 160,
159, 162, 155, 154, 152, 156, 164, 164, 164,
164, 164, 164, 123, 164, 124, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164,
164, 164, 164, 164, 164, 164, 164, 125, 164, 164, 126, 127, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164,
164, 128, 129, 130, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 131, 164,
164, 164, 164, 164, 164, 164, 164, 164, 157, 167, 166, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 163, 0, 159, 111, 164, 112, 164, 164, 113, 164, 114, 164, 164, 164, 164, 164, 164, 164,
164, 164, 164, 164, 164, 164, 135, 164,
164, 164, 164, 164, 164, 164, 164, 164, 164, 115, 164, 164, 164, 164, 164, 164, 164, 164, 164, 116, 164, 164, 164,
164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 117, 164, 164, 118, 164, 164, 164, 164, 164, 164, 164, 164, 164,
164, 119, 164, 164, 120, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 121, 164, 164, 164,
164, 164, 164, 164, 164, 164, 122, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 0, 164, 164, 164, 164, 164, 164, 164, 82, 164, 83, 45, 84, 164, 164, 164, 85, 164, 164,
86, 141, 164, 164, 164, 164, 164, 88, 164, 164, 164, 89, 90, 164, 164, 164, 164, 164, 164, 164, 91, 164, 164,
92, 93, 164, 164, 94, 164, 95, 134, 164, 164, 164, 164, 164, 164, 96, 164, 97, 98, 99, 164, 101, 164, 102,
164, 164, 164, 164, 103, 164, 164, 164, 164, 164, 104, 164, 164, 32, 164, 164, 164, 164, 164, 164, 164, 105, 164,
164, 164, 164, 164, 106, 107, 30, 164,
144, 164, 164, 164, 164, 164, 164, 164, 164, 108, 164, 109, 164, 110, 137, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 0, 62, 63, 164, 64, 164, 147, 164, 164, 164, 164, 164, 164, 164, 65, 164, 164, 164, 164, 164,
66, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 145, 67, 164, 164, 68, 164, 140, 100, 164, 69, 70, 164,
164, 164, 164, 71, 72, 73, 74, 164, 136, 164, 164, 164, 75, 76, 164, 164, 164, 164, 164, 77, 164, 164, 164,
164, 164, 164, 164, 78, 164, 164, 164,
164, 79, 164, 164, 164, 80, 164, 164, 164, 81, 143, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 0, 164, 35, 164,
164, 164, 36, 149, 164, 37, 164, 164, 164, 164, 38, 164, 39, 164, 40, 41, 42, 164, 43, 164, 164, 46, 47,
48, 49, 50, 164, 164, 164, 51, 133, 142, 164, 164, 52, 164, 164, 164, 53, 164, 164, 54, 132, 55, 164, 56,
164, 57, 164, 164, 164, 164, 58, 59, 60, 61, 164, 164, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 15, 16,
17, 164, 18, 19, 164, 164, 31, 20, 164, 164, 21, 22, 44, 23, 164, 164, 139, 24, 164, 164, 25, 26, 164,
164, 27, 138, 164, 28, 164, 164, 164, 164, 29, 34, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 0, 164, 87, 164, 10, 11,
164, 150, 12, 164, 13, 148, 33, 164, 164, 164, 14, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 0, 164, 164, 7, 164, 8, 9, 164, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0,
5, 6, 164, 2, 2, 2, 2, 2, 0, 0, 146, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0,
0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0, 151, 2, 2, 0, 2, 0, 2, 161, 2, 0
};
static const YY_CHAR yy_ec[256] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 4, 5, 1, 1, 6, 1, 7, 6, 6, 6, 6, 6, 8, 9, 6, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 6, 6, 20, 21, 22, 6, 1, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 6, 1, 6, 6, 49, 1, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 6, 76, 6, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
static const YY_CHAR yy_meta[77] = {0, 1, 1, 2, 1, 3, 1, 4, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1};
static const flex_int16_t yy_base[1199] = {
0, 0, 0, 581, 574, 76, 0, 573, 4737, 151, 153, 547, 0, 4737, 4737, 149, 148,
160, 159, 535, 532, 156, 156, 164, 162, 172, 223, 198, 211, 215, 151, 168, 210, 255,
257, 263, 262, 0, 277, 317, 360, 296, 221, 258, 171, 476, 0, 530, 0, 295, 308,
515, 516, 0, 0, 317, 418, 429, 317, 499, 496, 448, 524, 578, 630, 678, 730, 338,
436, 778, 330, 319, 349, 444, 830, 878, 500, 321, 511, 928, 980, 556, 512, 533, 431,
437, 347, 4737, 507, 4737, 485, 1045, 1055, 1066, 4737, 4737, 4737, 4737, 0, 174, 253,
438, 469, 284, 318, 567, 0, 538, 339, 578, 361, 591, 621, 607, 417, 429, 436, 453,
489, 641, 515, 521, 520, 537, 556, 568, 590, 594, 659, 601, 608, 0, 628, 625, 675,
633, 650, 644, 674, 674, 697, 673, 679, 685, 681, 689, 701, 722, 726, 0, 729, 714,
719, 740, 738, 766, 737, 734, 741, 776, 739, 776, 768, 786, 787, 785, 788, 782, 783,
800, 793, 796, 824, 822, 832, 833, 819, 840, 4737, 0, 4737, 0, 399, 0, 491, 0,
453, 1076, 1086, 1097, 0, 0, 0, 0, 838, 849, 866, 882, 923, 890, 934,
967, 868, 971, 1094, 1142, 952, 977, 1194, 1091, 1092, 1093, 1096, 1107, 1146, 1244, 1152, 1184,
1196, 1185, 1200, 1229, 1230, 1252, 1270, 1265, 1278, 880, 1296, 1136, 1345, 1293, 1304, 1128, 1306,
1322, 1341, 1226, 1347, 1370, 1268, 1358, 1375, 1384, 1398, 1234, 1413, 1401, 1410, 1424, 1415, 1456,
1434, 1466, 1455, 1489, 1464, 1498, 1495, 1510, 1520, 1519, 1528, 1541, 1532, 1562, 1573, 1564, 1583,
1595, 1586, 1574, 1597, 1596, 0, 4737, 452, 1662, 0, 837, 0, 844, 877, 0, 924, 0,
923, 970, 968, 981, 1640, 1082, 1081, 1090, 1084, 1082, 1164, 1147, 1170, 1168, 1217,
1305, 1323, 1641, 1364, 1376, 1399, 1435, 1442, 1472, 0, 1482, 1507, 1526, 1512, 1522, 1558, 1617,
1632, 1638, 1628, 1629, 1650, 1663, 1646, 1663, 1665, 1655, 1658, 1666, 1663, 1674, 1675, 1676, 1678,
1661, 1670, 0, 1665, 1681, 1681, 1687, 1694, 1689, 1690, 1678, 1680, 1693, 0, 1703, 1698, 1700,
1716, 1720, 1727, 1715, 1714, 1718, 1720, 1732, 1714, 1727, 1724, 1732, 1723, 1734, 0, 1717, 1732,
1725, 1727, 1737, 1734, 1731, 1739, 1749, 0, 1754, 1765, 1758, 1754, 1781, 1769, 1763, 1782, 1763,
1767, 1774, 1781, 1772, 0, 450, 1832, 1813, 1825, 1826, 1827, 1828, 1829, 1838, 1830,
1859, 1863, 1864, 1880, 1897, 1888, 1903, 1905, 1851, 1916, 1933, 1931, 1921, 1947, 1942, 1955, 1970,
1964, 1983, 1965, 1998, 1999, 2004, 1987, 2000, 2009, 2001, 2035, 2038, 2037, 2041, 2039, 2043, 2073,
2067, 2083, 2092, 2077, 2089, 2095, 2107, 2108, 2131, 2137, 2146, 2113, 2121, 2145, 2149, 2147, 2179,
2162, 2180, 2177, 2181, 2203, 2191, 2217, 2231, 2205, 2220, 2239, 2216, 2234, 2256, 2257, 2245, 2253,
2274, 2279, 2291, 2285, 2307, 2313, 2308, 2319, 2310, 2325, 2343, 2331, 2342, 2347, 2361, 2356, 2364,
2393, 2385, 2382, 2401, 2387, 2399, 2416, 2422, 2435, 2441, 2457, 2456, 2444, 2475, 2479,
2439, 2485, 2490, 2496, 448, 1828, 1830, 1879, 1975, 2036, 2280, 2348, 0, 2363, 0, 0, 2381,
2493, 2503, 2495, 0, 2496, 2499, 2499, 0, 2508, 2510, 2503, 2512, 2533, 2517, 2533, 2529, 2532,
0, 0, 2533, 2536, 2532, 2534, 2554, 2555, 2552, 0, 2538, 2559, 0, 0, 2563, 2550, 0,
2553, 0, 2549, 2564, 2552, 2548, 2555, 2556, 2568, 0, 2565, 0, 0, 0, 2558, 0, 2576,
0, 2584, 2587, 2582, 2574, 0, 2595, 2598, 2590, 2591, 2597, 0, 2610, 2611, 0, 2601, 2600,
2600, 2619, 2609, 2609, 2621, 0, 2614, 2622, 2619, 2624, 2616, 0, 0, 2613, 2621,
0, 2639, 2629, 2623, 2645, 2632, 2650, 2655, 2653, 0, 2641, 0, 2658, 0, 2645, 438, 2660,
2675, 2669, 2670, 2678, 2672, 2693, 2694, 2710, 2704, 2709, 2727, 2726, 2728, 2745, 2742, 2763, 2766,
2764, 2767, 2781, 2796, 2782, 2797, 2799, 2820, 2832, 2834, 2835, 2821, 2836, 2853, 2866, 2858, 2872,
2875, 2888, 2870, 2876, 2906, 2916, 2907, 2910, 2924, 2918, 2932, 2940, 2941, 2950, 2942, 2972, 2955,
2973, 2983, 3004, 2978, 3007, 2995, 3008, 3009, 3032, 3018, 3043, 3026, 3037, 3061, 3066, 3058, 3040,
3091, 3072, 3094, 3097, 3112, 3095, 3129, 3130, 3128, 3143, 3145, 3146, 3167, 3154, 3186,
3182, 3183, 3197, 3196, 3208, 3198, 3226, 3200, 3221, 3237, 3238, 3234, 3242, 3250, 3256, 3275, 3290,
3280, 3274, 3288, 3292, 3304, 3296, 3306, 3314, 3328, 413, 0, 0, 2655, 0, 2711, 0, 2712,
2744, 2746, 2740, 2785, 2808, 2931, 0, 2980, 2984, 3086, 3093, 3104, 0, 3102, 3169, 3196, 3260,
3266, 3296, 3298, 3311, 3325, 3332, 0, 0, 3321, 3337, 0, 3343, 0, 0, 3331, 0, 0,
3334, 3350, 3345, 3347, 0, 0, 0, 0, 3358, 3346, 3368, 3362, 3351, 0, 0, 3367, 3355,
3357, 3374, 3374, 0, 3383, 3384, 3383, 3368, 3380, 3389, 3394, 3382, 3385, 3384, 3404,
3406, 0, 3403, 3405, 3408, 0, 3398, 3417, 3418, 0, 0, 409, 3416, 3418, 3428, 3424, 3432,
3433, 3434, 3447, 3458, 3457, 3472, 3486, 3442, 3468, 3497, 3498, 3507, 3502, 3511, 3512, 3537, 3540,
3542, 3526, 3543, 3556, 3565, 3552, 3577, 3596, 3575, 3586, 3600, 3610, 3591, 3626, 3605, 3609, 3634,
3631, 3639, 3645, 3648, 3650, 3662, 3663, 3679, 3680, 3684, 3685, 3688, 3717, 3698, 3719, 3703, 3716,
3721, 3738, 3742, 3733, 3752, 3747, 3775, 3777, 3787, 3776, 3788, 3806, 3816, 3811, 3817, 3827, 3845,
3850, 3801, 3829, 3860, 3851, 3855, 3879, 3885, 3894, 3883, 3884, 404, 3437, 0, 3511,
3521, 3546, 3560, 0, 3607, 0, 3685, 3724, 3747, 3742, 0, 3796, 0, 3842, 0, 0, 0,
3861, 0, 3853, 3876, 0, 0, 0, 0, 0, 3882, 3896, 3904, 0, 3887, 0, 3902, 3917,
0, 3900, 3916, 3899, 0, 3926, 3927, 3915, 3919, 0, 3925, 0, 3928, 0, 3941, 3942, 3941,
3929, 0, 0, 0, 0, 3932, 3940, 403, 3948, 3949, 3950, 3953, 3963, 3967, 3979, 3982, 3984,
3993, 4017, 4012, 4003, 4007, 4036, 4021, 4049, 4035, 4038, 4051, 4052, 4053, 4057, 4075, 4061, 4067,
4086, 4089, 4091, 4092, 4101, 4107, 4115, 4123, 4120, 4124, 4129, 4126, 4145, 4141, 4155,
4157, 4180, 4181, 4169, 4195, 4166, 4194, 4191, 4212, 4197, 4229, 4235, 4245, 4233, 4220, 4234, 4237,
4251, 4266, 4283, 407, 0, 0, 0, 3958, 0, 0, 3998, 4047, 0, 0, 4163, 4184, 0,
0, 0, 0, 4225, 4261, 0, 0, 4256, 4273, 0, 0, 4259, 4271, 0, 0, 4270, 0,
4274, 4280, 4274, 4291, 0, 0, 404, 4299, 4302, 4305, 4307, 4308, 4311, 4320, 4337, 4321, 4323,
4324, 4359, 4336, 4342, 4345, 4353, 4377, 4378, 4361, 4376, 4394, 4390, 4391, 4393, 4415, 4416, 4399,
4427, 4433, 4431, 4432, 4456, 4450, 4461, 4466, 4467, 401, 4326, 0, 4367, 0, 0,
4413, 0, 0, 4431, 0, 0, 0, 4448, 4458, 4469, 0, 399, 4485, 4482, 4484, 4490, 4501,
4507, 4515, 4516, 4520, 4518, 4519, 4524, 4530, 4541, 4555, 4553, 395, 404, 4556, 0, 4544, 0,
0, 4554, 350, 4594, 4570, 4572, 4581, 4576, 4578, 4606, 344, 4612, 0, 0, 4575, 342, 4614,
4593, 4607, 4615, 338, 4613, 0, 335, 4614, 4612, 330, 4605, 325, 4617, 306, 4618, 303, 4624,
288, 4642, 255, 4643, 250, 4639, 245, 4640, 243, 4648, 240, 4650, 235, 4737, 221, 0, 226,
197, 187, 173, 4737, 0, 4737, 4706, 4711, 181, 4716, 4721, 4726, 4731
};
static const flex_int16_t yy_def[1199] = {
0, 1191, 1, 1192, 1192, 1191, 5, 1191, 1191, 1191, 1191, 1191, 1193, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1191, 1195, 1191, 1196, 1196, 1191,
1196, 1197, 1196, 1196, 1196, 1196, 1196, 1196, 1196, 1196, 1198, 1198, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
1196, 1191, 1191, 1193, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1191, 1195, 1191, 1196, 1196, 1196, 1197, 1196,
1196, 1196, 1196, 1196, 1196, 1196, 1196, 1196, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 1196, 1191, 1191, 1191, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1196, 1196, 1196, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 1191, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1196, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 1191, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1196, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1191, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1196, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 1191, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1196, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 1191, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1196, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1191, 1194, 1194, 1194, 1194, 1194,
1194, 1194, 1196, 62, 62, 62, 62, 62, 62, 62, 1191, 1191, 1194, 1194, 1194, 1196, 1196,
62, 62, 62, 1191, 1191, 1194, 1196, 1196, 62, 1191, 1191, 1196, 1196, 1191, 1191, 1196, 1196,
1191, 1191, 1196, 1196, 1191, 1191, 1196, 1196, 1191, 1191, 1196, 1196, 1191, 1191, 1196, 1196, 1191,
1196, 1191, 1196, 1191, 1196, 0, 1191, 1191, 1191, 1191, 1191, 1191, 1191
};
static const flex_int16_t yy_nxt[4814] = {
0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 37, 44, 37, 8, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 37, 44, 37, 45, 48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 77, 84, 77, 48, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 77, 84, 77,
85, 86, 86, 86, 86, 89, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90,
92, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 94, 95, 99, 105, 100, 111,
98, 107, 136, 112, 101, 1190, 102, 113, 108, 137, 103, 104, 177, 114, 278,
109, 115, 106, 110, 1189, 116, 1188, 117, 99, 105, 100, 111, 118, 107, 136, 112, 101,
119, 102, 113, 108, 137, 103, 104, 177, 114, 278, 109, 115, 106, 110, 126, 116, 128,
117, 1187, 138, 127, 1186, 118, 139, 129, 131, 173, 119, 120, 140, 130, 132, 133, 134,
174, 1185, 121, 1183, 135, 122, 1181, 126, 123, 128, 1179, 124, 138, 127, 125, 1177, 139,
129, 131, 173, 1175, 120, 140, 130, 132, 133, 134, 174, 144, 121, 141, 135, 122, 152,
142, 123, 175, 176, 124, 148, 143, 125, 145, 279, 153, 182, 86, 149, 146,
147, 154, 150, 155, 1173, 151, 144, 156, 141, 86, 86, 152, 142, 157, 175, 176, 1171,
148, 143, 1169, 145, 279, 153, 284, 185, 149, 146, 147, 154, 150, 155, 170, 151, 171,
156, 186, 172, 190, 191, 1167, 157, 158, 285, 159, 1165, 233, 160, 194, 86, 86, 284,
161, 1163, 162, 163, 1161, 194, 1158, 170, 1155, 171, 291, 1150, 172, 194, 194, 232, 194,
158, 285, 159, 222, 233, 160, 194, 234, 194, 223, 161, 235, 162, 163, 164, 194, 194,
236, 165, 296, 291, 166, 167, 194, 194, 232, 194, 194, 168, 297, 222, 169,
182, 86, 234, 194, 223, 1146, 235, 1145, 1137, 164, 1129, 194, 236, 165, 296, 1112, 166,
167, 1095, 1058, 1021, 959, 194, 168, 297, 897, 169, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 181, 181, 812,
181, 181, 181, 181, 181, 181, 273, 224, 307, 727, 616, 194, 505, 391, 308, 225, 181,
181, 181, 237, 280, 226, 195, 238, 196, 309, 194, 310, 281, 239, 197, 194, 198, 273,
224, 307, 199, 200, 194, 194, 282, 308, 225, 283, 390, 276, 237, 280, 226,
195, 238, 196, 309, 194, 310, 281, 239, 197, 194, 198, 275, 274, 311, 199, 200, 193,
194, 282, 192, 181, 283, 248, 181, 181, 181, 194, 181, 181, 181, 181, 181, 181, 249,
269, 183, 180, 251, 194, 250, 311, 252, 270, 181, 181, 181, 194, 253, 317, 248, 201,
178, 97, 194, 318, 96, 319, 194, 194, 194, 249, 269, 271, 272, 251, 194, 250, 87,
252, 270, 202, 289, 1191, 194, 253, 317, 320, 201, 290, 194, 47, 318, 194, 319, 194,
194, 194, 47, 1191, 271, 272, 266, 321, 267, 286, 287, 268, 202, 289, 181,
203, 322, 194, 320, 194, 290, 194, 204, 288, 194, 1191, 292, 293, 294, 205, 295, 1191,
206, 266, 321, 267, 286, 287, 268, 194, 1191, 323, 203, 322, 194, 324, 194, 298, 1191,
204, 288, 327, 299, 292, 293, 294, 205, 295, 300, 206, 301, 305, 306, 302, 1191, 328,
194, 207, 323, 303, 1191, 208, 324, 329, 298, 209, 304, 330, 327, 299, 312, 210, 313,
335, 211, 300, 314, 301, 305, 306, 302, 194, 328, 315, 207, 336, 303, 316, 208, 1191,
329, 1191, 209, 304, 330, 337, 1191, 312, 210, 313, 335, 211, 1191, 314, 325,
331, 338, 326, 194, 194, 315, 339, 336, 340, 316, 332, 212, 344, 213, 345, 333, 334,
337, 214, 341, 346, 342, 347, 215, 194, 1191, 325, 331, 338, 326, 348, 194, 343, 339,
349, 340, 1191, 332, 212, 344, 213, 345, 333, 334, 350, 214, 341, 346, 342, 347, 215,
194, 216, 351, 352, 353, 194, 348, 354, 343, 217, 349, 355, 218, 356, 361, 219, 362,
357, 220, 363, 350, 221, 1191, 1191, 367, 194, 1191, 1191, 216, 351, 352, 353, 194, 1191,
354, 1191, 217, 358, 355, 218, 356, 361, 219, 362, 357, 220, 363, 368, 221,
364, 359, 367, 194, 194, 227, 360, 369, 370, 365, 371, 228, 229, 230, 374, 358, 375,
366, 231, 372, 376, 381, 377, 379, 194, 368, 380, 364, 359, 1191, 373, 194, 227, 360,
369, 370, 365, 371, 228, 229, 230, 374, 378, 375, 366, 231, 372, 376, 381, 377, 379,
194, 240, 380, 382, 383, 194, 373, 385, 387, 388, 384, 389, 506, 194, 1191, 241, 1191,
1191, 378, 507, 386, 242, 243, 393, 194, 194, 1191, 1191, 240, 1191, 382, 383, 194, 194,
385, 387, 388, 384, 389, 506, 194, 194, 241, 194, 194, 1191, 507, 386, 242,
243, 393, 194, 194, 194, 244, 194, 394, 194, 1191, 508, 194, 194, 245, 194, 395, 194,
246, 1191, 194, 247, 194, 194, 396, 194, 1191, 194, 1191, 194, 399, 1191, 194, 244, 194,
394, 194, 194, 508, 1191, 194, 245, 194, 395, 194, 246, 397, 509, 247, 398, 194, 396,
194, 254, 194, 255, 194, 399, 256, 400, 510, 194, 1191, 257, 194, 258, 259, 1191, 1191,
1191, 194, 1191, 1191, 397, 509, 194, 398, 194, 1191, 411, 254, 194, 255, 1191, 1191, 256,
400, 510, 194, 412, 257, 1191, 258, 259, 194, 401, 402, 194, 194, 194, 1191,
511, 194, 260, 194, 404, 411, 261, 194, 403, 262, 263, 405, 512, 194, 513, 412, 264,
194, 413, 265, 194, 401, 402, 414, 194, 194, 194, 511, 1191, 260, 194, 404, 1191, 261,
1191, 403, 262, 263, 405, 512, 194, 513, 1191, 264, 194, 413, 265, 1191, 1191, 1191, 414,
1191, 1191, 194, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 277, 277, 277, 277,
277, 277, 277, 277, 277, 277, 92, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187, 392, 392, 392, 392, 392,
392, 392, 392, 392, 392, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 406,
194, 194, 194, 194, 517, 194, 518, 519, 520, 1191, 1191, 521, 423, 420, 421, 425, 194,
422, 1191, 424, 194, 194, 194, 194, 1191, 194, 406, 194, 194, 194, 194, 517, 194, 518,
519, 520, 194, 194, 521, 423, 420, 421, 425, 194, 422, 194, 424, 194, 194, 194, 194,
194, 194, 426, 1191, 194, 445, 452, 407, 408, 409, 194, 410, 194, 194, 194, 1191, 1191,
432, 522, 523, 194, 194, 1191, 1191, 194, 1191, 1191, 194, 524, 426, 194, 194,
445, 452, 407, 408, 409, 194, 410, 1191, 525, 194, 194, 194, 432, 522, 523, 194, 415,
433, 416, 194, 194, 417, 194, 524, 435, 194, 194, 418, 1191, 1191, 194, 194, 434, 1191,
419, 525, 436, 194, 194, 1191, 194, 1191, 194, 415, 433, 416, 194, 194, 417, 194, 526,
435, 194, 194, 418, 194, 194, 194, 194, 434, 194, 419, 437, 436, 1191, 459, 438, 194,
427, 194, 428, 1191, 194, 194, 429, 194, 194, 526, 194, 194, 194, 430, 194, 194, 1191,
431, 1191, 194, 439, 437, 194, 194, 459, 438, 194, 427, 194, 428, 194, 194,
442, 429, 194, 194, 194, 194, 1191, 194, 430, 462, 440, 194, 431, 441, 194, 439, 194,
194, 194, 194, 443, 194, 194, 194, 194, 194, 444, 442, 450, 1191, 194, 194, 194, 453,
451, 527, 462, 440, 194, 194, 441, 194, 194, 194, 1191, 528, 194, 443, 194, 194, 194,
194, 194, 444, 454, 450, 455, 194, 1191, 194, 453, 451, 527, 456, 1191, 457, 194, 194,
194, 194, 446, 194, 528, 194, 1191, 194, 458, 194, 1191, 194, 447, 454, 460, 455, 194,
448, 449, 194, 531, 1191, 456, 194, 457, 194, 194, 194, 194, 446, 194, 463,
194, 194, 532, 458, 194, 461, 465, 447, 464, 460, 194, 194, 448, 449, 194, 531, 194,
1191, 194, 1191, 194, 194, 1191, 194, 194, 466, 463, 194, 194, 532, 194, 194, 461, 465,
1191, 464, 194, 194, 467, 194, 533, 471, 468, 194, 194, 472, 470, 194, 194, 469, 194,
194, 466, 1191, 194, 1191, 194, 194, 534, 194, 194, 194, 476, 194, 1191, 467, 194, 533,
471, 468, 194, 194, 472, 470, 194, 1191, 469, 194, 473, 535, 194, 194, 194, 194, 478,
534, 194, 194, 194, 476, 194, 474, 194, 1191, 1191, 1191, 475, 194, 536, 477,
482, 194, 194, 1191, 537, 473, 535, 194, 194, 194, 194, 478, 194, 479, 1191, 194, 1191,
194, 474, 194, 483, 194, 480, 475, 194, 536, 477, 482, 194, 194, 481, 537, 485, 538,
484, 194, 194, 194, 1191, 194, 479, 194, 194, 486, 194, 194, 194, 483, 194, 480, 539,
194, 540, 487, 489, 541, 194, 481, 194, 485, 538, 484, 194, 194, 488, 194, 194, 194,
194, 491, 486, 194, 194, 194, 194, 490, 1191, 539, 194, 540, 487, 489, 541, 194, 492,
194, 1191, 194, 194, 496, 194, 488, 194, 194, 194, 1191, 491, 542, 1191, 194,
502, 194, 490, 494, 493, 194, 495, 1191, 194, 194, 194, 492, 500, 497, 194, 194, 496,
194, 504, 194, 194, 194, 194, 194, 542, 501, 194, 502, 498, 194, 494, 493, 194, 495,
499, 194, 194, 194, 503, 500, 497, 194, 194, 194, 1191, 504, 194, 194, 194, 194, 194,
1191, 501, 1191, 1191, 498, 194, 543, 544, 194, 545, 499, 546, 547, 514, 503, 515, 529,
194, 194, 194, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 516, 530, 548, 543,
544, 549, 545, 550, 546, 547, 514, 551, 515, 529, 552, 553, 554, 555, 556,
557, 558, 559, 562, 560, 563, 564, 565, 516, 530, 548, 566, 567, 549, 561, 550, 568,
569, 570, 551, 571, 572, 552, 553, 554, 555, 556, 557, 558, 559, 562, 560, 563, 564,
565, 573, 574, 575, 566, 567, 576, 561, 577, 568, 569, 570, 578, 571, 572, 579, 580,
581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 573, 574, 575, 592, 593, 576,
594, 577, 595, 596, 597, 578, 598, 599, 579, 580, 581, 582, 583, 584, 585, 586, 587,
588, 589, 590, 591, 600, 605, 601, 592, 593, 603, 594, 604, 595, 596, 597,
602, 598, 599, 606, 607, 608, 609, 610, 611, 612, 614, 615, 1191, 613, 1191, 1191, 600,
605, 601, 1191, 1191, 603, 1191, 604, 1191, 1191, 1191, 602, 1191, 1191, 606, 607, 608, 609,
610, 611, 612, 614, 615, 194, 613, 392, 392, 392, 392, 392, 392, 392, 392, 392, 392,
617, 194, 618, 194, 194, 194, 1191, 1191, 194, 620, 619, 1191, 1191, 194, 1191, 194, 728,
1191, 729, 1191, 194, 194, 194, 194, 194, 194, 194, 617, 194, 618, 194, 194, 194, 194,
194, 194, 620, 619, 194, 194, 194, 631, 622, 728, 621, 729, 194, 194, 194,
194, 194, 194, 194, 194, 194, 194, 1191, 623, 194, 194, 194, 194, 624, 194, 1191, 194,
194, 1191, 631, 622, 625, 621, 626, 194, 730, 194, 628, 1191, 194, 1191, 194, 194, 194,
194, 623, 194, 194, 627, 630, 624, 194, 194, 194, 1191, 629, 1191, 635, 625, 194, 626,
194, 730, 194, 628, 633, 194, 194, 194, 194, 1191, 194, 632, 1191, 1191, 627, 630, 194,
194, 194, 194, 634, 629, 194, 635, 637, 194, 194, 194, 194, 1191, 194, 633, 1191, 194,
638, 194, 636, 194, 632, 640, 643, 639, 194, 194, 194, 194, 1191, 634, 1191,
194, 194, 637, 1191, 194, 641, 194, 642, 194, 194, 194, 194, 638, 647, 636, 194, 194,
640, 643, 639, 194, 731, 645, 194, 194, 194, 194, 649, 194, 194, 194, 648, 641, 194,
642, 194, 194, 194, 194, 644, 647, 646, 1191, 194, 194, 194, 194, 194, 731, 645, 194,
194, 194, 194, 649, 194, 194, 194, 648, 650, 194, 194, 194, 194, 194, 194, 644, 194,
646, 655, 652, 194, 194, 194, 194, 732, 1191, 194, 651, 654, 653, 194, 194, 194, 194,
194, 650, 194, 194, 194, 194, 194, 194, 194, 194, 656, 655, 652, 1191, 194,
660, 657, 732, 194, 1191, 651, 654, 653, 194, 194, 194, 194, 194, 194, 194, 194, 194,
658, 194, 194, 194, 194, 656, 194, 662, 659, 194, 660, 657, 194, 194, 661, 1191, 194,
194, 194, 194, 663, 194, 668, 194, 194, 194, 1191, 658, 194, 194, 669, 194, 664, 194,
662, 659, 194, 194, 1191, 194, 194, 661, 194, 194, 194, 194, 194, 663, 194, 668, 194,
194, 666, 665, 670, 194, 194, 669, 671, 664, 194, 1191, 1191, 194, 194, 667, 194, 194,
672, 194, 1191, 194, 673, 194, 194, 194, 194, 194, 194, 666, 665, 670, 194,
194, 1191, 671, 676, 194, 194, 194, 194, 194, 667, 194, 677, 672, 679, 674, 194, 673,
194, 194, 194, 194, 675, 194, 194, 1191, 194, 194, 194, 678, 194, 676, 194, 194, 194,
194, 194, 1191, 194, 677, 1191, 679, 674, 194, 194, 194, 680, 194, 682, 675, 194, 194,
194, 194, 194, 194, 678, 194, 194, 194, 681, 194, 683, 194, 194, 194, 194, 194, 685,
1191, 194, 194, 688, 680, 194, 682, 1191, 194, 194, 194, 689, 194, 684, 194, 194, 194,
194, 681, 194, 683, 194, 194, 194, 194, 194, 685, 686, 690, 687, 688, 194,
194, 1191, 194, 194, 194, 194, 689, 194, 684, 194, 194, 194, 194, 1191, 691, 733, 1191,
194, 194, 693, 194, 1191, 686, 690, 687, 194, 194, 194, 692, 194, 194, 194, 194, 194,
194, 695, 194, 194, 194, 194, 694, 691, 733, 698, 194, 194, 693, 194, 697, 696, 1191,
699, 194, 194, 194, 692, 194, 701, 194, 194, 194, 194, 695, 194, 194, 194, 194, 694,
194, 194, 698, 194, 194, 194, 734, 697, 696, 194, 699, 700, 194, 194, 194, 194, 701,
735, 194, 194, 194, 194, 194, 702, 194, 194, 703, 194, 194, 704, 194, 1191,
194, 734, 194, 736, 194, 705, 700, 194, 194, 194, 194, 194, 735, 710, 194, 194, 194,
194, 702, 194, 194, 703, 707, 708, 704, 194, 706, 194, 194, 194, 736, 194, 705, 194,
194, 194, 709, 194, 194, 194, 710, 1191, 194, 1191, 1191, 194, 194, 194, 712, 707, 708,
711, 194, 706, 194, 194, 1191, 713, 194, 1191, 194, 194, 194, 709, 1191, 194, 194, 194,
194, 194, 194, 714, 194, 715, 194, 712, 1191, 716, 711, 717, 722, 194, 194, 194, 713,
194, 719, 194, 194, 194, 194, 718, 194, 1191, 194, 194, 1191, 194, 714, 720,
715, 194, 194, 194, 716, 194, 717, 722, 194, 194, 194, 194, 194, 719, 194, 1191, 194,
194, 718, 725, 723, 194, 194, 721, 724, 194, 720, 737, 194, 194, 194, 194, 194, 738,
739, 726, 194, 740, 194, 741, 742, 743, 194, 194, 744, 745, 725, 723, 194, 194, 721,
724, 194, 746, 737, 747, 748, 749, 194, 750, 738, 739, 726, 194, 740, 751, 741, 742,
743, 194, 752, 744, 745, 753, 754, 755, 756, 757, 758, 759, 746, 760, 747, 748, 749,
761, 750, 762, 763, 764, 765, 766, 751, 767, 768, 769, 770, 752, 772, 773,
753, 754, 755, 756, 757, 758, 759, 771, 760, 774, 775, 778, 761, 779, 762, 763, 764,
765, 766, 780, 767, 768, 769, 770, 781, 772, 773, 776, 777, 782, 783, 784, 785, 786,
771, 787, 774, 775, 778, 788, 779, 789, 790, 791, 792, 793, 780, 794, 795, 796, 797,
781, 798, 799, 776, 777, 782, 783, 784, 785, 786, 800, 787, 801, 802, 803, 788, 804,
789, 790, 791, 792, 793, 805, 794, 795, 796, 797, 806, 798, 799, 807, 808, 809, 810,
811, 194, 1191, 800, 1191, 801, 802, 803, 1191, 804, 194, 194, 1191, 194, 813,
805, 194, 898, 1191, 194, 806, 194, 818, 807, 808, 809, 810, 811, 194, 814, 815, 816,
817, 194, 819, 194, 194, 194, 194, 194, 194, 813, 1191, 194, 898, 194, 194, 820, 194,
818, 194, 194, 899, 900, 194, 194, 814, 815, 816, 817, 194, 819, 194, 194, 821, 194,
194, 194, 194, 194, 194, 194, 194, 823, 820, 822, 1191, 194, 194, 899, 900, 194, 194,
194, 901, 902, 194, 194, 194, 194, 903, 821, 194, 1191, 194, 194, 194, 194, 194, 824,
823, 1191, 822, 194, 194, 194, 194, 194, 194, 1191, 194, 901, 902, 194, 194,
194, 194, 903, 1191, 825, 827, 826, 194, 194, 194, 194, 824, 194, 194, 828, 194, 194,
194, 194, 194, 194, 832, 194, 194, 830, 194, 904, 194, 194, 1191, 829, 825, 827, 826,
194, 194, 194, 194, 831, 194, 194, 828, 194, 194, 905, 194, 194, 194, 832, 194, 194,
830, 194, 904, 194, 194, 834, 829, 194, 833, 194, 194, 194, 1191, 835, 831, 194, 194,
836, 194, 194, 905, 194, 194, 194, 1191, 1191, 1191, 194, 194, 194, 194, 194, 834, 194,
194, 833, 194, 194, 194, 837, 835, 194, 194, 194, 836, 843, 841, 194, 194,
839, 194, 194, 838, 194, 194, 194, 194, 194, 194, 842, 194, 194, 840, 194, 1191, 194,
837, 194, 194, 1191, 194, 194, 843, 841, 194, 194, 839, 194, 194, 838, 194, 194, 194,
194, 1191, 194, 842, 845, 194, 840, 194, 194, 194, 194, 194, 846, 844, 194, 194, 194,
1191, 194, 194, 1191, 847, 194, 906, 194, 194, 194, 194, 194, 194, 194, 845, 194, 194,
850, 194, 194, 194, 1191, 846, 844, 848, 194, 194, 194, 194, 194, 194, 847, 194, 906,
194, 194, 194, 194, 194, 849, 194, 1191, 194, 194, 850, 194, 194, 194, 194,
852, 194, 848, 194, 194, 194, 1191, 1191, 194, 194, 907, 851, 853, 194, 194, 194, 1191,
849, 194, 194, 908, 194, 854, 194, 194, 194, 194, 852, 194, 194, 194, 194, 855, 194,
194, 194, 194, 907, 851, 853, 857, 194, 1191, 856, 194, 194, 194, 908, 194, 854, 194,
194, 194, 194, 194, 194, 194, 194, 194, 855, 194, 194, 194, 860, 194, 1191, 194, 857,
194, 194, 856, 194, 194, 858, 1191, 1191, 859, 194, 194, 194, 194, 194, 194, 194, 194,
194, 194, 194, 1191, 194, 860, 194, 194, 194, 1191, 863, 194, 864, 866, 194,
858, 861, 862, 859, 194, 194, 1191, 194, 909, 1191, 194, 194, 194, 194, 194, 865, 194,
194, 194, 194, 194, 194, 863, 194, 864, 866, 910, 1191, 861, 862, 911, 194, 912, 867,
194, 909, 868, 194, 194, 194, 194, 194, 865, 194, 194, 194, 869, 194, 194, 1191, 194,
870, 871, 910, 194, 194, 194, 911, 194, 912, 867, 1191, 1191, 868, 194, 194, 1191, 194,
194, 194, 194, 194, 194, 869, 194, 194, 194, 872, 870, 871, 194, 194, 194, 194, 873,
194, 1191, 874, 876, 194, 875, 194, 194, 194, 1191, 1191, 194, 1191, 194, 194,
194, 194, 194, 194, 872, 1191, 878, 194, 194, 194, 913, 873, 194, 194, 874, 876, 194,
875, 194, 194, 194, 877, 880, 194, 882, 1191, 194, 194, 194, 194, 879, 914, 194, 878,
194, 194, 194, 913, 881, 194, 194, 1191, 194, 194, 194, 1191, 194, 194, 877, 880, 194,
882, 194, 194, 194, 194, 194, 879, 914, 194, 194, 194, 883, 194, 194, 881, 886, 194,
194, 194, 194, 194, 194, 194, 194, 1191, 194, 884, 885, 194, 194, 194, 194, 194, 194,
887, 915, 194, 194, 883, 194, 194, 916, 886, 194, 194, 194, 889, 888, 194,
892, 194, 194, 194, 884, 885, 194, 194, 891, 194, 194, 194, 887, 915, 194, 194, 194,
893, 194, 916, 194, 194, 194, 194, 889, 888, 194, 892, 194, 194, 194, 890, 895, 194,
194, 891, 194, 917, 194, 918, 194, 194, 194, 194, 893, 194, 894, 194, 194, 194, 194,
919, 194, 194, 194, 920, 921, 194, 890, 895, 194, 194, 922, 194, 917, 194, 918, 194,
896, 194, 923, 924, 925, 894, 194, 926, 927, 194, 919, 194, 930, 194, 920, 921, 931,
928, 932, 194, 929, 922, 933, 934, 935, 936, 937, 896, 938, 923, 924, 925,
939, 194, 926, 927, 940, 941, 942, 930, 943, 944, 945, 931, 928, 932, 946, 929, 947,
933, 934, 935, 936, 937, 948, 938, 949, 950, 951, 939, 952, 953, 954, 940, 941, 942,
955, 943, 944, 945, 956, 957, 958, 946, 194, 947, 194, 1191, 1191, 1191, 1191, 948, 194,
949, 950, 951, 194, 952, 953, 954, 961, 194, 962, 955, 194, 1022, 194, 956, 957, 958,
968, 194, 194, 194, 963, 194, 194, 960, 1191, 194, 194, 194, 194, 194, 964, 194, 194,
961, 194, 962, 194, 194, 1022, 194, 965, 194, 194, 968, 1191, 194, 194, 963,
194, 194, 960, 194, 194, 194, 194, 194, 1191, 964, 194, 194, 194, 966, 194, 194, 1191,
1191, 194, 965, 194, 194, 967, 194, 194, 194, 1191, 969, 194, 971, 194, 194, 194, 194,
970, 972, 1191, 973, 194, 194, 966, 194, 1191, 194, 194, 194, 1023, 1024, 194, 967, 194,
194, 977, 194, 969, 194, 971, 194, 194, 194, 194, 970, 972, 194, 973, 194, 194, 974,
194, 978, 194, 194, 194, 1023, 1024, 194, 1191, 976, 194, 977, 194, 975, 194, 194, 194,
194, 194, 1025, 194, 194, 194, 194, 981, 194, 974, 194, 978, 979, 194, 194,
1026, 194, 194, 194, 976, 194, 980, 982, 975, 194, 194, 194, 194, 194, 1025, 194, 194,
194, 194, 981, 983, 194, 194, 194, 979, 194, 194, 1026, 194, 194, 194, 194, 194, 980,
982, 194, 194, 194, 194, 194, 1027, 984, 194, 985, 194, 1191, 194, 983, 194, 194, 194,
194, 194, 194, 986, 194, 194, 194, 194, 194, 194, 1191, 194, 194, 194, 194, 1191, 1027,
984, 194, 985, 194, 194, 194, 989, 987, 194, 194, 194, 194, 194, 986, 194, 194, 194,
194, 988, 194, 194, 194, 990, 194, 194, 991, 194, 992, 194, 1191, 194, 194,
1191, 989, 987, 194, 194, 194, 194, 194, 194, 194, 194, 993, 194, 988, 194, 194, 194,
990, 194, 1028, 991, 194, 992, 194, 194, 194, 194, 996, 994, 194, 194, 194, 194, 194,
194, 194, 194, 194, 993, 995, 1191, 194, 194, 194, 194, 194, 1028, 998, 1029, 194, 1191,
194, 194, 194, 996, 994, 194, 194, 194, 1001, 997, 194, 194, 194, 194, 194, 995, 194,
194, 194, 194, 194, 194, 194, 998, 1029, 194, 999, 194, 194, 1030, 1000, 1002, 1031, 194,
1191, 1001, 997, 194, 194, 194, 194, 194, 194, 194, 194, 1191, 1003, 194, 1004,
194, 194, 194, 194, 999, 194, 194, 1030, 1000, 1002, 1031, 194, 1005, 194, 194, 194, 1191,
1006, 1007, 1032, 194, 194, 194, 194, 1003, 194, 1004, 194, 194, 194, 194, 1008, 194, 194,
194, 1191, 1191, 194, 1009, 1005, 194, 194, 194, 194, 1006, 1007, 1032, 194, 194, 194, 194,
1010, 194, 194, 194, 1015, 1011, 194, 1008, 194, 194, 194, 194, 194, 194, 1009, 1033, 1013,
1012, 194, 194, 194, 1014, 194, 194, 194, 194, 1017, 1010, 194, 194, 194, 1015, 1011, 194,
1016, 194, 1034, 1035, 194, 194, 194, 1191, 1033, 1013, 1012, 194, 194, 194, 1014,
194, 194, 194, 194, 1017, 194, 194, 1019, 194, 194, 194, 194, 1016, 194, 1034, 1035, 1020,
1036, 194, 1018, 194, 1037, 1038, 194, 194, 194, 1039, 1040, 194, 194, 194, 194, 194, 194,
1019, 1041, 194, 194, 194, 1042, 194, 1043, 1044, 1020, 1036, 1045, 1018, 194, 1037, 1038, 1046,
1047, 194, 1039, 1040, 1048, 194, 194, 194, 1049, 1050, 1051, 1041, 1052, 1053, 1054, 1042, 194,
1043, 1044, 1055, 1056, 1045, 1057, 1059, 194, 194, 1046, 1047, 1061, 1191, 1191, 1048, 1191, 1096,
1060, 1049, 1050, 1051, 194, 1052, 1053, 1054, 194, 194, 194, 194, 1055, 1056, 194,
1057, 1059, 194, 194, 1062, 194, 1061, 1063, 194, 194, 194, 1096, 1060, 194, 1191, 1064, 194,
1191, 1191, 194, 194, 194, 194, 194, 1097, 194, 194, 1065, 194, 194, 194, 1062, 194, 194,
1063, 194, 194, 194, 194, 194, 194, 1066, 1064, 194, 1068, 1067, 194, 194, 1191, 194, 1191,
1097, 194, 194, 1065, 194, 194, 194, 194, 1069, 194, 194, 194, 194, 194, 194, 194, 194,
1066, 1098, 194, 1068, 1067, 1070, 194, 194, 194, 194, 1071, 194, 194, 194, 194, 194, 194,
194, 1069, 194, 194, 194, 194, 194, 1072, 194, 194, 194, 1098, 194, 194, 194,
1070, 194, 194, 194, 194, 1071, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 1073,
194, 194, 1072, 194, 194, 194, 1191, 194, 194, 194, 1075, 194, 1076, 194, 1074, 194, 194,
194, 194, 1191, 194, 194, 194, 194, 194, 194, 1073, 194, 194, 194, 194, 194, 194, 194,
1079, 194, 194, 1075, 194, 1076, 1078, 1074, 194, 194, 194, 194, 1077, 194, 194, 194, 1081,
194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 1079, 194, 194, 194, 194, 194, 1078,
1191, 1080, 194, 194, 1099, 1077, 194, 194, 194, 1081, 194, 194, 194, 194, 194,
1191, 1082, 194, 194, 1083, 1084, 194, 194, 194, 1085, 194, 1191, 194, 1080, 194, 194, 1099,
194, 194, 194, 194, 194, 194, 194, 1191, 1100, 194, 194, 1082, 1087, 194, 1083, 1084, 194,
194, 1086, 1085, 194, 194, 194, 194, 194, 194, 194, 194, 1088, 194, 194, 194, 1101, 194,
1089, 1100, 194, 194, 194, 1087, 1090, 194, 194, 194, 194, 1086, 194, 194, 194, 194, 194,
194, 1091, 194, 194, 1088, 194, 1092, 194, 1101, 194, 1089, 194, 194, 194, 194, 194, 1090,
194, 194, 194, 194, 1191, 194, 194, 194, 194, 1102, 1103, 1091, 194, 194, 1104,
1105, 1092, 194, 1106, 194, 1093, 194, 194, 194, 194, 194, 1107, 194, 1108, 1109, 1110, 1094,
1111, 194, 194, 1191, 1102, 1103, 1191, 194, 194, 1104, 1105, 194, 194, 1106, 194, 1093, 1113,
194, 1191, 194, 194, 1107, 194, 1108, 1109, 1110, 1094, 1111, 194, 1114, 194, 194, 194, 1116,
194, 194, 194, 194, 194, 194, 194, 194, 1115, 1113, 194, 194, 194, 194, 1130, 194, 194,
194, 194, 194, 194, 194, 1114, 194, 194, 194, 1116, 194, 194, 194, 194, 194, 194, 194,
194, 1115, 194, 194, 194, 194, 194, 1130, 194, 194, 194, 194, 194, 194, 194,
1117, 1118, 194, 194, 194, 194, 194, 194, 1131, 194, 194, 1119, 194, 1191, 194, 194, 1121,
194, 194, 194, 194, 1191, 194, 194, 194, 194, 194, 1117, 1118, 194, 194, 194, 194, 1120,
194, 1131, 194, 194, 1119, 194, 194, 194, 194, 1121, 194, 194, 194, 194, 1123, 194, 194,
194, 194, 194, 1132, 1191, 1122, 194, 194, 194, 1120, 194, 194, 194, 194, 1191, 194, 194,
194, 194, 1133, 1125, 194, 194, 1124, 1123, 194, 194, 194, 194, 194, 1132, 194, 1122, 194,
194, 194, 1128, 194, 194, 1126, 1127, 194, 194, 1134, 1135, 194, 1133, 1125, 1136,
194, 1124, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 1128, 1191, 194,
1126, 1127, 194, 194, 1134, 1135, 194, 1138, 1139, 1136, 194, 194, 194, 194, 194, 1191, 194,
194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 1140, 1191, 194,
1138, 1139, 194, 194, 194, 194, 194, 194, 1141, 194, 194, 194, 194, 194, 194, 194, 194,
194, 194, 194, 194, 194, 194, 194, 1140, 1142, 194, 1143, 194, 194, 194, 1147, 194, 1148,
1144, 1141, 194, 194, 194, 1149, 194, 194, 194, 194, 1151, 1152, 194, 194, 194,
1191, 194, 194, 1142, 194, 1143, 194, 194, 194, 1147, 1157, 1148, 1144, 1146, 194, 1151, 194,
1149, 194, 194, 194, 1153, 194, 1152, 194, 194, 194, 194, 194, 194, 1191, 194, 194, 194,
194, 1162, 1164, 1157, 194, 194, 194, 194, 1154, 194, 1166, 194, 194, 194, 1153, 194, 1160,
194, 194, 194, 194, 1156, 1168, 1159, 194, 194, 194, 194, 1162, 1164, 1170, 194, 194, 194,
194, 1154, 1172, 1166, 1174, 1176, 1178, 1180, 1182, 1160, 1184, 194, 194, 1191, 1156, 1168, 1159,
194, 1191, 1191, 194, 1191, 1191, 1170, 1191, 1191, 1191, 1191, 1191, 1172, 1191, 1174,
1176, 1178, 1180, 1182, 1191, 1184, 46, 46, 46, 46, 46, 88, 1191, 1191, 88, 88, 179,
179, 179, 1191, 179, 181, 1191, 181, 181, 181, 184, 1191, 184, 184, 184, 194, 1191, 194,
194, 194, 7, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191};
static const flex_int16_t yy_chk[4814] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 9, 9, 10, 10, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 15,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 21, 22, 21, 24,
1194, 23, 30, 24, 21, 1188, 21, 24, 23, 31, 21, 21, 44, 24, 99,
23, 24, 22, 23, 1187, 25, 1186, 25, 21, 22, 21, 24, 25, 23, 30, 24, 21,
25, 21, 24, 23, 31, 21, 21, 44, 24, 99, 23, 24, 22, 23, 27, 25, 28,
25, 1185, 32, 27, 1183, 25, 32, 28, 29, 42, 25, 26, 32, 28, 29, 29, 29,
42, 1181, 26, 1179, 29, 26, 1177, 27, 26, 28, 1175, 26, 32, 27, 26, 1173, 32,
28, 29, 42, 1171, 26, 32, 28, 29, 29, 29, 42, 34, 26, 33, 29, 26, 36,
33, 26, 43, 43, 26, 35, 33, 26, 34, 100, 36, 49, 49, 35, 34,
34, 36, 35, 38, 1169, 35, 34, 38, 33, 50, 50, 36, 33, 38, 43, 43, 1167,
35, 33, 1165, 34, 100, 36, 103, 55, 35, 34, 34, 36, 35, 38, 41, 35, 41,
38, 55, 41, 58, 58, 1163, 38, 39, 104, 39, 1161, 71, 39, 77, 86, 86, 103,
39, 1158, 39, 39, 1155, 70, 1150, 41, 1145, 41, 108, 1137, 41, 67, 71, 70, 77,
39, 104, 39, 67, 71, 39, 77, 72, 70, 67, 39, 72, 39, 39, 40, 70, 67,
72, 40, 110, 108, 40, 40, 67, 71, 70, 77, 72, 40, 110, 67, 40,
182, 182, 72, 70, 67, 1130, 72, 1129, 1112, 40, 1095, 67, 72, 40, 110, 1058, 40,
40, 1021, 959, 897, 812, 72, 40, 110, 727, 40, 56, 56, 56, 56, 56, 56, 56,
56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 61, 61, 616,
61, 61, 61, 61, 61, 61, 84, 68, 114, 505, 391, 68, 276, 186, 115, 68, 61,
61, 61, 73, 101, 68, 61, 73, 61, 116, 84, 117, 101, 73, 61, 68, 61, 84,
68, 114, 61, 61, 68, 73, 102, 115, 68, 102, 184, 90, 73, 101, 68,
61, 73, 61, 116, 84, 117, 101, 73, 61, 68, 61, 88, 85, 118, 61, 61, 60,
73, 102, 59, 52, 102, 76, 61, 62, 62, 76, 62, 62, 62, 62, 62, 62, 76,
82, 51, 47, 78, 82, 76, 118, 78, 82, 62, 62, 62, 76, 78, 120, 76, 62,
45, 20, 76, 121, 19, 122, 78, 82, 83, 76, 82, 83, 83, 78, 82, 76, 11,
78, 82, 62, 107, 7, 76, 78, 120, 123, 62, 107, 83, 4, 121, 81, 122, 78,
82, 83, 3, 0, 83, 83, 81, 124, 81, 105, 105, 81, 62, 107, 62,
63, 125, 81, 123, 63, 107, 83, 63, 105, 81, 0, 109, 109, 109, 63, 109, 0,
63, 81, 124, 81, 105, 105, 81, 63, 0, 126, 63, 125, 81, 127, 63, 111, 0,
63, 105, 129, 111, 109, 109, 109, 63, 109, 112, 63, 112, 113, 113, 112, 0, 130,
63, 64, 126, 112, 0, 64, 127, 132, 111, 64, 112, 133, 129, 111, 119, 64, 119,
135, 64, 112, 119, 112, 113, 113, 112, 64, 130, 119, 64, 136, 112, 119, 64, 0,
132, 0, 64, 112, 133, 137, 0, 119, 64, 119, 135, 64, 0, 119, 128,
134, 138, 128, 64, 65, 119, 139, 136, 139, 119, 134, 65, 141, 65, 142, 134, 134,
137, 65, 140, 143, 140, 144, 65, 65, 0, 128, 134, 138, 128, 145, 65, 140, 139,
146, 139, 0, 134, 65, 141, 65, 142, 134, 134, 147, 65, 140, 143, 140, 144, 65,
65, 66, 148, 150, 151, 66, 145, 152, 140, 66, 146, 153, 66, 154, 156, 66, 157,
154, 66, 158, 147, 66, 0, 0, 160, 66, 0, 0, 66, 148, 150, 151, 66, 0,
152, 0, 66, 155, 153, 66, 154, 156, 66, 157, 154, 66, 158, 161, 66,
159, 155, 160, 66, 69, 69, 155, 162, 163, 159, 164, 69, 69, 69, 166, 155, 167,
159, 69, 165, 168, 171, 169, 170, 69, 161, 170, 159, 155, 0, 165, 69, 69, 155,
162, 163, 159, 164, 69, 69, 69, 166, 169, 167, 159, 69, 165, 168, 171, 169, 170,
69, 74, 170, 172, 173, 74, 165, 174, 175, 176, 173, 177, 279, 194, 0, 74, 0,
0, 169, 281, 174, 74, 74, 195, 195, 74, 0, 0, 74, 0, 172, 173, 74, 194,
174, 175, 176, 173, 177, 279, 194, 196, 74, 202, 195, 0, 281, 174, 74,
74, 195, 195, 74, 75, 75, 227, 196, 197, 0, 282, 194, 196, 75, 202, 197, 199,
75, 0, 196, 75, 202, 195, 197, 75, 0, 227, 0, 197, 199, 0, 75, 75, 227,
196, 197, 199, 282, 0, 196, 75, 202, 197, 199, 75, 198, 284, 75, 198, 198, 197,
75, 79, 227, 79, 197, 199, 79, 200, 286, 200, 0, 79, 199, 79, 79, 0, 0,
0, 198, 0, 0, 198, 284, 79, 198, 198, 0, 206, 79, 200, 79, 0, 0, 79,
200, 286, 200, 206, 79, 0, 79, 79, 201, 201, 201, 198, 203, 206, 0,
287, 79, 80, 207, 203, 206, 80, 200, 201, 80, 80, 203, 288, 201, 289, 206, 80,
203, 207, 80, 201, 201, 201, 207, 203, 206, 80, 287, 0, 80, 207, 203, 0, 80,
0, 201, 80, 80, 203, 288, 201, 289, 0, 80, 203, 207, 80, 0, 0, 0, 207,
0, 0, 80, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 92, 92, 92, 92,
92, 92, 92, 92, 92, 92, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187, 188, 188, 188, 188, 188,
188, 188, 188, 188, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 204,
209, 210, 211, 204, 291, 212, 292, 293, 294, 0, 0, 295, 211, 209, 209, 213, 213,
210, 0, 212, 209, 210, 211, 204, 0, 212, 204, 209, 210, 211, 204, 291, 212, 292,
293, 294, 213, 233, 295, 211, 209, 209, 213, 213, 210, 229, 212, 209, 210, 211, 204,
205, 212, 214, 0, 214, 229, 233, 205, 205, 205, 216, 205, 213, 233, 229, 0, 0,
216, 296, 297, 205, 229, 0, 0, 214, 0, 0, 205, 298, 214, 216, 214,
229, 233, 205, 205, 205, 216, 205, 0, 299, 229, 217, 219, 216, 296, 297, 205, 208,
217, 208, 214, 208, 208, 218, 298, 219, 216, 220, 208, 0, 0, 217, 219, 218, 0,
208, 299, 220, 217, 219, 0, 208, 0, 218, 208, 217, 208, 220, 208, 208, 218, 300,
219, 237, 220, 208, 221, 222, 217, 219, 218, 245, 208, 221, 220, 0, 237, 222, 208,
215, 218, 215, 0, 237, 220, 215, 221, 222, 300, 223, 237, 245, 215, 221, 222, 0,
215, 0, 245, 223, 221, 215, 225, 237, 222, 240, 215, 224, 215, 223, 237,
225, 215, 221, 222, 226, 223, 0, 245, 215, 240, 224, 225, 215, 224, 240, 223, 224,
215, 225, 231, 226, 240, 228, 224, 226, 223, 228, 225, 231, 0, 232, 226, 234, 234,
232, 301, 240, 224, 225, 231, 224, 240, 228, 224, 0, 302, 231, 226, 235, 228, 232,
226, 234, 228, 235, 231, 235, 232, 0, 234, 234, 232, 301, 236, 0, 236, 231, 236,
235, 228, 230, 230, 302, 238, 0, 235, 236, 232, 0, 234, 230, 235, 238, 235, 241,
230, 230, 236, 304, 0, 236, 230, 236, 238, 236, 235, 239, 230, 230, 241,
238, 242, 305, 236, 241, 239, 243, 230, 242, 238, 243, 241, 230, 230, 236, 304, 239,
0, 230, 0, 238, 242, 0, 239, 244, 244, 241, 247, 242, 305, 243, 241, 239, 243,
0, 242, 248, 243, 246, 246, 306, 250, 247, 239, 244, 250, 249, 247, 242, 248, 249,
244, 244, 0, 247, 0, 248, 243, 307, 246, 252, 250, 252, 248, 0, 246, 246, 306,
250, 247, 249, 244, 250, 249, 247, 0, 248, 249, 251, 308, 252, 254, 251, 248, 254,
307, 246, 252, 250, 252, 256, 251, 253, 0, 0, 0, 251, 249, 309, 253,
256, 254, 251, 0, 311, 251, 308, 252, 254, 251, 256, 254, 253, 255, 0, 255, 0,
256, 251, 253, 257, 258, 255, 251, 257, 309, 253, 256, 254, 251, 255, 311, 259, 312,
258, 255, 259, 256, 0, 253, 255, 258, 255, 260, 257, 261, 260, 257, 258, 255, 313,
257, 314, 261, 262, 315, 259, 255, 264, 259, 312, 258, 255, 259, 261, 261, 260, 263,
258, 264, 260, 257, 261, 260, 262, 263, 0, 313, 264, 314, 261, 262, 315, 259, 265,
264, 0, 263, 265, 267, 267, 261, 261, 260, 263, 0, 264, 316, 0, 266,
271, 262, 263, 266, 265, 264, 266, 0, 265, 268, 267, 265, 270, 268, 263, 265, 267,
267, 273, 266, 271, 269, 273, 272, 316, 270, 266, 271, 269, 268, 266, 265, 270, 266,
269, 265, 268, 267, 272, 270, 268, 269, 273, 272, 0, 273, 266, 271, 269, 273, 272,
0, 270, 0, 0, 269, 268, 317, 318, 270, 319, 269, 320, 321, 290, 272, 290, 303,
269, 273, 272, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 290, 303, 322, 317,
318, 323, 319, 324, 320, 321, 290, 325, 290, 303, 326, 327, 328, 329, 330,
331, 332, 333, 335, 334, 336, 338, 339, 290, 303, 322, 340, 341, 323, 334, 324, 342,
343, 344, 325, 345, 346, 326, 327, 328, 329, 330, 331, 332, 333, 335, 334, 336, 338,
339, 347, 349, 350, 340, 341, 351, 334, 352, 342, 343, 344, 353, 345, 346, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 367, 347, 349, 350, 368, 369, 351,
370, 352, 371, 372, 373, 353, 374, 375, 354, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 367, 377, 380, 378, 368, 369, 379, 370, 379, 371, 372, 373,
378, 374, 375, 381, 382, 383, 384, 385, 386, 387, 388, 389, 0, 387, 0, 0, 377,
380, 378, 0, 0, 379, 0, 379, 0, 0, 0, 378, 0, 0, 381, 382, 383, 384,
385, 386, 387, 388, 389, 393, 387, 392, 392, 392, 392, 392, 392, 392, 392, 392, 392,
394, 395, 396, 397, 398, 400, 0, 0, 393, 399, 397, 0, 0, 399, 0, 393, 506,
0, 507, 0, 394, 395, 396, 397, 398, 400, 409, 394, 395, 396, 397, 398, 400, 399,
401, 393, 399, 397, 402, 403, 399, 409, 402, 506, 401, 507, 409, 394, 395,
396, 397, 398, 400, 409, 401, 404, 0, 403, 402, 403, 399, 401, 404, 406, 0, 402,
403, 0, 409, 402, 405, 401, 405, 409, 508, 404, 406, 0, 407, 0, 408, 401, 404,
406, 403, 402, 403, 405, 408, 404, 406, 410, 405, 0, 407, 0, 413, 405, 407, 405,
408, 508, 404, 406, 411, 407, 412, 408, 411, 0, 406, 410, 0, 0, 405, 408, 413,
415, 410, 405, 412, 407, 414, 413, 415, 407, 412, 408, 411, 0, 416, 411, 0, 412,
416, 411, 414, 415, 410, 418, 420, 417, 414, 413, 415, 417, 0, 412, 0,
414, 416, 415, 0, 412, 418, 411, 419, 416, 419, 418, 420, 416, 424, 414, 415, 417,
418, 420, 417, 414, 509, 422, 417, 421, 422, 425, 427, 416, 419, 423, 426, 418, 424,
419, 426, 419, 418, 420, 421, 424, 423, 0, 417, 421, 422, 425, 427, 509, 422, 423,
421, 422, 425, 427, 426, 419, 423, 426, 428, 424, 428, 426, 430, 429, 432, 421, 431,
423, 433, 430, 421, 422, 425, 427, 510, 0, 423, 429, 432, 431, 428, 426, 430, 429,
432, 428, 431, 428, 433, 430, 429, 432, 435, 431, 434, 433, 430, 0, 434,
438, 435, 510, 438, 0, 429, 432, 431, 428, 436, 430, 429, 432, 435, 431, 439, 433,
436, 437, 434, 435, 440, 434, 438, 440, 437, 434, 438, 435, 436, 438, 439, 0, 441,
442, 439, 436, 441, 437, 446, 435, 440, 439, 0, 436, 437, 434, 447, 440, 442, 438,
440, 437, 441, 442, 0, 436, 443, 439, 446, 441, 442, 439, 444, 441, 437, 446, 447,
440, 444, 443, 448, 445, 450, 447, 449, 442, 443, 0, 0, 441, 442, 445, 444, 443,
449, 446, 0, 452, 450, 444, 448, 445, 450, 447, 449, 444, 443, 448, 445,
450, 0, 449, 454, 443, 451, 453, 455, 452, 445, 444, 455, 449, 457, 451, 452, 450,
457, 448, 445, 450, 453, 449, 454, 0, 451, 453, 455, 456, 456, 454, 460, 451, 453,
455, 452, 0, 457, 455, 0, 457, 451, 463, 458, 457, 458, 461, 460, 453, 456, 454,
460, 451, 453, 455, 456, 456, 459, 460, 459, 464, 461, 463, 458, 457, 462, 461, 464,
0, 463, 458, 467, 458, 461, 460, 0, 456, 459, 460, 468, 464, 462, 465, 466, 459,
462, 459, 464, 461, 463, 458, 467, 462, 461, 464, 465, 469, 466, 467, 468,
469, 0, 465, 466, 459, 470, 468, 464, 462, 465, 466, 472, 462, 0, 470, 511, 0,
471, 467, 472, 469, 0, 465, 469, 466, 470, 468, 469, 471, 465, 466, 472, 470, 473,
475, 474, 477, 471, 472, 474, 473, 470, 511, 477, 471, 476, 472, 469, 476, 475, 0,
478, 470, 473, 475, 471, 477, 480, 472, 474, 473, 475, 474, 477, 471, 476, 474, 473,
481, 479, 477, 478, 476, 482, 512, 476, 475, 480, 478, 479, 473, 475, 484, 477, 480,
514, 474, 483, 481, 479, 485, 482, 476, 482, 483, 481, 479, 484, 478, 0,
482, 512, 484, 517, 480, 485, 479, 483, 488, 484, 485, 487, 514, 490, 483, 481, 479,
485, 482, 486, 482, 483, 487, 488, 484, 491, 486, 489, 488, 484, 517, 487, 485, 490,
483, 488, 489, 485, 487, 486, 490, 0, 492, 0, 0, 491, 486, 489, 493, 487, 488,
492, 491, 486, 489, 488, 0, 493, 487, 0, 490, 494, 492, 489, 0, 501, 486, 495,
493, 492, 498, 494, 491, 494, 489, 493, 0, 495, 492, 496, 501, 494, 497, 496, 493,
501, 498, 495, 494, 492, 498, 497, 501, 0, 495, 493, 0, 498, 494, 499,
494, 499, 497, 496, 495, 500, 496, 501, 494, 497, 496, 502, 501, 498, 495, 0, 503,
498, 497, 503, 502, 499, 504, 500, 502, 500, 499, 518, 499, 497, 496, 502, 500, 519,
520, 504, 503, 522, 502, 523, 524, 526, 504, 503, 527, 528, 503, 502, 499, 504, 500,
502, 500, 529, 518, 530, 531, 532, 502, 533, 519, 520, 504, 503, 522, 534, 523, 524,
526, 504, 537, 527, 528, 538, 539, 540, 541, 542, 543, 545, 529, 546, 530, 531, 532,
549, 533, 550, 552, 554, 555, 556, 534, 557, 558, 559, 560, 537, 562, 566,
538, 539, 540, 541, 542, 543, 545, 560, 546, 568, 570, 572, 549, 573, 550, 552, 554,
555, 556, 575, 557, 558, 559, 560, 576, 562, 566, 571, 571, 577, 578, 579, 581, 582,
560, 584, 568, 570, 572, 585, 573, 586, 587, 588, 589, 590, 575, 592, 593, 594, 595,
576, 596, 599, 571, 571, 577, 578, 579, 581, 582, 600, 584, 602, 603, 604, 585, 605,
586, 587, 588, 589, 590, 606, 592, 593, 594, 595, 607, 596, 599, 608, 609, 611, 613,
615, 617, 0, 600, 0, 602, 603, 604, 0, 605, 619, 620, 0, 622, 617,
606, 618, 730, 0, 621, 607, 617, 622, 608, 609, 611, 613, 615, 617, 618, 619, 620,
621, 622, 623, 624, 618, 619, 620, 621, 622, 617, 0, 618, 730, 626, 621, 625, 617,
622, 627, 625, 732, 734, 623, 624, 618, 619, 620, 621, 622, 623, 624, 618, 628, 626,
621, 629, 628, 630, 627, 625, 626, 630, 625, 629, 0, 627, 625, 732, 734, 623, 624,
632, 735, 736, 631, 629, 628, 630, 737, 628, 626, 0, 629, 628, 630, 627, 625, 631,
630, 0, 629, 632, 633, 635, 631, 634, 636, 0, 632, 735, 736, 631, 629,
628, 630, 737, 0, 633, 635, 634, 637, 639, 633, 635, 631, 634, 636, 637, 632, 633,
635, 631, 634, 636, 641, 638, 640, 639, 641, 738, 637, 639, 0, 638, 633, 635, 634,
637, 639, 633, 635, 640, 634, 636, 637, 638, 640, 739, 641, 642, 646, 641, 638, 640,
639, 641, 738, 637, 639, 643, 638, 643, 642, 644, 645, 647, 0, 644, 640, 642, 646,
645, 638, 640, 739, 641, 642, 646, 0, 0, 0, 643, 648, 644, 645, 647, 643, 650,
643, 642, 644, 645, 647, 648, 644, 649, 642, 646, 645, 654, 652, 651, 648,
650, 652, 655, 649, 650, 643, 648, 644, 645, 647, 653, 650, 649, 651, 653, 0, 654,
648, 651, 649, 0, 652, 655, 654, 652, 651, 648, 650, 652, 655, 649, 650, 656, 658,
653, 0, 659, 653, 657, 649, 651, 653, 657, 654, 661, 651, 660, 656, 652, 655, 660,
0, 656, 658, 0, 661, 659, 740, 662, 656, 658, 653, 657, 659, 661, 657, 663, 664,
666, 657, 660, 661, 0, 660, 656, 663, 665, 660, 662, 656, 658, 668, 661, 659, 740,
662, 663, 664, 666, 657, 665, 661, 0, 663, 664, 666, 665, 660, 667, 669,
668, 668, 663, 665, 672, 662, 0, 0, 668, 670, 742, 667, 669, 663, 664, 666, 0,
665, 667, 669, 743, 674, 670, 665, 672, 667, 669, 668, 668, 670, 671, 672, 671, 673,
675, 676, 670, 742, 667, 669, 673, 674, 0, 671, 678, 667, 669, 743, 674, 670, 671,
672, 680, 673, 675, 676, 670, 671, 677, 671, 673, 675, 676, 681, 678, 0, 685, 673,
674, 679, 671, 678, 680, 677, 0, 0, 679, 671, 677, 680, 673, 675, 676, 681, 684,
677, 685, 682, 0, 679, 681, 678, 683, 685, 0, 683, 679, 684, 687, 680,
677, 682, 682, 679, 684, 677, 0, 682, 744, 0, 681, 684, 683, 685, 682, 686, 679,
686, 687, 683, 688, 691, 683, 689, 684, 687, 745, 0, 682, 682, 746, 684, 748, 688,
682, 744, 689, 686, 690, 683, 688, 691, 686, 689, 686, 687, 690, 688, 691, 0, 689,
692, 693, 745, 694, 692, 693, 746, 690, 748, 688, 0, 0, 689, 686, 690, 0, 688,
691, 695, 689, 696, 697, 690, 694, 692, 693, 695, 692, 693, 699, 694, 692, 693, 696,
690, 0, 697, 699, 695, 698, 696, 697, 698, 0, 0, 695, 0, 696, 697,
699, 694, 692, 693, 695, 0, 701, 699, 701, 702, 749, 696, 700, 698, 697, 699, 695,
698, 696, 697, 698, 700, 704, 703, 706, 0, 708, 699, 701, 702, 703, 750, 700, 701,
705, 701, 702, 749, 705, 700, 698, 0, 704, 703, 706, 0, 708, 709, 700, 704, 703,
706, 707, 708, 705, 701, 702, 703, 750, 700, 712, 705, 707, 710, 711, 705, 713, 709,
713, 704, 703, 706, 707, 708, 709, 0, 714, 710, 711, 707, 712, 705, 715, 710, 711,
714, 751, 712, 713, 707, 710, 711, 752, 713, 709, 713, 714, 716, 715, 707,
719, 716, 715, 714, 710, 711, 718, 712, 718, 715, 710, 711, 714, 751, 720, 713, 717,
720, 721, 752, 719, 716, 723, 714, 716, 715, 718, 719, 716, 715, 722, 717, 724, 718,
720, 718, 717, 753, 721, 754, 725, 720, 723, 717, 720, 721, 722, 719, 716, 723, 722,
755, 724, 718, 726, 756, 757, 722, 717, 724, 725, 720, 760, 717, 753, 721, 754, 725,
726, 723, 761, 763, 766, 722, 726, 769, 770, 722, 755, 724, 772, 726, 756, 757, 777,
771, 778, 725, 771, 760, 779, 780, 781, 784, 785, 726, 786, 761, 763, 766,
787, 726, 769, 770, 788, 790, 791, 772, 792, 793, 794, 777, 771, 778, 795, 771, 796,
779, 780, 781, 784, 785, 797, 786, 798, 799, 800, 787, 801, 803, 804, 788, 790, 791,
805, 792, 793, 794, 807, 808, 809, 795, 813, 796, 814, 0, 0, 0, 0, 797, 816,
798, 799, 800, 815, 801, 803, 804, 817, 818, 819, 805, 813, 898, 814, 807, 808, 809,
825, 813, 816, 814, 820, 820, 815, 815, 0, 816, 817, 818, 819, 815, 821, 822, 821,
817, 818, 819, 825, 813, 898, 814, 822, 820, 826, 825, 0, 816, 823, 820,
820, 815, 815, 822, 821, 817, 818, 819, 0, 821, 822, 821, 824, 823, 826, 825, 0,
0, 823, 822, 820, 826, 824, 827, 828, 823, 0, 827, 830, 829, 822, 821, 824, 829,
828, 830, 0, 831, 832, 824, 823, 826, 0, 827, 828, 823, 900, 901, 830, 824, 827,
828, 836, 829, 827, 830, 829, 831, 832, 824, 829, 828, 830, 833, 831, 832, 834, 833,
835, 837, 827, 828, 836, 900, 901, 830, 0, 835, 840, 836, 829, 834, 838, 833, 831,
832, 834, 902, 835, 837, 833, 839, 840, 834, 833, 835, 837, 838, 840, 836,
903, 843, 838, 841, 835, 840, 839, 841, 834, 838, 833, 839, 844, 834, 902, 835, 837,
847, 839, 840, 842, 843, 842, 841, 838, 840, 845, 903, 843, 838, 841, 849, 844, 839,
841, 850, 846, 847, 839, 844, 905, 845, 842, 846, 847, 0, 845, 842, 843, 842, 841,
849, 848, 845, 848, 850, 846, 852, 849, 844, 851, 0, 850, 846, 847, 853, 0, 905,
845, 842, 846, 854, 848, 845, 855, 851, 856, 852, 849, 848, 851, 848, 850, 846, 852,
853, 854, 851, 857, 858, 856, 854, 853, 856, 855, 857, 856, 0, 854, 848,
0, 855, 851, 856, 852, 859, 860, 851, 857, 858, 861, 862, 853, 854, 863, 857, 858,
856, 854, 907, 856, 855, 857, 856, 865, 859, 860, 865, 863, 867, 861, 862, 859, 860,
863, 857, 858, 861, 862, 864, 0, 863, 868, 864, 865, 866, 907, 869, 908, 867, 0,
865, 859, 860, 865, 863, 867, 861, 862, 872, 866, 863, 868, 864, 870, 866, 864, 869,
871, 868, 864, 865, 866, 874, 869, 908, 867, 870, 873, 872, 909, 871, 873, 910, 870,
0, 872, 866, 871, 868, 864, 870, 866, 874, 869, 871, 0, 875, 873, 876,
874, 875, 878, 876, 870, 873, 872, 909, 871, 873, 910, 870, 877, 877, 879, 871, 0,
878, 879, 912, 874, 875, 878, 876, 875, 873, 876, 887, 875, 878, 876, 880, 880, 877,
879, 0, 0, 882, 881, 877, 877, 879, 881, 883, 878, 879, 912, 887, 875, 878, 876,
882, 880, 884, 887, 888, 883, 882, 880, 880, 877, 879, 881, 883, 882, 881, 914, 885,
884, 881, 883, 885, 886, 884, 887, 888, 886, 890, 882, 880, 884, 891, 888, 883, 882,
889, 889, 918, 920, 881, 883, 885, 0, 914, 885, 884, 886, 890, 885, 886,
884, 891, 888, 886, 890, 892, 889, 893, 891, 895, 896, 893, 889, 889, 918, 920, 894,
921, 885, 892, 894, 927, 928, 886, 890, 892, 929, 931, 891, 895, 896, 893, 892, 889,
893, 933, 895, 896, 893, 934, 894, 936, 937, 894, 921, 938, 892, 894, 927, 928, 940,
941, 892, 929, 931, 942, 895, 896, 893, 943, 945, 947, 933, 949, 950, 951, 934, 894,
936, 937, 952, 957, 938, 958, 960, 961, 962, 940, 941, 963, 0, 0, 942, 0, 1025,
962, 943, 945, 947, 964, 949, 950, 951, 965, 960, 961, 962, 952, 957, 963,
958, 960, 961, 962, 964, 966, 963, 965, 967, 964, 968, 1025, 962, 965, 0, 967, 964,
0, 0, 969, 965, 960, 961, 962, 1028, 966, 963, 969, 967, 972, 968, 964, 966, 973,
965, 967, 964, 968, 971, 969, 965, 970, 967, 970, 972, 971, 969, 975, 0, 972, 0,
1028, 966, 973, 969, 967, 972, 968, 971, 974, 973, 977, 974, 970, 978, 971, 969, 975,
970, 1029, 970, 972, 971, 976, 975, 976, 972, 979, 980, 981, 973, 977, 974, 982, 978,
971, 974, 984, 977, 974, 970, 978, 982, 985, 975, 976, 1029, 979, 980, 981,
976, 983, 976, 982, 979, 980, 981, 984, 977, 974, 982, 978, 986, 985, 984, 987, 983,
988, 989, 982, 985, 983, 976, 0, 979, 980, 981, 990, 983, 991, 982, 989, 986, 991,
984, 987, 0, 988, 989, 986, 985, 992, 987, 983, 988, 989, 994, 990, 983, 993, 995,
996, 997, 991, 990, 996, 991, 995, 989, 986, 991, 992, 987, 993, 988, 989, 994, 999,
992, 993, 995, 998, 997, 994, 990, 996, 993, 995, 996, 997, 991, 1000, 996, 1001, 995,
0, 998, 999, 992, 1032, 993, 998, 1006, 994, 999, 1004, 993, 995, 998, 997,
0, 1000, 996, 1001, 1002, 1003, 1002, 1003, 1000, 1004, 1001, 0, 1006, 998, 999, 1004, 1032,
1008, 998, 1006, 1007, 1005, 1004, 1010, 0, 1033, 1002, 1003, 1000, 1007, 1001, 1002, 1003, 1002,
1003, 1005, 1004, 1008, 1009, 1006, 1007, 1005, 1004, 1010, 1008, 1009, 1015, 1007, 1005, 1038, 1010,
1011, 1033, 1002, 1003, 1011, 1007, 1012, 1009, 1014, 1016, 1012, 1005, 1017, 1008, 1009, 1015, 1007,
1005, 1013, 1010, 1013, 1009, 1015, 1014, 1011, 1038, 1018, 1011, 1014, 1016, 1012, 1011, 1017, 1012,
1009, 1014, 1016, 1012, 0, 1017, 1013, 1019, 1015, 1039, 1042, 1013, 1018, 1013, 1043,
1046, 1014, 1011, 1047, 1018, 1019, 1014, 1016, 1012, 1020, 1017, 1050, 1019, 1052, 1053, 1054, 1020,
1055, 1013, 1019, 0, 1039, 1042, 0, 1018, 1059, 1043, 1046, 1060, 1020, 1047, 1061, 1019, 1062,
1063, 0, 1020, 1064, 1050, 1019, 1052, 1053, 1054, 1020, 1055, 1059, 1065, 1067, 1060, 1068, 1069,
1061, 1059, 1062, 1063, 1060, 1020, 1064, 1061, 1066, 1062, 1063, 1071, 1066, 1064, 1096, 1065, 1067,
1072, 1068, 1069, 1073, 1059, 1065, 1067, 1060, 1068, 1069, 1061, 1074, 1062, 1063, 1071, 1066, 1064,
1070, 1066, 1077, 1072, 1071, 1066, 1073, 1096, 1065, 1067, 1072, 1068, 1069, 1073, 1074,
1070, 1075, 1078, 1075, 1076, 1070, 1074, 1077, 1098, 1071, 1066, 1076, 1070, 0, 1077, 1072, 1080,
1081, 1073, 1082, 1079, 0, 1078, 1075, 1076, 1085, 1074, 1070, 1075, 1078, 1075, 1076, 1070, 1079,
1077, 1098, 1080, 1081, 1076, 1082, 1079, 1083, 1084, 1080, 1081, 1085, 1082, 1079, 1084, 1078, 1075,
1076, 1085, 1086, 1101, 0, 1083, 1088, 1089, 1087, 1079, 1083, 1084, 1080, 1081, 0, 1082, 1079,
1083, 1084, 1104, 1089, 1085, 1086, 1087, 1084, 1091, 1088, 1089, 1087, 1086, 1101, 1090, 1083, 1088,
1089, 1087, 1092, 1083, 1084, 1090, 1091, 1093, 1094, 1108, 1109, 1091, 1104, 1089, 1110,
1086, 1087, 1090, 1091, 1088, 1089, 1087, 1092, 1114, 1090, 1115, 1113, 1093, 1094, 1092, 0, 1116,
1090, 1091, 1093, 1094, 1108, 1109, 1091, 1113, 1115, 1110, 1117, 1114, 1090, 1115, 1113, 0, 1118,
1092, 1114, 1116, 1115, 1113, 1093, 1094, 1119, 1120, 1116, 1122, 1123, 1121, 1117, 1118, 0, 1124,
1113, 1115, 1118, 1117, 1114, 1125, 1115, 1113, 1121, 1118, 1119, 1120, 1116, 1122, 1123, 1121, 1126,
1119, 1120, 1124, 1122, 1123, 1121, 1117, 1118, 1125, 1124, 1126, 1128, 1118, 1127, 1131, 1125, 1133,
1127, 1121, 1126, 1119, 1120, 1136, 1122, 1123, 1121, 1126, 1138, 1139, 1124, 1140, 1128,
0, 1127, 1142, 1125, 1143, 1126, 1128, 1141, 1127, 1131, 1149, 1133, 1127, 1146, 1126, 1151, 1139,
1136, 1140, 1152, 1138, 1141, 1142, 1139, 1143, 1140, 1128, 1141, 1127, 1142, 0, 1143, 1144, 1153,
1141, 1156, 1159, 1149, 1160, 1152, 1138, 1154, 1144, 1139, 1162, 1140, 1152, 1138, 1141, 1142, 1154,
1143, 1144, 1153, 1141, 1146, 1164, 1151, 1160, 1144, 1153, 1154, 1156, 1159, 1166, 1160, 1152, 1138,
1154, 1144, 1168, 1162, 1170, 1172, 1174, 1176, 1178, 1154, 1180, 1144, 1153, 0, 1146, 1164, 1151,
1160, 0, 0, 1154, 0, 0, 1166, 0, 0, 0, 0, 0, 1168, 0, 1170,
1172, 1174, 1176, 1178, 0, 1180, 1192, 1192, 1192, 1192, 1192, 1193, 0, 0, 1193, 1193, 1195,
1195, 1195, 0, 1195, 1196, 0, 1196, 1196, 1196, 1197, 0, 1197, 1197, 1197, 1198, 0, 1198,
1198, 1198, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191,
1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191};
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
#line 1 "flex_lexer.l"
/**
* lexer
*
*
*/
/***************************
** Section 1: Definitions
***************************/
#line 12 "flex_lexer.l"
#include <stdio.h>
#include <climits>
#include <sstream>
#include "../sql/Expr.h"
#include "bison_parser.h"
#define TOKEN(name) \
{ return SQL_##name; }
static thread_local std::stringstream strbuf;
#line 2133 "flex_lexer.cpp"
/***************************
** Section 2: Rules
***************************/
/* Define the output files */
/* Make reentrant */
/* performance tweeks */
/* other flags */
/* %option nodefault */
/***************************
** Section 3: Rules
***************************/
#line 2147 "flex_lexer.cpp"
#define INITIAL 0
#define singlequotedstring 1
#define COMMENT 2
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void*
#endif
/* Holds the entire state of the reentrant scanner. */
struct yyguts_t {
/* User-defined. Not touched by flex. */
YY_EXTRA_TYPE yyextra_r;
/* The rest are the same as the globals declared in the non-reentrant scanner. */
FILE *yyin_r, *yyout_r;
size_t yy_buffer_stack_top; /**< index of top of stack. */
size_t yy_buffer_stack_max; /**< capacity of stack. */
YY_BUFFER_STATE* yy_buffer_stack; /**< Stack as an array. */
char yy_hold_char;
int yy_n_chars;
int yyleng_r;
char* yy_c_buf_p;
int yy_init;
int yy_start;
int yy_did_buffer_switch_on_eof;
int yy_start_stack_ptr;
int yy_start_stack_depth;
int* yy_start_stack;
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
int yylineno_r;
int yy_flex_debug_r;
char* yytext_r;
int yy_more_flag;
int yy_more_len;
YYSTYPE* yylval_r;
YYLTYPE* yylloc_r;
}; /* end struct yyguts_t */
static int yy_init_globals(yyscan_t yyscanner);
/* This must go here because YYSTYPE and YYLTYPE are included
* from bison output in section 1.*/
#define yylval yyg->yylval_r
#define yylloc yyg->yylloc_r
int yylex_init(yyscan_t* scanner);
int yylex_init_extra(YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy(yyscan_t yyscanner);
int yyget_debug(yyscan_t yyscanner);
void yyset_debug(int debug_flag, yyscan_t yyscanner);
YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner);
void yyset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner);
FILE* yyget_in(yyscan_t yyscanner);
void yyset_in(FILE* _in_str, yyscan_t yyscanner);
FILE* yyget_out(yyscan_t yyscanner);
void yyset_out(FILE* _out_str, yyscan_t yyscanner);
int yyget_leng(yyscan_t yyscanner);
char* yyget_text(yyscan_t yyscanner);
int yyget_lineno(yyscan_t yyscanner);
void yyset_lineno(int _line_number, yyscan_t yyscanner);
int yyget_column(yyscan_t yyscanner);
void yyset_column(int _column_no, yyscan_t yyscanner);
YYSTYPE* yyget_lval(yyscan_t yyscanner);
void yyset_lval(YYSTYPE* yylval_param, yyscan_t yyscanner);
YYLTYPE* yyget_lloc(yyscan_t yyscanner);
void yyset_lloc(YYLTYPE* yylloc_param, yyscan_t yyscanner);
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap(yyscan_t yyscanner);
#else
extern int yywrap(yyscan_t yyscanner);
#endif
#endif
#ifndef YY_NO_UNPUT
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy(char*, const char*, int, yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen(const char*, yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput(yyscan_t yyscanner);
#else
static int input(yyscan_t yyscanner);
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO \
do { \
if (fwrite(yytext, (size_t)yyleng, 1, yyout)) { \
} \
} while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf, result, max_size) \
if (YY_CURRENT_BUFFER_LVALUE->yy_is_interactive) { \
int c = '*'; \
int n; \
for (n = 0; n < max_size && (c = getc(yyin)) != EOF && c != '\n'; ++n) buf[n] = (char)c; \
if (c == '\n') buf[n++] = (char)c; \
if (c == EOF && ferror(yyin)) YY_FATAL_ERROR("input in flex scanner failed"); \
result = n; \
} else { \
errno = 0; \
while ((result = (int)fread(buf, 1, (yy_size_t)max_size, yyin)) == 0 && ferror(yyin)) { \
if (errno != EINTR) { \
YY_FATAL_ERROR("input in flex scanner failed"); \
break; \
} \
errno = 0; \
clearerr(yyin); \
} \
}
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error(msg, yyscanner)
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex(YYSTYPE* yylval_param, YYLTYPE* yylloc_param, yyscan_t yyscanner);
#define YY_DECL int yylex(YYSTYPE* yylval_param, YYLTYPE* yylloc_param, yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/ break;
#endif
#define YY_RULE_SETUP YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL {
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
yylloc = yylloc_param;
if (!yyg->yy_init) {
yyg->yy_init = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if (!yyg->yy_start) yyg->yy_start = 1; /* first start state */
if (!yyin) yyin = stdin;
if (!yyout) yyout = stdout;
if (!YY_CURRENT_BUFFER) {
yyensure_buffer_stack(yyscanner);
YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner);
}
yy_load_buffer_state(yyscanner);
}
{
#line 57 "flex_lexer.l"
#line 2434 "flex_lexer.cpp"
while (/*CONSTCOND*/ 1) /* loops until end-of-file is reached */
{
yy_cp = yyg->yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yyg->yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yyg->yy_start;
yy_match:
do {
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if (yy_accept[yy_current_state]) {
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) {
yy_current_state = (int)yy_def[yy_current_state];
if (yy_current_state >= 1192) yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
} while (yy_current_state != 1191);
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch (yy_act) { /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yyg->yy_hold_char;
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 59 "flex_lexer.l"
BEGIN(COMMENT);
YY_BREAK
case 2:
YY_RULE_SETUP
#line 60 "flex_lexer.l"
/* skipping comment content until a end of line is read */;
YY_BREAK
case 3:
/* rule 3 can match eol */
YY_RULE_SETUP
#line 61 "flex_lexer.l"
BEGIN(INITIAL);
YY_BREAK
case 4:
/* rule 4 can match eol */
YY_RULE_SETUP
#line 63 "flex_lexer.l"
/* skip whitespace */;
YY_BREAK
case 5:
YY_RULE_SETUP
#line 65 "flex_lexer.l"
TOKEN(DEALLOCATE)
YY_BREAK
case 6:
YY_RULE_SETUP
#line 66 "flex_lexer.l"
TOKEN(PARAMETERS)
YY_BREAK
case 7:
YY_RULE_SETUP
#line 67 "flex_lexer.l"
TOKEN(INTERSECT)
YY_BREAK
case 8:
YY_RULE_SETUP
#line 68 "flex_lexer.l"
TOKEN(TEMPORARY)
YY_BREAK
case 9:
YY_RULE_SETUP
#line 69 "flex_lexer.l"
TOKEN(TIMESTAMP)
YY_BREAK
case 10:
YY_RULE_SETUP
#line 70 "flex_lexer.l"
TOKEN(DESCRIBE)
YY_BREAK
case 11:
YY_RULE_SETUP
#line 71 "flex_lexer.l"
TOKEN(DISTINCT)
YY_BREAK
case 12:
YY_RULE_SETUP
#line 72 "flex_lexer.l"
TOKEN(NVARCHAR)
YY_BREAK
case 13:
YY_RULE_SETUP
#line 73 "flex_lexer.l"
TOKEN(RESTRICT)
YY_BREAK
case 14:
YY_RULE_SETUP
#line 74 "flex_lexer.l"
TOKEN(TRUNCATE)
YY_BREAK
case 15:
YY_RULE_SETUP
#line 75 "flex_lexer.l"
TOKEN(ANALYZE)
YY_BREAK
case 16:
YY_RULE_SETUP
#line 76 "flex_lexer.l"
TOKEN(BETWEEN)
YY_BREAK
case 17:
YY_RULE_SETUP
#line 77 "flex_lexer.l"
TOKEN(CASCADE)
YY_BREAK
case 18:
YY_RULE_SETUP
#line 78 "flex_lexer.l"
TOKEN(COLUMNS)
YY_BREAK
case 19:
YY_RULE_SETUP
#line 79 "flex_lexer.l"
TOKEN(CONTROL)
YY_BREAK
case 20:
YY_RULE_SETUP
#line 80 "flex_lexer.l"
TOKEN(DEFAULT)
YY_BREAK
case 21:
YY_RULE_SETUP
#line 81 "flex_lexer.l"
TOKEN(EXECUTE)
YY_BREAK
case 22:
YY_RULE_SETUP
#line 82 "flex_lexer.l"
TOKEN(EXPLAIN)
YY_BREAK
case 23:
YY_RULE_SETUP
#line 83 "flex_lexer.l"
TOKEN(INTEGER)
YY_BREAK
case 24:
YY_RULE_SETUP
#line 84 "flex_lexer.l"
TOKEN(NATURAL)
YY_BREAK
case 25:
YY_RULE_SETUP
#line 85 "flex_lexer.l"
TOKEN(PREPARE)
YY_BREAK
case 26:
YY_RULE_SETUP
#line 86 "flex_lexer.l"
TOKEN(PRIMARY)
YY_BREAK
case 27:
YY_RULE_SETUP
#line 87 "flex_lexer.l"
TOKEN(SCHEMAS)
YY_BREAK
case 28:
YY_RULE_SETUP
#line 88 "flex_lexer.l"
TOKEN(SPATIAL)
YY_BREAK
case 29:
YY_RULE_SETUP
#line 89 "flex_lexer.l"
TOKEN(VARCHAR)
YY_BREAK
case 30:
YY_RULE_SETUP
#line 90 "flex_lexer.l"
TOKEN(TIME)
YY_BREAK
case 31:
YY_RULE_SETUP
#line 91 "flex_lexer.l"
TOKEN(DECIMAL)
YY_BREAK
case 32:
YY_RULE_SETUP
#line 92 "flex_lexer.l"
TOKEN(REAL)
YY_BREAK
case 33:
YY_RULE_SETUP
#line 93 "flex_lexer.l"
TOKEN(SMALLINT)
YY_BREAK
case 34:
YY_RULE_SETUP
#line 94 "flex_lexer.l"
TOKEN(VIRTUAL)
YY_BREAK
case 35:
YY_RULE_SETUP
#line 95 "flex_lexer.l"
TOKEN(BEFORE)
YY_BREAK
case 36:
YY_RULE_SETUP
#line 96 "flex_lexer.l"
TOKEN(COLUMN)
YY_BREAK
case 37:
YY_RULE_SETUP
#line 97 "flex_lexer.l"
TOKEN(CREATE)
YY_BREAK
case 38:
YY_RULE_SETUP
#line 98 "flex_lexer.l"
TOKEN(DELETE)
YY_BREAK
case 39:
YY_RULE_SETUP
#line 99 "flex_lexer.l"
TOKEN(DIRECT)
YY_BREAK
case 40:
YY_RULE_SETUP
#line 100 "flex_lexer.l"
TOKEN(DOUBLE)
YY_BREAK
case 41:
YY_RULE_SETUP
#line 101 "flex_lexer.l"
TOKEN(ESCAPE)
YY_BREAK
case 42:
YY_RULE_SETUP
#line 102 "flex_lexer.l"
TOKEN(EXCEPT)
YY_BREAK
case 43:
YY_RULE_SETUP
#line 103 "flex_lexer.l"
TOKEN(EXISTS)
YY_BREAK
case 44:
YY_RULE_SETUP
#line 104 "flex_lexer.l"
TOKEN(EXTRACT)
YY_BREAK
case 45:
YY_RULE_SETUP
#line 105 "flex_lexer.l"
TOKEN(CAST)
YY_BREAK
case 46:
YY_RULE_SETUP
#line 106 "flex_lexer.l"
TOKEN(FORMAT)
YY_BREAK
case 47:
YY_RULE_SETUP
#line 107 "flex_lexer.l"
TOKEN(GLOBAL)
YY_BREAK
case 48:
YY_RULE_SETUP
#line 108 "flex_lexer.l"
TOKEN(HAVING)
YY_BREAK
case 49:
YY_RULE_SETUP
#line 109 "flex_lexer.l"
TOKEN(IMPORT)
YY_BREAK
case 50:
YY_RULE_SETUP
#line 110 "flex_lexer.l"
TOKEN(INSERT)
YY_BREAK
case 51:
YY_RULE_SETUP
#line 111 "flex_lexer.l"
TOKEN(ISNULL)
YY_BREAK
case 52:
YY_RULE_SETUP
#line 112 "flex_lexer.l"
TOKEN(OFFSET)
YY_BREAK
case 53:
YY_RULE_SETUP
#line 113 "flex_lexer.l"
TOKEN(RENAME)
YY_BREAK
case 54:
YY_RULE_SETUP
#line 114 "flex_lexer.l"
TOKEN(SCHEMA)
YY_BREAK
case 55:
YY_RULE_SETUP
#line 115 "flex_lexer.l"
TOKEN(SELECT)
YY_BREAK
case 56:
YY_RULE_SETUP
#line 116 "flex_lexer.l"
TOKEN(SORTED)
YY_BREAK
case 57:
YY_RULE_SETUP
#line 117 "flex_lexer.l"
TOKEN(TABLES)
YY_BREAK
case 58:
YY_RULE_SETUP
#line 118 "flex_lexer.l"
TOKEN(UNIQUE)
YY_BREAK
case 59:
YY_RULE_SETUP
#line 119 "flex_lexer.l"
TOKEN(UNLOAD)
YY_BREAK
case 60:
YY_RULE_SETUP
#line 120 "flex_lexer.l"
TOKEN(UPDATE)
YY_BREAK
case 61:
YY_RULE_SETUP
#line 121 "flex_lexer.l"
TOKEN(VALUES)
YY_BREAK
case 62:
YY_RULE_SETUP
#line 122 "flex_lexer.l"
TOKEN(AFTER)
YY_BREAK
case 63:
YY_RULE_SETUP
#line 123 "flex_lexer.l"
TOKEN(ALTER)
YY_BREAK
case 64:
YY_RULE_SETUP
#line 124 "flex_lexer.l"
TOKEN(ARRAY)
YY_BREAK
case 65:
YY_RULE_SETUP
#line 125 "flex_lexer.l"
TOKEN(CROSS)
YY_BREAK
case 66:
YY_RULE_SETUP
#line 126 "flex_lexer.l"
TOKEN(DELTA)
YY_BREAK
case 67:
YY_RULE_SETUP
#line 127 "flex_lexer.l"
TOKEN(FLOAT)
YY_BREAK
case 68:
YY_RULE_SETUP
#line 128 "flex_lexer.l"
TOKEN(GROUP)
YY_BREAK
case 69:
YY_RULE_SETUP
#line 129 "flex_lexer.l"
TOKEN(INDEX)
YY_BREAK
case 70:
YY_RULE_SETUP
#line 130 "flex_lexer.l"
TOKEN(INNER)
YY_BREAK
case 71:
YY_RULE_SETUP
#line 131 "flex_lexer.l"
TOKEN(LIMIT)
YY_BREAK
case 72:
YY_RULE_SETUP
#line 132 "flex_lexer.l"
TOKEN(LOCAL)
YY_BREAK
case 73:
YY_RULE_SETUP
#line 133 "flex_lexer.l"
TOKEN(MERGE)
YY_BREAK
case 74:
YY_RULE_SETUP
#line 134 "flex_lexer.l"
TOKEN(MINUS)
YY_BREAK
case 75:
YY_RULE_SETUP
#line 135 "flex_lexer.l"
TOKEN(ORDER)
YY_BREAK
case 76:
YY_RULE_SETUP
#line 136 "flex_lexer.l"
TOKEN(OUTER)
YY_BREAK
case 77:
YY_RULE_SETUP
#line 137 "flex_lexer.l"
TOKEN(RIGHT)
YY_BREAK
case 78:
YY_RULE_SETUP
#line 138 "flex_lexer.l"
TOKEN(TABLE)
YY_BREAK
case 79:
YY_RULE_SETUP
#line 139 "flex_lexer.l"
TOKEN(UNION)
YY_BREAK
case 80:
YY_RULE_SETUP
#line 140 "flex_lexer.l"
TOKEN(USING)
YY_BREAK
case 81:
YY_RULE_SETUP
#line 141 "flex_lexer.l"
TOKEN(WHERE)
YY_BREAK
case 82:
YY_RULE_SETUP
#line 142 "flex_lexer.l"
TOKEN(CALL)
YY_BREAK
case 83:
YY_RULE_SETUP
#line 143 "flex_lexer.l"
TOKEN(CASE)
YY_BREAK
case 84:
YY_RULE_SETUP
#line 144 "flex_lexer.l"
TOKEN(CHAR)
YY_BREAK
case 85:
YY_RULE_SETUP
#line 145 "flex_lexer.l"
TOKEN(COPY)
YY_BREAK
case 86:
YY_RULE_SETUP
#line 146 "flex_lexer.l"
TOKEN(DATE)
YY_BREAK
case 87:
YY_RULE_SETUP
#line 147 "flex_lexer.l"
TOKEN(DATETIME)
YY_BREAK
case 88:
YY_RULE_SETUP
#line 148 "flex_lexer.l"
TOKEN(DESC)
YY_BREAK
case 89:
YY_RULE_SETUP
#line 149 "flex_lexer.l"
TOKEN(DROP)
YY_BREAK
case 90:
YY_RULE_SETUP
#line 150 "flex_lexer.l"
TOKEN(ELSE)
YY_BREAK
case 91:
YY_RULE_SETUP
#line 151 "flex_lexer.l"
TOKEN(FILE)
YY_BREAK
case 92:
YY_RULE_SETUP
#line 152 "flex_lexer.l"
TOKEN(FROM)
YY_BREAK
case 93:
YY_RULE_SETUP
#line 153 "flex_lexer.l"
TOKEN(FULL)
YY_BREAK
case 94:
YY_RULE_SETUP
#line 154 "flex_lexer.l"
TOKEN(HASH)
YY_BREAK
case 95:
YY_RULE_SETUP
#line 155 "flex_lexer.l"
TOKEN(HINT)
YY_BREAK
case 96:
YY_RULE_SETUP
#line 156 "flex_lexer.l"
TOKEN(INTO)
YY_BREAK
case 97:
YY_RULE_SETUP
#line 157 "flex_lexer.l"
TOKEN(JOIN)
YY_BREAK
case 98:
YY_RULE_SETUP
#line 158 "flex_lexer.l"
TOKEN(LEFT)
YY_BREAK
case 99:
YY_RULE_SETUP
#line 159 "flex_lexer.l"
TOKEN(LIKE)
YY_BREAK
case 100:
YY_RULE_SETUP
#line 160 "flex_lexer.l"
TOKEN(ILIKE)
YY_BREAK
case 101:
YY_RULE_SETUP
#line 161 "flex_lexer.l"
TOKEN(LOAD)
YY_BREAK
case 102:
YY_RULE_SETUP
#line 162 "flex_lexer.l"
TOKEN(LONG)
YY_BREAK
case 103:
YY_RULE_SETUP
#line 163 "flex_lexer.l"
TOKEN(NULL)
YY_BREAK
case 104:
YY_RULE_SETUP
#line 164 "flex_lexer.l"
TOKEN(PLAN)
YY_BREAK
case 105:
YY_RULE_SETUP
#line 165 "flex_lexer.l"
TOKEN(SHOW)
YY_BREAK
case 106:
YY_RULE_SETUP
#line 166 "flex_lexer.l"
TOKEN(TEXT)
YY_BREAK
case 107:
YY_RULE_SETUP
#line 167 "flex_lexer.l"
TOKEN(THEN)
YY_BREAK
case 108:
YY_RULE_SETUP
#line 168 "flex_lexer.l"
TOKEN(VIEW)
YY_BREAK
case 109:
YY_RULE_SETUP
#line 169 "flex_lexer.l"
TOKEN(WHEN)
YY_BREAK
case 110:
YY_RULE_SETUP
#line 170 "flex_lexer.l"
TOKEN(WITH)
YY_BREAK
case 111:
YY_RULE_SETUP
#line 171 "flex_lexer.l"
TOKEN(ADD)
YY_BREAK
case 112:
YY_RULE_SETUP
#line 172 "flex_lexer.l"
TOKEN(ALL)
YY_BREAK
case 113:
YY_RULE_SETUP
#line 173 "flex_lexer.l"
TOKEN(AND)
YY_BREAK
case 114:
YY_RULE_SETUP
#line 174 "flex_lexer.l"
TOKEN(ASC)
YY_BREAK
case 115:
YY_RULE_SETUP
#line 175 "flex_lexer.l"
TOKEN(END)
YY_BREAK
case 116:
YY_RULE_SETUP
#line 176 "flex_lexer.l"
TOKEN(FOR)
YY_BREAK
case 117:
YY_RULE_SETUP
#line 177 "flex_lexer.l"
TOKEN(INT)
YY_BREAK
case 118:
YY_RULE_SETUP
#line 178 "flex_lexer.l"
TOKEN(KEY)
YY_BREAK
case 119:
YY_RULE_SETUP
#line 179 "flex_lexer.l"
TOKEN(NOT)
YY_BREAK
case 120:
YY_RULE_SETUP
#line 180 "flex_lexer.l"
TOKEN(OFF)
YY_BREAK
case 121:
YY_RULE_SETUP
#line 181 "flex_lexer.l"
TOKEN(SET)
YY_BREAK
case 122:
YY_RULE_SETUP
#line 182 "flex_lexer.l"
TOKEN(TOP)
YY_BREAK
case 123:
YY_RULE_SETUP
#line 183 "flex_lexer.l"
TOKEN(AS)
YY_BREAK
case 124:
YY_RULE_SETUP
#line 184 "flex_lexer.l"
TOKEN(BY)
YY_BREAK
case 125:
YY_RULE_SETUP
#line 185 "flex_lexer.l"
TOKEN(IF)
YY_BREAK
case 126:
YY_RULE_SETUP
#line 186 "flex_lexer.l"
TOKEN(IN)
YY_BREAK
case 127:
YY_RULE_SETUP
#line 187 "flex_lexer.l"
TOKEN(IS)
YY_BREAK
case 128:
YY_RULE_SETUP
#line 188 "flex_lexer.l"
TOKEN(OF)
YY_BREAK
case 129:
YY_RULE_SETUP
#line 189 "flex_lexer.l"
TOKEN(ON)
YY_BREAK
case 130:
YY_RULE_SETUP
#line 190 "flex_lexer.l"
TOKEN(OR)
YY_BREAK
case 131:
YY_RULE_SETUP
#line 191 "flex_lexer.l"
TOKEN(TO)
YY_BREAK
case 132:
YY_RULE_SETUP
#line 192 "flex_lexer.l"
TOKEN(SECOND)
YY_BREAK
case 133:
YY_RULE_SETUP
#line 193 "flex_lexer.l"
TOKEN(MINUTE)
YY_BREAK
case 134:
YY_RULE_SETUP
#line 194 "flex_lexer.l"
TOKEN(HOUR)
YY_BREAK
case 135:
YY_RULE_SETUP
#line 195 "flex_lexer.l"
TOKEN(DAY)
YY_BREAK
case 136:
YY_RULE_SETUP
#line 196 "flex_lexer.l"
TOKEN(MONTH)
YY_BREAK
case 137:
YY_RULE_SETUP
#line 197 "flex_lexer.l"
TOKEN(YEAR)
YY_BREAK
case 138:
YY_RULE_SETUP
#line 198 "flex_lexer.l"
TOKEN(SECONDS)
YY_BREAK
case 139:
YY_RULE_SETUP
#line 199 "flex_lexer.l"
TOKEN(MINUTES)
YY_BREAK
case 140:
YY_RULE_SETUP
#line 200 "flex_lexer.l"
TOKEN(HOURS)
YY_BREAK
case 141:
YY_RULE_SETUP
#line 201 "flex_lexer.l"
TOKEN(DAYS)
YY_BREAK
case 142:
YY_RULE_SETUP
#line 202 "flex_lexer.l"
TOKEN(MONTHS)
YY_BREAK
case 143:
YY_RULE_SETUP
#line 203 "flex_lexer.l"
TOKEN(YEARS)
YY_BREAK
case 144:
YY_RULE_SETUP
#line 204 "flex_lexer.l"
TOKEN(TRUE)
YY_BREAK
case 145:
YY_RULE_SETUP
#line 205 "flex_lexer.l"
TOKEN(FALSE)
YY_BREAK
case 146:
YY_RULE_SETUP
#line 206 "flex_lexer.l"
TOKEN(TRANSACTION)
YY_BREAK
case 147:
YY_RULE_SETUP
#line 207 "flex_lexer.l"
TOKEN(BEGIN)
YY_BREAK
case 148:
YY_RULE_SETUP
#line 208 "flex_lexer.l"
TOKEN(ROLLBACK)
YY_BREAK
case 149:
YY_RULE_SETUP
#line 209 "flex_lexer.l"
TOKEN(COMMIT)
YY_BREAK
case 150:
YY_RULE_SETUP
#line 210 "flex_lexer.l"
TOKEN(INTERVAL)
YY_BREAK
case 151:
YY_RULE_SETUP
#line 212 "flex_lexer.l"
TOKEN(CHARACTER_VARYING)
YY_BREAK
/* Allow =/== see https://sqlite.org/lang_expr.html#collateop */
case 152:
YY_RULE_SETUP
#line 215 "flex_lexer.l"
TOKEN(EQUALS)
YY_BREAK
case 153:
YY_RULE_SETUP
#line 216 "flex_lexer.l"
TOKEN(NOTEQUALS)
YY_BREAK
case 154:
YY_RULE_SETUP
#line 217 "flex_lexer.l"
TOKEN(NOTEQUALS)
YY_BREAK
case 155:
YY_RULE_SETUP
#line 218 "flex_lexer.l"
TOKEN(LESSEQ)
YY_BREAK
case 156:
YY_RULE_SETUP
#line 219 "flex_lexer.l"
TOKEN(GREATEREQ)
YY_BREAK
case 157:
YY_RULE_SETUP
#line 220 "flex_lexer.l"
TOKEN(CONCAT)
YY_BREAK
case 158:
YY_RULE_SETUP
#line 222 "flex_lexer.l"
{
return yytext[0];
}
YY_BREAK
case 159:
#line 225 "flex_lexer.l"
case 160:
YY_RULE_SETUP
#line 225 "flex_lexer.l"
{
yylval->fval = atof(yytext);
return SQL_FLOATVAL;
}
YY_BREAK
/*
* Regularly, negative literals are treated as <unary minus> <positive literal>. This does not work for LLONG_MIN, as it has no
* positive equivalent. We thus match for LLONG_MIN specifically. This is not an issue for floats, where
* numeric_limits<double>::lowest() == -numeric_limits<double>::max();
*/
case 161:
YY_RULE_SETUP
#line 235 "flex_lexer.l"
{
yylval->ival = LLONG_MIN;
return SQL_INTVAL;
}
YY_BREAK
case 162:
YY_RULE_SETUP
#line 240 "flex_lexer.l"
{
errno = 0;
yylval->ival = strtoll(yytext, nullptr, 0);
if (errno) {
return fprintf(stderr, "[SQL-Lexer-Error] Integer cannot be parsed - is it out of range?");
return 0;
}
return SQL_INTVAL;
}
YY_BREAK
case 163:
YY_RULE_SETUP
#line 250 "flex_lexer.l"
{
// Crop the leading and trailing quote char
yylval->sval = hsql::substr(yytext, 1, strlen(yytext) - 1);
return SQL_IDENTIFIER;
}
YY_BREAK
case 164:
YY_RULE_SETUP
#line 256 "flex_lexer.l"
{
yylval->sval = strdup(yytext);
return SQL_IDENTIFIER;
}
YY_BREAK
case 165:
YY_RULE_SETUP
#line 261 "flex_lexer.l"
{
BEGIN singlequotedstring;
strbuf.clear();
strbuf.str("");
} // Clear strbuf manually, see #170
YY_BREAK
case 166:
YY_RULE_SETUP
#line 262 "flex_lexer.l"
{
strbuf << '\'';
}
YY_BREAK
case 167:
/* rule 167 can match eol */
YY_RULE_SETUP
#line 263 "flex_lexer.l"
{
strbuf << yytext;
}
YY_BREAK
case 168:
YY_RULE_SETUP
#line 264 "flex_lexer.l"
{
BEGIN 0;
yylval->sval = strdup(strbuf.str().c_str());
return SQL_STRING;
}
YY_BREAK
case YY_STATE_EOF(singlequotedstring):
#line 265 "flex_lexer.l"
{
fprintf(stderr, "[SQL-Lexer-Error] Unterminated string\n");
return 0;
}
YY_BREAK
case 169:
YY_RULE_SETUP
#line 267 "flex_lexer.l"
{
fprintf(stderr, "[SQL-Lexer-Error] Unknown Character: %c\n", yytext[0]);
return 0;
}
YY_BREAK
case 170:
YY_RULE_SETUP
#line 269 "flex_lexer.l"
ECHO;
YY_BREAK
#line 3368 "flex_lexer.cpp"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(COMMENT):
yyterminate();
case YY_END_OF_BUFFER: {
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int)(yy_cp - yyg->yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yyg->yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW) {
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if (yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]) { /* This was really a NUL. */
yy_state_type yy_next_state;
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state(yyscanner);
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans(yy_current_state, yyscanner);
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
if (yy_next_state) {
/* Consume the NUL. */
yy_cp = ++yyg->yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else {
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
}
}
else
switch (yy_get_next_buffer(yyscanner)) {
case EOB_ACT_END_OF_FILE: {
yyg->yy_did_buffer_switch_on_eof = 0;
if (yywrap(yyscanner)) {
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else {
if (!yyg->yy_did_buffer_switch_on_eof) YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state(yyscanner);
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
yy_current_state = yy_get_previous_state(yyscanner);
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR("fatal flex scanner internal error--no action found");
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
char* dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char* source = yyg->yytext_ptr;
int number_to_move, i;
int ret_val;
if (yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1])
YY_FATAL_ERROR("fatal flex scanner internal error--end of buffer missed");
if (YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0) { /* Don't try to fill the buffer, so this is an EOF. */
if (yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1) {
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else {
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int)(yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for (i = 0; i < number_to_move; ++i) *(dest++) = *(source++);
if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING)
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
else {
int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while (num_to_read <= 0) { /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset = (int)(yyg->yy_c_buf_p - b->yy_ch_buf);
if (b->yy_is_our_buffer) {
int new_size = b->yy_buf_size * 2;
if (new_size <= 0)
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char*)
/* Include room in for 2 EOB chars. */
yyrealloc((void*)b->yy_ch_buf, (yy_size_t)(b->yy_buf_size + 2), yyscanner);
} else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = NULL;
if (!b->yy_ch_buf) YY_FATAL_ERROR("fatal error - scanner input buffer overflow");
yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
}
if (num_to_read > YY_READ_BUF_SIZE) num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT((&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
if (yyg->yy_n_chars == 0) {
if (number_to_move == YY_MORE_ADJ) {
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin, yyscanner);
}
else {
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf =
(char*)yyrealloc((void*)YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t)new_size, yyscanner);
if (!YY_CURRENT_BUFFER_LVALUE->yy_ch_buf) YY_FATAL_ERROR("out of dynamic memory in yy_get_next_buffer()");
/* "- 2" to take care of EOB's */
YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int)(new_size - 2);
}
yyg->yy_n_chars += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state(yyscan_t yyscanner) {
yy_state_type yy_current_state;
char* yy_cp;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yy_current_state = yyg->yy_start;
for (yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp) {
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if (yy_accept[yy_current_state]) {
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) {
yy_current_state = (int)yy_def[yy_current_state];
if (yy_current_state >= 1192) yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans(yy_state_type yy_current_state, yyscan_t yyscanner) {
int yy_is_jam;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
char* yy_cp = yyg->yy_c_buf_p;
YY_CHAR yy_c = 1;
if (yy_accept[yy_current_state]) {
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) {
yy_current_state = (int)yy_def[yy_current_state];
if (yy_current_state >= 1192) yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 1191);
(void)yyg;
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput(yyscan_t yyscanner)
#else
static int input(yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if (*yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR) {
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if (yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]) /* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else { /* need more input */
int offset = (int)(yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch (yy_get_next_buffer(yyscanner)) {
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin, yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE: {
if (yywrap(yyscanner)) return 0;
if (!yyg->yy_did_buffer_switch_on_eof) YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char*)yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart(FILE* input_file, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER) {
yyensure_buffer_stack(yyscanner);
YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner);
}
yy_init_buffer(YY_CURRENT_BUFFER, input_file, yyscanner);
yy_load_buffer_state(yyscanner);
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
void yy_switch_to_buffer(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack(yyscanner);
if (YY_CURRENT_BUFFER == new_buffer) return;
if (YY_CURRENT_BUFFER) {
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state(yyscanner);
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
static void yy_load_buffer_state(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
yyg->yy_hold_char = *yyg->yy_c_buf_p;
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer(FILE* file, int size, yyscan_t yyscanner) {
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE)yyalloc(sizeof(struct yy_buffer_state), yyscanner);
if (!b) YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()");
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char*)yyalloc((yy_size_t)(b->yy_buf_size + 2), yyscanner);
if (!b->yy_ch_buf) YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()");
b->yy_is_our_buffer = 1;
yy_init_buffer(b, file, yyscanner);
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
void yy_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!b) return;
if (b == YY_CURRENT_BUFFER) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE)0;
if (b->yy_is_our_buffer) yyfree((void*)b->yy_ch_buf, yyscanner);
yyfree((void*)b, yyscanner);
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer(YY_BUFFER_STATE b, FILE* file, yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yy_flush_buffer(b, yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER) {
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
void yy_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!b) return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if (b == YY_CURRENT_BUFFER) yy_load_buffer_state(yyscanner);
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
void yypush_buffer_state(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL) return;
yyensure_buffer_stack(yyscanner);
/* This block is copied from yy_switch_to_buffer. */
if (YY_CURRENT_BUFFER) {
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state(yyscanner);
yyg->yy_did_buffer_switch_on_eof = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
void yypop_buffer_state(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER) return;
yy_delete_buffer(YY_CURRENT_BUFFER, yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state(yyscanner);
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack(yyscan_t yyscanner) {
yy_size_t num_to_alloc;
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc(num_to_alloc * sizeof(struct yy_buffer_state*), yyscanner);
if (!yyg->yy_buffer_stack) YY_FATAL_ERROR("out of dynamic memory in yyensure_buffer_stack()");
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1) {
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc(
yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*), yyscanner);
if (!yyg->yy_buffer_stack) YY_FATAL_ERROR("out of dynamic memory in yyensure_buffer_stack()");
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer(char* base, yy_size_t size, yyscan_t yyscanner) {
YY_BUFFER_STATE b;
if (size < 2 || base[size - 2] != YY_END_OF_BUFFER_CHAR || base[size - 1] != YY_END_OF_BUFFER_CHAR)
/* They forgot to leave room for the EOB's. */
return NULL;
b = (YY_BUFFER_STATE)yyalloc(sizeof(struct yy_buffer_state), yyscanner);
if (!b) YY_FATAL_ERROR("out of dynamic memory in yy_scan_buffer()");
b->yy_buf_size = (int)(size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b, yyscanner);
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string(const char* yystr, yyscan_t yyscanner) {
return yy_scan_bytes(yystr, (int)strlen(yystr), yyscanner);
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes(const char* yybytes, int _yybytes_len, yyscan_t yyscanner) {
YY_BUFFER_STATE b;
char* buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = (yy_size_t)(_yybytes_len + 2);
buf = (char*)yyalloc(n, yyscanner);
if (!buf) YY_FATAL_ERROR("out of dynamic memory in yy_scan_bytes()");
for (i = 0; i < _yybytes_len; ++i) buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len + 1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf, n, yyscanner);
if (!b) YY_FATAL_ERROR("bad buffer in yy_scan_bytes()");
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yynoreturn yy_fatal_error(const char* msg, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
fprintf(stderr, "%s\n", msg);
exit(YY_EXIT_FAILURE);
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do { \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg); \
yytext[yyleng] = yyg->yy_hold_char; \
yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
yyg->yy_hold_char = *yyg->yy_c_buf_p; \
*yyg->yy_c_buf_p = '\0'; \
yyleng = yyless_macro_arg; \
} while (0)
/* Accessor methods (get/set functions) to struct members. */
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yyextra;
}
/** Get the current line number.
* @param yyscanner The scanner object.
*/
int yyget_lineno(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER) return 0;
return yylineno;
}
/** Get the current column number.
* @param yyscanner The scanner object.
*/
int yyget_column(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER) return 0;
return yycolumn;
}
/** Get the input stream.
* @param yyscanner The scanner object.
*/
FILE* yyget_in(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yyin;
}
/** Get the output stream.
* @param yyscanner The scanner object.
*/
FILE* yyget_out(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yyout;
}
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
int yyget_leng(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yyleng;
}
/** Get the current token.
* @param yyscanner The scanner object.
*/
char* yyget_text(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yytext;
}
/** Set the user-defined data. This data is never touched by the scanner.
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
void yyset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined;
}
/** Set the current line number.
* @param _line_number line number
* @param yyscanner The scanner object.
*/
void yyset_lineno(int _line_number, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (!YY_CURRENT_BUFFER) YY_FATAL_ERROR("yyset_lineno called with no buffer");
yylineno = _line_number;
}
/** Set the current column.
* @param _column_no column number
* @param yyscanner The scanner object.
*/
void yyset_column(int _column_no, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (!YY_CURRENT_BUFFER) YY_FATAL_ERROR("yyset_column called with no buffer");
yycolumn = _column_no;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
* @see yy_switch_to_buffer
*/
void yyset_in(FILE* _in_str, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str;
}
void yyset_out(FILE* _out_str, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str;
}
int yyget_debug(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
void yyset_debug(int _bdebug, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug;
}
/* Accessor methods for yylval and yylloc */
YYSTYPE* yyget_lval(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
void yyset_lval(YYSTYPE* yylval_param, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
}
YYLTYPE* yyget_lloc(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
return yylloc;
}
void yyset_lloc(YYLTYPE* yylloc_param, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
yylloc = yylloc_param;
}
/* User-visible API */
/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
int yylex_init(yyscan_t* ptr_yy_globals) {
if (ptr_yy_globals == NULL) {
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t)yyalloc(sizeof(struct yyguts_t), NULL);
if (*ptr_yy_globals == NULL) {
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t));
return yy_init_globals(*ptr_yy_globals);
}
/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
* The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
int yylex_init_extra(YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals) {
struct yyguts_t dummy_yyguts;
yyset_extra(yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL) {
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t)yyalloc(sizeof(struct yyguts_t), &dummy_yyguts);
if (*ptr_yy_globals == NULL) {
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t));
yyset_extra(yy_user_defined, *ptr_yy_globals);
return yy_init_globals(*ptr_yy_globals);
}
static int yy_init_globals(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
yyg->yy_buffer_stack_top = 0;
yyg->yy_buffer_stack_max = 0;
yyg->yy_c_buf_p = NULL;
yyg->yy_init = 0;
yyg->yy_start = 0;
yyg->yy_start_stack_ptr = 0;
yyg->yy_start_stack_depth = 0;
yyg->yy_start_stack = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = NULL;
yyout = NULL;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while (YY_CURRENT_BUFFER) {
yy_delete_buffer(YY_CURRENT_BUFFER, yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
yyfree(yyg->yy_buffer_stack, yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
yyfree(yyg->yy_start_stack, yyscanner);
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals(yyscanner);
/* Destroy the main struct (reentrant only). */
yyfree(yyscanner, yyscanner);
yyscanner = NULL;
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy(char* s1, const char* s2, int n, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
int i;
for (i = 0; i < n; ++i) s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen(const char* s, yyscan_t yyscanner) {
int n;
for (n = 0; s[n]; ++n)
;
return n;
}
#endif
void* yyalloc(yy_size_t size, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
void* yyrealloc(void* ptr, yy_size_t size, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return realloc(ptr, size);
}
void yyfree(void* ptr, yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
free((char*)ptr); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 269 "flex_lexer.l"
/***************************
** Section 3: User code
***************************/
int yyerror(const char* msg) {
fprintf(stderr, "[SQL-Lexer-Error] %s\n", msg);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.