text
string | size
int64 | token_count
int64 |
|---|---|---|
//
// PostTreatUtils.cpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "PostTreatUtils.hpp"
#include <iostream>
using namespace MNN;
static bool _OpNeedContent(OpType type, int index) {
switch (type) {
case OpType_Shape:
case OpType_PriorBox:
return false;
case OpType_Interp:
case OpType_Crop:
case OpType_Reshape:
case OpType_Resize:
if (1 == index) {
return false;
}
break;
default:
break;
}
return true;
}
PostTreatUtils::PostTreatUtils(std::unique_ptr<MNN::NetT>& net) : mNet(std::move(net)) {
}
const std::set<MNN::OpType> PostTreatUtils::NC4HW4_OPs = {
MNN::OpType_Convolution,
MNN::OpType_ConvolutionDepthwise,
MNN::OpType_Pooling,
MNN::OpType_ROIPooling,
MNN::OpType_Resize,
MNN::OpType_LSTM,
MNN::OpType_SpatialProduct,
MNN::OpType_Deconvolution,
MNN::OpType_DeconvolutionDepthwise,
MNN::OpType_Proposal,
MNN::OpType_PriorBox,
MNN::OpType_DetectionOutput,
MNN::OpType_Eltwise,
MNN::OpType_LRN,
MNN::OpType_Interp,
MNN::OpType_Crop,
MNN::OpType_Scale,
MNN::OpType_TfQuantizedConv2D,
MNN::OpType_QuantizedDepthwiseConv2D,
MNN::OpType_BatchToSpaceND,
MNN::OpType_SpaceToBatchND,
MNN::OpType_BatchNorm,
MNN::OpType_Moments,
MNN::OpType_QuantizedAvgPool,
MNN::OpType_QuantizedAdd,
};
const std::set<MNN::OpType> PostTreatUtils::COMPABILITY_OPs = {
MNN::OpType_ReLU, MNN::OpType_ReLU6, MNN::OpType_Concat, MNN::OpType_Slice, MNN::OpType_Permute,
MNN::OpType_Selu, MNN::OpType_ConvertTensor, MNN::OpType_Sigmoid, MNN::OpType_Softmax, MNN::OpType_Cast,
MNN::OpType_Reshape, MNN::OpType_TanH, MNN::OpType_ArgMax,
};
const std::vector<MNN::OpType> PostTreatUtils::DELETE_Ops = {
MNN::OpType_Seq2Out,
MNN::OpType_Dropout,
};
void PostTreatUtils::treatIm2Seq() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_Im2Seq) {
iter++;
continue;
}
auto inputId = op->inputIndexes[0];
auto outputId = op->outputIndexes[0];
auto outputname = mNet->tensorName[outputId];
// New Reshape
MNN::OpT* reshapeT = new MNN::OpT;
reshapeT->name = "____reshape____" + op->name;
auto reshapeP = new MNN::ReshapeT;
reshapeP->dims.push_back(0); // b
reshapeP->dims.push_back(-1); // c
reshapeP->dims.push_back(1); // h
reshapeP->dims.push_back(0); // w
reshapeT->main.type = MNN::OpParameter_Reshape;
reshapeT->type = MNN::OpType_Reshape;
reshapeT->main.value = reshapeP;
// Net Tensor
mNet->tensorName.push_back(reshapeT->name);
int tempId = mNet->tensorName.size() - 1;
reshapeT->inputIndexes.push_back(inputId);
reshapeT->outputIndexes.push_back(tempId);
op->inputIndexes[0] = tempId;
op->type = MNN::OpType_Permute;
auto convP = new MNN::PermuteT;
op->main.type = MNN::OpParameter_Permute;
op->main.value = convP;
convP->dims.push_back(0);
convP->dims.push_back(3);
convP->dims.push_back(2);
convP->dims.push_back(1);
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(reshapeT));
}
}
void PostTreatUtils::deleteUnusefulOp() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
bool shouldDelete = false;
for (int i = 0; i < PostTreatUtils::DELETE_Ops.size(); ++i) {
if (op->type == PostTreatUtils::DELETE_Ops[i]) {
shouldDelete = true;
break;
}
}
if (!shouldDelete) {
iter++;
continue;
}
// Find the next op
auto originInput = op->inputIndexes[0];
auto originOutput = op->outputIndexes[0];
iter = mNet->oplists.erase(iter);
for (auto subIter = mNet->oplists.begin(); subIter != mNet->oplists.end(); subIter++) {
auto& subOp = *subIter;
for (int v = 0; v < subOp->inputIndexes.size(); ++v) {
if (subOp->inputIndexes[v] == originOutput) {
subOp->inputIndexes[v] = originInput;
}
}
}
}
}
bool PostTreatUtils::_merge2Convolution(const MNN::OpT* inplaceOp, MNN::OpT* convolutionOp) {
if (inplaceOp->type == MNN::OpType_ReLU && inplaceOp->main.AsRelu()->slope == 0.0f) {
convolutionOp->main.AsConvolution2D()->common->relu = true;
return true;
}
if (inplaceOp->type == MNN::OpType_ReLU6) {
convolutionOp->main.AsConvolution2D()->common->relu6 = true;
return true;
}
const auto& convCommon = convolutionOp->main.AsConvolution2D()->common;
if (convCommon->relu || convCommon->relu6) {
return false;
}
if (inplaceOp->type == MNN::OpType_BatchNorm || inplaceOp->type == MNN::OpType_Scale) {
std::vector<float> alpha;
std::vector<float> bias;
if (inplaceOp->type == MNN::OpType_BatchNorm) {
auto l = inplaceOp->main.AsBatchNorm();
alpha.resize(l->channels);
bias.resize(l->channels);
const float* slopePtr = l->slopeData.data();
const float* meanDataPtr = l->meanData.data();
const float* varDataPtr = l->varData.data();
const float* biasDataPtr = l->biasData.data();
for (int i = 0; i < l->channels; i++) {
float sqrt_var = sqrt(varDataPtr[i]);
bias[i] = biasDataPtr[i] - slopePtr[i] * meanDataPtr[i] / sqrt_var;
alpha[i] = slopePtr[i] / sqrt_var;
}
}
if (inplaceOp->type == MNN::OpType_Scale) {
bias = inplaceOp->main.AsScale()->biasData;
alpha = inplaceOp->main.AsScale()->scaleData;
}
auto conv2D = convolutionOp->main.AsConvolution2D();
int outputCount = conv2D->common->outputCount;
for (int i = 0; i < outputCount; ++i) {
conv2D->bias[i] = conv2D->bias[i] * alpha[i] + bias[i];
}
if (nullptr != conv2D->quanParameter.get()) {
for (int i = 0; i < outputCount; ++i) {
conv2D->quanParameter->alpha[i] *= alpha[i];
}
} else {
int weightPartSize = conv2D->weight.size() / outputCount;
for (int i = 0; i < outputCount; ++i) {
float a = alpha[i];
for (int j = 0; j < weightPartSize; ++j) {
conv2D->weight[i * weightPartSize + j] *= a;
}
}
}
return true;
}
return false;
}
bool PostTreatUtils::_isSingleInputOutput(const MNN::OpT* op) {
if (op->inputIndexes.size() != 1 || op->outputIndexes.size() != 1) {
return false;
}
return true;
}
void PostTreatUtils::merge2Convolution() {
// Merge Layer
std::vector<MNN::OpT*> readyToDelete;
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
MNN::OpT& currentOp = *(iter->get());
if (currentOp.type != MNN::OpType_Convolution && currentOp.type != MNN::OpType_Deconvolution &&
currentOp.type != MNN::OpType_ConvolutionDepthwise) {
continue;
}
DCHECK(currentOp.outputIndexes.size() == 1) << "Conv output ERROR!";
// merge Batchnorm/Relu/Relu6 to Convolution
std::vector<MNN::OpT*> nextOp = this->_findOpByInputIndex(currentOp.outputIndexes[0]);
while (1) {
if (nextOp.size() != 1) {
break;
}
const int nextOutputIndex = nextOp[0]->outputIndexes[0];
bool succ = _merge2Convolution(nextOp[0], ¤tOp);
if (_isSingleInputOutput(nextOp[0]) && succ) {
// LOG(INFO) << "Merge " << nextOp[0]->name.c_str()<< " into convolution: " << currentOp.name.c_str();
currentOp.outputIndexes[0] = nextOp[0]->outputIndexes[0];
readyToDelete.push_back(nextOp[0]);
nextOp = this->_findOpByInputIndex(nextOutputIndex);
} else {
break;
}
}
}
for (auto op : readyToDelete) {
_removeOpInNet(op);
}
}
void PostTreatUtils::addTensorType() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
if (op->type == MNN::OpType_StridedSlice) {
auto parameter = op->main.AsStridedSliceParam();
auto dataType = parameter->T;
{
int index = op->inputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
{
int index = op->outputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
}
if (op->type == MNN::OpType_Const) {
auto constP = op->main.AsBlob();
{
int index = op->outputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = constP->dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
}
}
}
void PostTreatUtils::removeInplaceOp() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
if (!_isSingleInputOutput(op.get())) {
continue;
}
if (op->inputIndexes[0] != op->outputIndexes[0]) {
continue;
}
auto originIndex = op->inputIndexes[0];
mNet->tensorName.push_back(op->name);
int newIndex = mNet->tensorName.size() - 1;
op->outputIndexes[0] = newIndex;
for (auto subIter = iter + 1; subIter != mNet->oplists.end(); subIter++) {
auto& subOp = *subIter;
for (int i = 0; i < subOp->inputIndexes.size(); ++i) {
if (subOp->inputIndexes[i] == originIndex) {
subOp->inputIndexes[i] = newIndex;
}
}
for (int i = 0; i < subOp->outputIndexes.size(); ++i) {
if (subOp->outputIndexes[i] == originIndex) {
subOp->outputIndexes[i] = newIndex;
}
}
}
mNet->tensorNumber = mNet->tensorName.size();
}
}
void PostTreatUtils::reIndexTensor() {
std::map<int, int> usefulTensorIndexMap;
std::vector<std::string> usefulTensorName;
std::vector<bool> tensorValid(mNet->tensorName.size(), false);
for (auto& op : mNet->oplists) {
for (auto index : op->inputIndexes) {
tensorValid[index] = true;
}
for (auto index : op->outputIndexes) {
tensorValid[index] = true;
}
}
for (int i = 0; i < tensorValid.size(); ++i) {
if (tensorValid[i]) {
usefulTensorIndexMap.insert(std::make_pair(i, usefulTensorName.size()));
usefulTensorName.push_back(mNet->tensorName[i]);
}
}
// Re index
for (auto& op : mNet->oplists) {
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->inputIndexes[i]);
DCHECK(iter != usefulTensorIndexMap.end()) << "ERROR";
op->inputIndexes[i] = iter->second;
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->outputIndexes[i]);
DCHECK(iter != usefulTensorIndexMap.end()) << "ERROR";
op->outputIndexes[i] = iter->second;
}
}
mNet->tensorName = usefulTensorName;
for (auto iter = mNet->extraTensorDescribe.begin(); iter != mNet->extraTensorDescribe.end();) {
auto index = (*iter)->index;
if (usefulTensorIndexMap.find(index) == usefulTensorIndexMap.end()) {
iter = mNet->extraTensorDescribe.erase(iter);
continue;
}
(*iter)->index = usefulTensorIndexMap.find(index)->second;
iter++;
}
}
void PostTreatUtils::addConverterForTensorFlowModel() {
if (mNet->sourceType == MNN::NetSource_CAFFE) {
return;
}
// Don't support inplace
std::vector<MNN::MNN_DATA_FORMAT> tensorType(mNet->tensorName.size());
std::map<std::string, MNN::MNN_DATA_FORMAT> opType;
for (auto& iter : mNet->oplists) {
auto type = MNN::MNN_DATA_FORMAT_NHWC;
if (iter->type == MNN::OpType_ConvertTensor) {
type = iter->main.AsTensorConvertInfo()->dest;
} else if (PostTreatUtils::NC4HW4_OPs.find(iter->type) != PostTreatUtils::NC4HW4_OPs.end()) {
type = MNN::MNN_DATA_FORMAT_NC4HW4;
} else if (PostTreatUtils::COMPABILITY_OPs.find(iter->type) != PostTreatUtils::COMPABILITY_OPs.end()) {
int caffeNumber = 0;
int tensorFlowNamer = 0;
for (auto index : iter->inputIndexes) {
if (tensorType[index] == MNN::MNN_DATA_FORMAT_NC4HW4) {
caffeNumber++;
} else if (tensorType[index] == MNN::MNN_DATA_FORMAT_NHWC) {
tensorFlowNamer++;
}
}
if (caffeNumber > tensorFlowNamer) {
type = MNN::MNN_DATA_FORMAT_NC4HW4;
} else {
type = MNN::MNN_DATA_FORMAT_NHWC;
}
if (iter->type == MNN::OpType_Reshape) {
if (iter->main.AsReshape()->dims.size() != 4) {
type = MNN::MNN_DATA_FORMAT_NHWC;
}
}
}
for (auto index : iter->outputIndexes) {
tensorType[index] = type;
}
opType.insert(std::make_pair(iter->name, type));
}
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
auto currentType = opType.find(op->name)->second;
std::vector<MNN::OpT*> transformOps;
auto currentName = op->name;
const bool useAutoFormat = NC4HW4_OPs.find(op->type) != NC4HW4_OPs.end();
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto inputIndex = op->inputIndexes[i];
MNN::OpT* inputOp = this->_findOpByOutputIndex(inputIndex);
if (inputOp && inputOp->type == MNN::OpType_Input && useAutoFormat) {
auto inputOpParam = inputOp->main.AsInput();
inputOpParam->dformat = MNN::MNN_DATA_FORMAT_NC4HW4;
tensorType[inputIndex] = MNN::MNN_DATA_FORMAT_NC4HW4;
opType[inputOp->name] = MNN::MNN_DATA_FORMAT_NC4HW4;
continue;
}
auto type = tensorType[inputIndex];
if (type == currentType) {
continue;
}
if (!_OpNeedContent(op->type, i)) {
continue;
}
// Insert Transform op
MNN::OpT* transformOp = new MNN::OpT;
transformOps.push_back(transformOp);
MNN::TensorConvertInfoT* tc = new MNN::TensorConvertInfoT;
tc->source = type;
tc->dest = currentType;
transformOp->main.type = MNN::OpParameter_TensorConvertInfo;
transformOp->main.value = tc;
transformOp->name = mNet->tensorName[inputIndex] + "___tr4" + op->name;
// printf("Insert convert for %s, %s 's input %d\n", net->tensorName[inputIndex].c_str(), op->name.c_str(),
// i);
transformOp->inputIndexes.push_back(inputIndex);
transformOp->outputIndexes.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(transformOp->name);
op->inputIndexes[i] = transformOp->outputIndexes[0];
transformOp->type = MNN::OpType_ConvertTensor;
}
for (int i = transformOps.size() - 1; i >= 0; i--) {
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(transformOps[i]));
}
for (; (*iter)->name != currentName; iter++) {
}
iter++;
}
// Reset axis map
const int axisMap[4] = {0, 2, 3, 1};
for (auto& op : mNet->oplists) {
if (opType.find(op->name)->second == MNN::MNN_DATA_FORMAT_NHWC) {
continue;
}
if (MNN::OpType_Input == op->type) {
auto input = op->main.AsInput();
if (4 == input->dims.size()) {
int h = input->dims[1];
int c = input->dims[3];
int w = input->dims[2];
input->dims[1] = c;
input->dims[2] = h;
input->dims[3] = w;
}
}
if (MNN::OpType_Concat == op->type) {
auto axis = op->main.AsAxis();
if (axis->axis >= 0 && axis->axis <= 3) {
axis->axis = axisMap[axis->axis];
}
}
if (MNN::OpType_Permute == op->type) {
auto permuteT = op->main.AsPermute();
for (int i = 0; i < permuteT->dims.size(); ++i) {
DCHECK(permuteT->dims[i] >= 0 && permuteT->dims[i] <= 3) << "Dim Error ==> " << op->name;
permuteT->dims[i] = axisMap[permuteT->dims[i]];
}
}
if (MNN::OpType_Slice == op->type) {
auto slice = op->main.AsSlice();
if (slice->axis >= 0 && slice->axis <= 3) {
slice->axis = axisMap[slice->axis];
}
}
if (MNN::OpType_Reshape == op->type) {
auto reshape = op->main.AsReshape();
auto originDim = reshape->dims;
for (int i = 0; i < reshape->dims.size(); ++i) {
CHECK(i >= 0 && i <= 3) << "Error";
reshape->dims[axisMap[i]] = originDim[i];
}
}
}
std::vector<bool> tensorTypeSet(tensorType.size(), false);
for (auto& iter : mNet->extraTensorDescribe) {
auto index = iter->index;
iter->blob->dataFormat = tensorType[index];
tensorTypeSet[index] = true;
}
for (int i = 0; i < tensorTypeSet.size(); ++i) {
if (tensorTypeSet[i]) {
continue;
}
auto describe = new MNN::TensorDescribeT;
describe->index = i;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataFormat = tensorType[i];
describe->blob->dataType = MNN::DataType_DT_FLOAT;
mNet->extraTensorDescribe.push_back(std::unique_ptr<MNN::TensorDescribeT>(describe));
}
}
MNN::OpT* ensureOpInNet(std::unique_ptr<MNN::NetT>& net, MNN::OpT* op) {
for (auto& _op : net->oplists) {
if (_op.get() == op) {
return op;
}
}
return nullptr;
}
MNN::OpT* PostTreatUtils::_findOpByOutputIndex(int outputIndex) {
for (auto& op : mNet->oplists) {
if (inVector(op->outputIndexes, outputIndex)) {
return op.get();
}
}
return nullptr;
}
std::vector<MNN::OpT*> PostTreatUtils::_findOpByInputIndex(int inputIndex) {
std::vector<MNN::OpT*> ops;
for (auto& op : mNet->oplists) {
if (inVector(op->inputIndexes, inputIndex)) {
ops.push_back(op.get());
}
}
// check whether the next op is in_place op
const int opsSize = ops.size();
if (opsSize > 1) {
auto realNextOp = ops[0];
if (inVector(realNextOp->outputIndexes, inputIndex)) {
ops.clear();
ops.push_back(realNextOp);
}
}
return ops;
}
int PostTreatUtils::_getOpDecestorCount(MNN::OpT* op) {
int decestorCount = 0;
for (auto& otherOp : mNet->oplists) {
if (otherOp.get() != op) {
for (auto inputIndex : otherOp->inputIndexes) {
if (inVector(op->outputIndexes, inputIndex)) {
decestorCount++;
break; // one decestor just count one.
}
}
}
}
return decestorCount;
}
void PostTreatUtils::_removeOpInNet(MNN::OpT* op) {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
if (iter->get() == op) {
// LOG(INFO) << "remove op: " << op->name;
mNet->oplists.erase(iter);
break;
}
}
}
void PostTreatUtils::_removeOnlyOneDecestorOps(MNN::OpT* op) {
std::vector<MNN::OpT*> opsToBeChecked;
opsToBeChecked.push_back(op);
while (!opsToBeChecked.empty()) {
bool hasRemoved = false;
std::vector<MNN::OpT*> addedToBeChecked;
for (auto iter = opsToBeChecked.begin(); iter != opsToBeChecked.end();) {
MNN::OpT* op = *iter;
if (!ensureOpInNet(mNet, op)) {
hasRemoved = true;
iter = opsToBeChecked.erase(iter);
continue;
}
if (this->_getOpDecestorCount(op) == 0) {
for (int inputIndex : op->inputIndexes) {
addedToBeChecked.push_back(this->_findOpByOutputIndex(inputIndex));
}
hasRemoved = true;
this->_removeOpInNet(op);
iter = opsToBeChecked.erase(iter);
continue;
}
iter++;
}
if (!hasRemoved)
break;
opsToBeChecked.insert(opsToBeChecked.end(), addedToBeChecked.begin(), addedToBeChecked.end());
}
}
void PostTreatUtils::removeDeconvolutionShapeInput() {
std::set<MNN::OpT*> shapeOps;
for (auto& op : mNet->oplists) {
if (op->type == MNN::OpType_Deconvolution) {
if (op->inputIndexes.size() == 1) {
continue;
}
int firstInputIndex = op->inputIndexes[0];
op->inputIndexes.erase(op->inputIndexes.begin());
MNN::OpT* shapeOp = this->_findOpByOutputIndex(firstInputIndex);
if (shapeOp) {
shapeOps.insert(shapeOp);
}
}
}
for (auto& op : shapeOps) {
this->_removeOnlyOneDecestorOps(op);
}
}
void PostTreatUtils::turnInnerProduct2Convolution() {
std::vector<MNN::OpT*> readyToDelete;
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_InnerProduct) {
iter++;
continue;
}
// ONNX Gemm will be mapped to InnerProduct, check whether is Flatten before Gemm
// then delete Flatten(mapped to Reshape, and this Reshape will reshape tensor to be
// two dimensions, such as [M,K], which is the input of Gemm)
auto inputId = op->inputIndexes[0];
auto beforeGemm = _findOpByOutputIndex(inputId);
auto refBeforeGemm = _findOpByInputIndex(beforeGemm->outputIndexes[0]);
if (beforeGemm->type == MNN::OpType_Reshape && _isSingleInputOutput(beforeGemm) && refBeforeGemm.size() == 1) {
// change the input index
const int beforeGemmInputId = beforeGemm->inputIndexes[0];
op->inputIndexes[0] = beforeGemmInputId;
inputId = beforeGemmInputId;
readyToDelete.push_back(beforeGemm);
}
auto paramInner = op->main.AsInnerProduct();
const auto axis = paramInner->axis;
std::vector<MNN::OpT*> newOpPrevious;
std::vector<MNN::OpT*> newOpPost;
// New Reshape
MNN::OpT* reshapeT = new MNN::OpT;
newOpPrevious.push_back(reshapeT);
reshapeT->name = "____reshape____" + op->name;
auto reshapeP = new MNN::ReshapeT;
reshapeP->dims.resize(4);
for (int i = 0; i < axis; ++i) {
reshapeP->dims[i] = 0;
}
reshapeP->dims[axis] = -1;
for (int i = axis + 1; i < 4; ++i) {
reshapeP->dims[i] = 1;
}
if (mNet->sourceType == MNN::NetSource_TENSORFLOW) {
reshapeP->dims[3] = -1;
reshapeP->dims[1] = 1;
reshapeP->dims[2] = 1;
}
reshapeT->main.type = MNN::OpParameter_Reshape;
reshapeT->type = MNN::OpType_Reshape;
reshapeT->main.value = reshapeP;
// Net Tensor
mNet->tensorName.push_back(reshapeT->name);
int tempId = mNet->tensorName.size() - 1;
reshapeT->inputIndexes.push_back(inputId);
reshapeT->outputIndexes.push_back(tempId);
auto opName = op->name;
bool needPermute = 1 != axis && mNet->sourceType == MNN::NetSource_CAFFE;
if (needPermute) {
// Add Permute
auto permuteBefore = new MNN::OpT;
permuteBefore->type = MNN::OpType_Permute;
permuteBefore->main.type = MNN::OpParameter_Permute;
auto permuteT = new MNN::PermuteT;
permuteBefore->name = "___permute1__" + reshapeT->name;
permuteT->dims.resize(4);
for (int i = 0; i < 4; ++i) {
permuteT->dims[i] = i;
}
permuteT->dims[1] = axis;
permuteT->dims[axis] = 3;
permuteT->dims[3] = 1;
permuteBefore->main.value = permuteT;
permuteBefore->inputIndexes.push_back(tempId);
mNet->tensorName.push_back(permuteBefore->name);
tempId = mNet->tensorName.size() - 1;
permuteBefore->outputIndexes.push_back(tempId);
newOpPrevious.push_back(permuteBefore);
}
op->inputIndexes[0] = tempId;
op->type = MNN::OpType_Convolution;
auto convP = new MNN::Convolution2DT;
auto originInner = op->main.AsInnerProduct();
convP->common = std::unique_ptr<MNN::Convolution2DCommonT>(new MNN::Convolution2DCommonT);
convP->common->kernelX = 1;
convP->common->kernelY = 1;
convP->common->dilateX = 1;
convP->common->dilateY = 1;
convP->common->strideX = 1;
convP->common->strideY = 1;
convP->common->group = 1;
convP->common->outputCount = originInner->outputCount;
convP->common->padX = 0;
convP->common->padY = 0;
convP->common->padMode = MNN::PadMode_CAFFE;
convP->bias = originInner->bias;
convP->weight = originInner->weight;
convP->quanParameter = std::move(originInner->quanParameter);
if (convP->quanParameter.get() != nullptr) {
convP->quanParameter->has_scaleInt = false;
}
op->main.Reset();
op->main.type = MNN::OpParameter_Convolution2D;
op->main.value = convP;
if (needPermute) {
// Add Permute After
auto permuteBefore = new MNN::OpT;
permuteBefore->type = MNN::OpType_Permute;
permuteBefore->main.type = MNN::OpParameter_Permute;
auto permuteT = new MNN::PermuteT;
permuteBefore->name = "___permute2__" + reshapeT->name;
permuteT->dims.resize(4);
permuteT->dims[0] = 0;
permuteT->dims[1] = 3;
permuteT->dims[2] = 2;
permuteT->dims[3] = 2;
permuteT->dims[axis] = 1;
permuteBefore->main.value = permuteT;
mNet->tensorName.push_back(permuteBefore->name);
tempId = mNet->tensorName.size() - 1;
permuteBefore->inputIndexes.push_back(tempId);
permuteBefore->outputIndexes.push_back(op->outputIndexes[0]);
op->outputIndexes[0] = tempId;
newOpPost.push_back(permuteBefore);
}
for (int i = 0; i < newOpPrevious.size(); ++i) {
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(newOpPrevious[newOpPrevious.size() - i - 1]));
}
for (;; iter++) {
auto& op = *iter;
if (op->name == opName) {
break;
}
}
for (int i = 0; i < newOpPost.size(); ++i) {
iter = mNet->oplists.insert(iter + 1, std::unique_ptr<MNN::OpT>(newOpPost[i]));
}
}
for (auto op : readyToDelete) {
_removeOpInNet(op);
}
}
void PostTreatUtils::turnGroupConvolution() {
// Pick DepthWise one
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
const auto op_type = op->type;
auto conv2D = op->main.AsConvolution2D();
auto& common = conv2D->common;
if (op_type == MNN::OpType_Convolution || op_type == MNN::OpType_Deconvolution) {
bool turnConv2DW = false;
// check whether idst quantization model
if (nullptr != conv2D->quanParameter.get()) {
auto& quanParam = conv2D->quanParameter;
auto quanWeightBuffer = quanParam->buffer.data();
const int weightShapeDim = static_cast<int>(quanWeightBuffer[0]);
if (weightShapeDim == 4) {
const auto weightShapePtr = reinterpret_cast<unsigned short*>(quanWeightBuffer + 1);
int ci = weightShapePtr[1];
if (ci == 1 && common->group != 1 && mNet->sourceType == MNN::NetSource_CAFFE) {
ci = weightShapePtr[0];
}
turnConv2DW = common->outputCount == common->group && ci == common->outputCount;
}
} else {
const int srcCount =
conv2D->weight.size() * common->group / common->outputCount / common->kernelX / common->kernelY;
turnConv2DW = common->outputCount == common->group && srcCount == common->outputCount;
}
if (turnConv2DW) {
switch (op_type) {
case MNN::OpType_Convolution:
op->type = MNN::OpType_ConvolutionDepthwise;
break;
case MNN::OpType_Deconvolution:
op->type = MNN::OpType_DeconvolutionDepthwise;
break;
default:
break;
}
}
}
}
// Delete Convolution With Grouop
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_Convolution && op->type != MNN::OpType_Deconvolution) {
iter++;
continue;
}
auto conv2D = op->main.AsConvolution2D();
auto& common = conv2D->common;
if (common->group == 1) {
iter++;
continue;
}
int srcCount = conv2D->weight.size() * common->group / common->outputCount / common->kernelX / common->kernelY;
DCHECK(srcCount % common->group == 0 && common->outputCount % common->group == 0)
<< "split group convolution ERROR! ==> " << op->name;
std::vector<int> newConvolutionInputIndex;
std::vector<int> newConvolutionOutputIndex;
for (int i = 0; i < common->group; ++i) {
std::ostringstream newTensorNameOs;
newTensorNameOs << op->name << "___input___" << i;
newConvolutionInputIndex.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(newTensorNameOs.str());
}
for (int i = 0; i < common->group; ++i) {
std::ostringstream newTensorNameOs;
newTensorNameOs << op->name << "___output___" << i;
newConvolutionOutputIndex.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(newTensorNameOs.str());
}
std::vector<MNN::OpT*> newOp;
// Create slice op
{
MNN::OpT* sliceOp = new MNN::OpT;
sliceOp->type = MNN::OpType_Slice;
sliceOp->name = op->name + "_____slice";
sliceOp->inputIndexes = op->inputIndexes;
sliceOp->outputIndexes = newConvolutionInputIndex;
auto sliceT = new MNN::SliceT;
sliceOp->main.type = MNN::OpParameter_Slice;
sliceOp->main.value = sliceT;
sliceT->axis = 1;
for (int i = 0; i < common->group - 1; ++i) {
sliceT->slicePoints.push_back(srcCount / (common->group) * (i + 1));
}
newOp.push_back(sliceOp);
}
int partWeightSize = conv2D->weight.size() / common->group;
int partBiasSize = conv2D->bias.size() / common->group;
// Create Sub Convolution
for (int i = 0; i < common->group; ++i) {
std::ostringstream opNameOs;
auto newConvOp = new MNN::OpT;
opNameOs << op->name << "__group__" << i;
newConvOp->type = op->type;
newConvOp->name = opNameOs.str();
newConvOp->main.type = MNN::OpParameter_Convolution2D;
newConvOp->inputIndexes.push_back(newConvolutionInputIndex[i]);
newConvOp->outputIndexes.push_back(newConvolutionOutputIndex[i]);
auto newConvolutionT = new MNN::Convolution2DT;
newConvOp->main.value = newConvolutionT;
newConvolutionT->common = std::unique_ptr<MNN::Convolution2DCommonT>(new MNN::Convolution2DCommonT);
newConvolutionT->common->kernelX = common->kernelX;
newConvolutionT->common->kernelY = common->kernelY;
newConvolutionT->common->dilateY = common->dilateY;
newConvolutionT->common->dilateX = common->dilateX;
newConvolutionT->common->strideX = common->strideX;
newConvolutionT->common->strideY = common->strideY;
newConvolutionT->common->group = 1;
newConvolutionT->common->padMode = common->padMode;
newConvolutionT->common->outputCount = common->outputCount / common->group;
newConvolutionT->common->padX = common->padX;
newConvolutionT->common->padY = common->padY;
newConvolutionT->common->relu = common->relu;
int startWeight = partWeightSize * i;
int startBias = partBiasSize * i;
for (int v = 0; v < partWeightSize; ++v) {
newConvolutionT->weight.push_back(conv2D->weight[startWeight + v]);
}
for (int v = 0; v < partBiasSize; ++v) {
newConvolutionT->bias.push_back(conv2D->bias[startBias + v]);
}
newOp.push_back(newConvOp);
}
// Set this op be Concat Op
{
op->type = MNN::OpType_Concat;
op->inputIndexes = newConvolutionOutputIndex;
op->main.Reset();
op->main.type = MNN::OpParameter_Axis;
auto axisT = new MNN::AxisT;
axisT->axis = 1;
op->main.value = axisT;
}
for (int v = 0; v < newOp.size(); ++v) {
int index = newOp.size() - v - 1;
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(newOp[index]));
}
}
}
void PostTreatUtils::changeBatchnNorm2Scale() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
const MNN::OpType opType = op->type;
if (MNN::OpType_BatchNorm != opType) {
iter++;
continue;
}
// instance norm have three input tensors(input_tensor, mean, variance)
if (op->inputIndexes.size() != 1) {
iter++;
continue;
}
// DLOG(INFO) << "change BatchNorm to Scale: " << op->name;
auto batchnormParam = op->main.AsBatchNorm();
auto scaleParam = new MNN::ScaleT;
scaleParam->channels = batchnormParam->channels;
scaleParam->scaleData.resize(batchnormParam->channels);
scaleParam->biasData.resize(batchnormParam->channels);
const float* slopePtr = batchnormParam->slopeData.data();
const float* meanDataPtr = batchnormParam->meanData.data();
const float* varDataPtr = batchnormParam->varData.data();
const float* biasDataPtr = batchnormParam->biasData.data();
for (int i = 0; i < batchnormParam->channels; i++) {
float sqrt_var = sqrt(varDataPtr[i]);
scaleParam->biasData[i] = biasDataPtr[i] - slopePtr[i] * meanDataPtr[i] / sqrt_var;
scaleParam->scaleData[i] = slopePtr[i] / sqrt_var;
}
op->type = MNN::OpType_Scale;
op->main.type = MNN::OpParameter_Scale;
op->main.value = scaleParam;
}
}
| 38,240
| 12,380
|
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "base/scheduler_stub.h"
#include "testing/base/public/gunit.h"
namespace mozc {
namespace {
static int g_counter = 0;
static bool g_result = true;
bool TestFunc(void *data) {
++g_counter;
return g_result;
}
class SchedulerStubTest : public ::testing::Test {
protected:
virtual void SetUp() {
g_counter = 0;
g_result = true;
}
virtual void TearDown() {
g_counter = 0;
g_result = true;
}
};
TEST_F(SchedulerStubTest, AddRemoveJob) {
SchedulerStub scheduler_stub;
EXPECT_FALSE(scheduler_stub.HasJob("Test"));
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test", 1000, 100000, 5000, 0, &TestFunc, NULL));
EXPECT_TRUE(scheduler_stub.HasJob("Test"));
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay_start
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000); // default_interval
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000); // default_interval
EXPECT_EQ(3, g_counter);
scheduler_stub.RemoveJob("Test");
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
EXPECT_FALSE(scheduler_stub.HasJob("Test"));
}
TEST_F(SchedulerStubTest, BackOff) {
SchedulerStub scheduler_stub;
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test", 1000, 6000, 3000, 0, &TestFunc, NULL));
g_result = false;
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay_start
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000)
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000 * 2)
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000 * 4)
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
// backoff (wait 1000 + 1000 * 8) > 6000, use same delay
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
g_result = true;
// use same delay
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(6, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(7, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
}
TEST_F(SchedulerStubTest, AddRemoveJobs) {
SchedulerStub scheduler_stub;
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test1", 1000, 100000, 1000, 0, &TestFunc, NULL));
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay
EXPECT_EQ(1, g_counter);
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test2", 1000, 100000, 1000, 0, &TestFunc, NULL));
scheduler_stub.PutClockForward(1000); // delay + interval
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.RemoveJob("Test3"); // nothing happens
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(7, g_counter);
scheduler_stub.RemoveJob("Test2");
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
scheduler_stub.RemoveAllJobs();
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
}
} // namespace
} // namespace mozc
| 6,076
| 2,641
|
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "../Header/DotCloud.h"
using namespace std;
using namespace dt;
vector<Vector3D*> DotCloudReader::GetDotCloud()
{
vector<Vector3D*> dots = vector<Vector3D*>();
string filename;
cout << "Enter name of file in resource directory: ";
cin >> filename;
filename = "Resource\\" + filename;
ifstream file(filename);
double x = 0, y = 0, z = 0;
int red = 0, green = 0, blue = 0;
char hex;
//each row start with a "#"
while (file >> hex)
{
file >> x >> y >> z >> red >> green >> blue;
Vector3D* dot = new Vector3D(x, y, z, (uint8_t)red, (uint8_t)green, (uint8_t)blue);
dots.push_back(dot);
}
file.close();
return dots;
}
| 787
| 288
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/transport_security_state.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_param_associator.h"
#include "base/rand_util.h"
#include "base/strings/string_piece.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/openssl_util.h"
#include "crypto/sha2.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/ct_policy_status.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_cert_types.h"
#include "net/cert/x509_certificate.h"
#include "net/extras/preload_data/decoder.h"
#include "net/http/hsts_info.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/net_buildflags.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/tools/huffman_trie/bit_writer.h"
#include "net/tools/huffman_trie/trie/trie_bit_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
namespace test_default {
#include "net/http/transport_security_state_static_unittest_default.h"
}
namespace test1 {
#include "net/http/transport_security_state_static_unittest1.h"
}
namespace test2 {
#include "net/http/transport_security_state_static_unittest2.h"
}
namespace test3 {
#include "net/http/transport_security_state_static_unittest3.h"
}
const char kHost[] = "example.test";
const uint16_t kPort = 443;
const char kReportUri[] = "http://report-example.test/test";
const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
const char kExpectCTStaticReportURI[] =
"http://report-uri.preloaded.test/expect-ct";
const char* const kGoodPath[] = {
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"sha256/fzP+pVAbH0hRoUphJKenIP8+2tD/d2QH9J+kQNieM6Q=",
"sha256/9vRUVdjloCa4wXUKfDWotV5eUXYD7vu0v0z9SRzQdzg=",
"sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY=",
nullptr,
};
const char* const kBadPath[] = {
"sha256/1111111111111111111111111111111111111111111=",
"sha256/2222222222222222222222222222222222222222222=",
"sha256/3333333333333333333333333333333333333333333=", nullptr,
};
// Constructs a SignedCertificateTimestampAndStatus with the given information
// and appends it to |sct_list|.
void MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::Origin origin,
const std::string& log_id,
const std::string& extensions,
const std::string& signature_data,
const base::Time& timestamp,
ct::SCTVerifyStatus status,
SignedCertificateTimestampAndStatusList* sct_list) {
scoped_refptr<net::ct::SignedCertificateTimestamp> sct(
new net::ct::SignedCertificateTimestamp());
sct->version = net::ct::SignedCertificateTimestamp::V1;
sct->log_id = log_id;
sct->extensions = extensions;
sct->timestamp = timestamp;
sct->signature.signature_data = signature_data;
sct->origin = origin;
sct_list->push_back(net::SignedCertificateTimestampAndStatus(sct, status));
}
// A mock ReportSenderInterface that just remembers the latest report
// URI and report to be sent.
class MockCertificateReportSender
: public TransportSecurityState::ReportSenderInterface {
public:
MockCertificateReportSender() = default;
~MockCertificateReportSender() override = default;
void Send(const GURL& report_uri,
base::StringPiece content_type,
base::StringPiece report,
const base::Callback<void()>& success_callback,
const base::Callback<void(const GURL&, int, int)>& error_callback)
override {
latest_report_uri_ = report_uri;
latest_report_.assign(report.data(), report.size());
latest_content_type_.assign(content_type.data(), content_type.size());
}
void Clear() {
latest_report_uri_ = GURL();
latest_report_ = std::string();
latest_content_type_ = std::string();
}
const GURL& latest_report_uri() { return latest_report_uri_; }
const std::string& latest_report() { return latest_report_; }
const std::string& latest_content_type() { return latest_content_type_; }
private:
GURL latest_report_uri_;
std::string latest_report_;
std::string latest_content_type_;
};
// A mock ReportSenderInterface that simulates a net error on every report sent.
class MockFailingCertificateReportSender
: public TransportSecurityState::ReportSenderInterface {
public:
MockFailingCertificateReportSender() : net_error_(ERR_CONNECTION_FAILED) {}
~MockFailingCertificateReportSender() override = default;
int net_error() { return net_error_; }
// TransportSecurityState::ReportSenderInterface:
void Send(const GURL& report_uri,
base::StringPiece content_type,
base::StringPiece report,
const base::Callback<void()>& success_callback,
const base::Callback<void(const GURL&, int, int)>& error_callback)
override {
ASSERT_FALSE(error_callback.is_null());
error_callback.Run(report_uri, net_error_, 0);
}
private:
const int net_error_;
};
// A mock ExpectCTReporter that remembers the latest violation that was
// reported and the number of violations reported.
class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
public:
MockExpectCTReporter() : num_failures_(0) {}
~MockExpectCTReporter() override = default;
void OnExpectCTFailed(const HostPortPair& host_port_pair,
const GURL& report_uri,
base::Time expiration,
const X509Certificate* validated_certificate_chain,
const X509Certificate* served_certificate_chain,
const SignedCertificateTimestampAndStatusList&
signed_certificate_timestamps) override {
num_failures_++;
host_port_pair_ = host_port_pair;
report_uri_ = report_uri;
expiration_ = expiration;
served_certificate_chain_ = served_certificate_chain;
validated_certificate_chain_ = validated_certificate_chain;
signed_certificate_timestamps_ = signed_certificate_timestamps;
}
const HostPortPair& host_port_pair() { return host_port_pair_; }
const GURL& report_uri() { return report_uri_; }
const base::Time& expiration() { return expiration_; }
uint32_t num_failures() { return num_failures_; }
const X509Certificate* served_certificate_chain() {
return served_certificate_chain_;
}
const X509Certificate* validated_certificate_chain() {
return validated_certificate_chain_;
}
const SignedCertificateTimestampAndStatusList&
signed_certificate_timestamps() {
return signed_certificate_timestamps_;
}
private:
HostPortPair host_port_pair_;
GURL report_uri_;
base::Time expiration_;
uint32_t num_failures_;
const X509Certificate* served_certificate_chain_;
const X509Certificate* validated_certificate_chain_;
SignedCertificateTimestampAndStatusList signed_certificate_timestamps_;
};
class MockRequireCTDelegate : public TransportSecurityState::RequireCTDelegate {
public:
MOCK_METHOD3(IsCTRequiredForHost,
CTRequirementLevel(const std::string& hostname,
const X509Certificate* chain,
const HashValueVector& hashes));
};
void CompareCertificateChainWithList(
const scoped_refptr<X509Certificate>& cert_chain,
const base::Value* cert_list) {
ASSERT_TRUE(cert_chain);
ASSERT_TRUE(cert_list->is_list());
std::vector<std::string> pem_encoded_chain;
cert_chain->GetPEMEncodedChain(&pem_encoded_chain);
ASSERT_EQ(pem_encoded_chain.size(), cert_list->GetList().size());
for (size_t i = 0; i < pem_encoded_chain.size(); i++) {
const std::string& list_cert = cert_list->GetList()[i].GetString();
EXPECT_EQ(pem_encoded_chain[i], list_cert);
}
}
void CheckHPKPReport(
const std::string& report,
const HostPortPair& host_port_pair,
bool include_subdomains,
const std::string& noted_hostname,
const scoped_refptr<X509Certificate>& served_certificate_chain,
const scoped_refptr<X509Certificate>& validated_certificate_chain,
const HashValueVector& known_pins) {
base::Optional<base::Value> value = base::JSONReader::Read(report);
ASSERT_TRUE(value.has_value());
const base::Value& report_dict = value.value();
ASSERT_TRUE(report_dict.is_dict());
const std::string* report_hostname = report_dict.FindStringKey("hostname");
ASSERT_TRUE(report_hostname);
EXPECT_EQ(host_port_pair.host(), *report_hostname);
base::Optional<int> report_port = report_dict.FindIntKey("port");
ASSERT_TRUE(report_port.has_value());
EXPECT_EQ(host_port_pair.port(), report_port.value());
base::Optional<bool> report_include_subdomains =
report_dict.FindBoolKey("include-subdomains");
ASSERT_TRUE(report_include_subdomains.has_value());
EXPECT_EQ(include_subdomains, report_include_subdomains.value());
const std::string* report_noted_hostname =
report_dict.FindStringKey("noted-hostname");
ASSERT_TRUE(report_noted_hostname);
EXPECT_EQ(noted_hostname, *report_noted_hostname);
// TODO(estark): check times in RFC3339 format.
const std::string* report_expiration =
report_dict.FindStringKey("effective-expiration-date");
ASSERT_TRUE(report_expiration);
EXPECT_FALSE(report_expiration->empty());
const std::string* report_date = report_dict.FindStringKey("date-time");
ASSERT_TRUE(report_date);
EXPECT_FALSE(report_date->empty());
const base::Value* report_served_certificate_chain =
report_dict.FindKey("served-certificate-chain");
ASSERT_TRUE(report_served_certificate_chain);
ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
served_certificate_chain, report_served_certificate_chain));
const base::Value* report_validated_certificate_chain =
report_dict.FindKey("validated-certificate-chain");
ASSERT_TRUE(report_validated_certificate_chain);
ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
validated_certificate_chain, report_validated_certificate_chain));
}
bool operator==(const TransportSecurityState::STSState& lhs,
const TransportSecurityState::STSState& rhs) {
return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
lhs.upgrade_mode == rhs.upgrade_mode &&
lhs.include_subdomains == rhs.include_subdomains &&
lhs.domain == rhs.domain;
}
bool operator==(const TransportSecurityState::PKPState& lhs,
const TransportSecurityState::PKPState& rhs) {
return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
lhs.spki_hashes == rhs.spki_hashes &&
lhs.bad_spki_hashes == rhs.bad_spki_hashes &&
lhs.include_subdomains == rhs.include_subdomains &&
lhs.domain == rhs.domain && lhs.report_uri == rhs.report_uri;
}
} // namespace
class TransportSecurityStateTest : public testing::Test {
public:
TransportSecurityStateTest() {
SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
}
~TransportSecurityStateTest() override {
SetTransportSecurityStateSourceForTesting(nullptr);
}
void SetUp() override {
crypto::EnsureOpenSSLInit();
}
static void DisableStaticPins(TransportSecurityState* state) {
state->enable_static_pins_ = false;
}
static void EnableStaticPins(TransportSecurityState* state) {
state->enable_static_pins_ = true;
}
static void EnableStaticExpectCT(TransportSecurityState* state) {
state->enable_static_expect_ct_ = true;
}
static HashValueVector GetSampleSPKIHashes() {
HashValueVector spki_hashes;
HashValue hash(HASH_VALUE_SHA256);
memset(hash.data(), 0, hash.size());
spki_hashes.push_back(hash);
return spki_hashes;
}
static HashValue GetSampleSPKIHash(uint8_t value) {
HashValue hash(HASH_VALUE_SHA256);
memset(hash.data(), value, hash.size());
return hash;
}
protected:
bool GetStaticDomainState(TransportSecurityState* state,
const std::string& host,
TransportSecurityState::STSState* sts_result,
TransportSecurityState::PKPState* pkp_result) {
return state->GetStaticDomainState(host, sts_result, pkp_result);
}
bool GetExpectCTState(TransportSecurityState* state,
const std::string& host,
TransportSecurityState::ExpectCTState* result) {
return state->GetStaticExpectCTState(host, result);
}
};
TEST_F(TransportSecurityStateTest, DomainNameOddities) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// DNS suffix search tests. Some DNS resolvers allow a terminal "." to
// indicate not perform DNS suffix searching. Ensure that regardless
// of how this is treated at the resolver layer, or at the URL/origin
// layer (that is, whether they are treated as equivalent or distinct),
// ensure that for policy matching, something lacking a terminal "."
// is equivalent to something with a terminal "."
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
state.AddHSTS("example.com", expiry, true /* include_subdomains */);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
// Trailing '.' should be equivalent; it's just a resolver hint
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com."));
// Leading '.' should be invalid
EXPECT_FALSE(state.ShouldUpgradeToSSL(".example.com"));
// Subdomains should work regardless
EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com."));
// But invalid subdomains should be rejected
EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com."));
// Now try the inverse form
TransportSecurityState state2;
state2.AddHSTS("example.net.", expiry, true /* include_subdomains */);
EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net."));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net"));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net."));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net"));
// Finally, test weird things
TransportSecurityState state3;
state3.AddHSTS("", expiry, true /* include_subdomains */);
EXPECT_FALSE(state3.ShouldUpgradeToSSL(""));
EXPECT_FALSE(state3.ShouldUpgradeToSSL("."));
EXPECT_FALSE(state3.ShouldUpgradeToSSL("..."));
// Make sure it didn't somehow apply HSTS to the world
EXPECT_FALSE(state3.ShouldUpgradeToSSL("example.org"));
TransportSecurityState state4;
state4.AddHSTS(".", expiry, true /* include_subdomains */);
EXPECT_FALSE(state4.ShouldUpgradeToSSL(""));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("."));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("..."));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("example.org"));
// Now do the same for preloaded entries
TransportSecurityState state5;
EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test"));
EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test."));
EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test"));
EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test."));
}
TEST_F(TransportSecurityStateTest, SimpleMatches) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example.com"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example.com"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("foo.example.com"));
}
TEST_F(TransportSecurityStateTest, MatchesCase1) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
bool include_subdomains = false;
state.AddHSTS("EXample.coM", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
}
TEST_F(TransportSecurityStateTest, MatchesCase2) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Check dynamic entries
EXPECT_FALSE(state.ShouldUpgradeToSSL("EXample.coM"));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("EXample.coM"));
// Check static entries
EXPECT_TRUE(state.ShouldUpgradeToSSL("hStS-prelOAded.tEsT"));
EXPECT_TRUE(
state.ShouldUpgradeToSSL("inClude-subDOmaIns-hsts-prEloaDed.TesT"));
}
TEST_F(TransportSecurityStateTest, SubdomainMatches) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.test"));
bool include_subdomains = true;
state.AddHSTS("example.test", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.baz.example.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("notexample.test"));
}
// Tests that a more-specific HSTS or HPKP rule overrides a less-specific rule
// with it, regardless of the includeSubDomains bit. This is a regression test
// for https://crbug.com/469957. Note this behavior does not match the spec.
// See https://crbug.com/821811.
TEST_F(TransportSecurityStateTest, SubdomainCarveout) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, true);
state.AddHSTS("foo.example1.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
state.AddHPKP("foo.example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
// The foo.example1.test rule overrides the example1.test rule, so
// bar.foo.example1.test has no HSTS state.
EXPECT_FALSE(state.ShouldUpgradeToSSL("bar.foo.example1.test"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
// The foo.example2.test rule overrides the example1.test rule, so
// bar.foo.example2.test has no HPKP state.
EXPECT_FALSE(state.HasPublicKeyPins("bar.foo.example2.test"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example2.test"));
// Expire the foo.example*.test rules.
state.AddHSTS("foo.example1.test", older, false);
state.AddHPKP("foo.example2.test", older, false, GetSampleSPKIHashes(),
report_uri);
// Now the base example*.test rules apply to bar.foo.example*.test.
EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example1.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("bar.foo.example2.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example2.test"));
}
TEST_F(TransportSecurityStateTest, FatalSSLErrors) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, false);
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
// The presense of either HSTS or HPKP is enough to make SSL errors fatal.
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example1.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example2.test"));
}
// Tests that HPKP and HSTS state both expire. Also tests that expired entries
// are pruned.
TEST_F(TransportSecurityStateTest, Expiration) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
// Note: this test assumes that inserting an entry with an expiration time in
// the past works and is pruned on query.
state.AddHSTS("example1.test", older, false);
EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.has_dynamic_pkp_state());
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(state.has_dynamic_pkp_state());
state.AddHSTS("example1.test", older, false);
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_TRUE(state.has_dynamic_pkp_state());
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.has_dynamic_pkp_state());
// Test that HSTS can outlive HPKP.
state.AddHSTS("example1.test", expiry, false);
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Test that HPKP can outlive HSTS.
state.AddHSTS("example2.test", older, false);
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
}
// Tests that HPKP and HSTS state are queried independently for subdomain
// matches.
TEST_F(TransportSecurityStateTest, IndependentSubdomain) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, true);
state.AddHPKP("example1.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
state.AddHSTS("example2.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("foo.example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
}
// Tests that HPKP and HSTS state are inserted and overridden independently.
TEST_F(TransportSecurityStateTest, IndependentInsertion) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Place an includeSubdomains HSTS entry below a normal HPKP entry.
state.AddHSTS("example1.test", expiry, true);
state.AddHPKP("foo.example1.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Drop the includeSubdomains from the HSTS entry.
state.AddHSTS("example1.test", expiry, false);
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
// Place an includeSubdomains HPKP entry below a normal HSTS entry.
state.AddHSTS("foo.example2.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
// Drop the includeSubdomains from the HSTS entry.
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_FALSE(state.HasPublicKeyPins("foo.example2.test"));
}
// Tests that GetDynamic[PKP|STS]State returns the correct data and that the
// states are not mixed together.
TEST_F(TransportSecurityStateTest, DynamicDomainState) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry1 = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time expiry2 = current_time + base::TimeDelta::FromSeconds(2000);
state.AddHSTS("example.com", expiry1, true);
state.AddHPKP("foo.example.com", expiry2, false, GetSampleSPKIHashes(),
report_uri);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
ASSERT_TRUE(state.GetDynamicSTSState("foo.example.com", &sts_state, nullptr));
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
EXPECT_TRUE(sts_state.ShouldUpgradeToSSL());
EXPECT_TRUE(pkp_state.HasPublicKeyPins());
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_EQ(expiry1, sts_state.expiry);
EXPECT_EQ(expiry2, pkp_state.expiry);
EXPECT_EQ("example.com", sts_state.domain);
EXPECT_EQ("foo.example.com", pkp_state.domain);
}
// Tests that new pins always override previous pins. This should be true for
// both pins at the same domain or includeSubdomains pins at a parent domain.
TEST_F(TransportSecurityStateTest, NewPinsOverride) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
TransportSecurityState::PKPState pkp_state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
HashValue hash1(HASH_VALUE_SHA256);
memset(hash1.data(), 0x01, hash1.size());
HashValue hash2(HASH_VALUE_SHA256);
memset(hash2.data(), 0x02, hash1.size());
HashValue hash3(HASH_VALUE_SHA256);
memset(hash3.data(), 0x03, hash1.size());
state.AddHPKP("example.com", expiry, true, HashValueVector(1, hash1),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash1);
state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash2),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash2);
state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash3),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash3);
}
TEST_F(TransportSecurityStateTest, DeleteAllDynamicDataSince) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState::ExpectCTState expect_ct_state;
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
EXPECT_FALSE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
state.AddHPKP("example.com", expiry, include_subdomains,
GetSampleSPKIHashes(), GURL());
state.AddExpectCT("example.com", expiry, true, GURL());
state.DeleteAllDynamicDataSince(expiry, base::DoNothing());
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_TRUE(state.HasPublicKeyPins("example.com"));
EXPECT_TRUE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
state.DeleteAllDynamicDataSince(older, base::DoNothing());
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
EXPECT_FALSE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
// Dynamic data in |state| should be empty now.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.has_dynamic_pkp_state());
EXPECT_FALSE(TransportSecurityState::ExpectCTStateIterator(state).HasNext());
}
TEST_F(TransportSecurityStateTest, DeleteDynamicDataForHost) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
bool include_subdomains = false;
state.AddHSTS("example1.test", expiry, include_subdomains);
state.AddHPKP("example1.test", expiry, include_subdomains,
GetSampleSPKIHashes(), GURL());
state.AddExpectCT("example1.test", expiry, true, GURL());
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example2.test"));
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(state.GetDynamicExpectCTState("example1.test", &expect_ct_state));
EXPECT_FALSE(
state.GetDynamicExpectCTState("example2.test", &expect_ct_state));
EXPECT_TRUE(state.DeleteDynamicDataForHost("example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
EXPECT_FALSE(
state.GetDynamicExpectCTState("example1.test", &expect_ct_state));
}
TEST_F(TransportSecurityStateTest, LongNames) {
TransportSecurityState state;
const char kLongName[] =
"lookupByWaveIdHashAndWaveIdIdAndWaveIdDomainAndWaveletIdIdAnd"
"WaveletIdDomainAndBlipBlipid";
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// Just checks that we don't hit a NOTREACHED.
EXPECT_FALSE(state.GetStaticDomainState(kLongName, &sts_state, &pkp_state));
EXPECT_FALSE(state.GetDynamicSTSState(kLongName, &sts_state, nullptr));
EXPECT_FALSE(state.GetDynamicPKPState(kLongName, &pkp_state));
}
static bool AddHash(const std::string& type_and_base64, HashValueVector* out) {
HashValue hash;
if (!hash.FromString(type_and_base64))
return false;
out->push_back(hash);
return true;
}
TEST_F(TransportSecurityStateTest, PinValidationWithoutRejectedCerts) {
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++) {
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
}
for (size_t i = 0; kBadPath[i]; i++) {
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
}
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(state.GetStaticDomainState("no-rejected-pins-pkp.preloaded.test",
&sts_state, &pkp_state));
EXPECT_TRUE(pkp_state.HasPublicKeyPins());
std::string failure_log;
EXPECT_TRUE(pkp_state.CheckPublicKeyPins(good_hashes, &failure_log));
EXPECT_FALSE(pkp_state.CheckPublicKeyPins(bad_hashes, &failure_log));
}
// Tests that pinning violations on preloaded pins trigger reports when
// the preloaded pin contains a report URI.
TEST_F(TransportSecurityStateTest, PreloadedPKPReportUri) {
const char kPreloadedPinDomain[] = "with-report-uri-pkp.preloaded.test";
const uint16_t kPort = 443;
HostPortPair host_port_pair(kPreloadedPinDomain, kPort);
TransportSecurityState state;
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EnableStaticPins(&state);
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::STSState unused_sts_state;
ASSERT_TRUE(state.GetStaticDomainState(kPreloadedPinDomain, &unused_sts_state,
&pkp_state));
ASSERT_TRUE(pkp_state.HasPublicKeyPins());
GURL report_uri = pkp_state.report_uri;
ASSERT_TRUE(report_uri.is_valid());
ASSERT_FALSE(report_uri.is_empty());
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter, as long as they are not the real google.com
// certs in the pins.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector bad_hashes;
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
// Trigger a violation and check that it sends a report.
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(
report, host_port_pair, pkp_state.include_subdomains, pkp_state.domain,
cert1.get(), cert2.get(), pkp_state.spki_hashes));
}
// Tests that report URIs are thrown out if they point to the same host,
// over HTTPS, for which a pin was violated.
TEST_F(TransportSecurityStateTest, HPKPReportUriToSameHost) {
HostPortPair host_port_pair(kHost, kPort);
GURL https_report_uri("https://example.test/report");
GURL http_report_uri("http://example.test/report");
TransportSecurityState state;
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
HashValueVector good_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter, as long as they don't match the certs in the pins.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector bad_hashes;
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
state.AddHPKP(kHost, expiry, true, good_hashes, https_report_uri);
// Trigger a violation and check that it does not send a report
// because the report-uri is HTTPS and same-host as the pins.
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_TRUE(mock_report_sender.latest_report_uri().is_empty());
// An HTTP report uri to the same host should be okay.
state.AddHPKP("example.test", expiry, true, good_hashes, http_report_uri);
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(http_report_uri, mock_report_sender.latest_report_uri());
}
// Tests that static (preloaded) expect CT state is read correctly.
TEST_F(TransportSecurityStateTest, PreloadedExpectCT) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(
GetExpectCTState(&state, kExpectCTStaticHostname, &expect_ct_state));
EXPECT_EQ(kExpectCTStaticHostname, expect_ct_state.domain);
EXPECT_EQ(GURL(kExpectCTStaticReportURI), expect_ct_state.report_uri);
EXPECT_FALSE(
GetExpectCTState(&state, "hsts-preloaded.test", &expect_ct_state));
}
// Tests that the Expect CT reporter is not notified for invalid or absent
// header values.
TEST_F(TransportSecurityStateTest, InvalidExpectCTHeader) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
state.ProcessExpectCTHeader("blah blah", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is only notified about certificates
// chaining to public roots.
TEST_F(TransportSecurityStateTest, ExpectCTNonPublicRoot) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
ssl_info.is_issued_by_known_root = false;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.is_issued_by_known_root = true;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified when compliance
// details aren't available.
TEST_F(TransportSecurityStateTest, ExpectCTComplianceNotAvailable) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified about compliant
// connections.
TEST_F(TransportSecurityStateTest, ExpectCTCompliantCert) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for preloaded Expect-CT
// when the build is not timely.
TEST_F(TransportSecurityStateTest, PreloadedExpectCTBuildNotTimely) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
// Sanity-check that the reporter is notified if the build is timely and the
// connection is not compliant.
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for dynamic Expect-CT when
// the build is not timely.
TEST_F(TransportSecurityStateTest, DynamicExpectCTBuildNotTimely) {
HostPortPair host_port("example.test", 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
const char kHeader[] = "max-age=10, report-uri=http://report.test";
state.ProcessExpectCTHeader(kHeader, host_port, ssl_info);
// No report should have been sent and the state should not have been saved.
EXPECT_EQ(0u, reporter.num_failures());
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
// Sanity-check that the reporter is notified if the build is timely and the
// connection is not compliant.
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader(kHeader, host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for a site that
// isn't preloaded.
TEST_F(TransportSecurityStateTest, ExpectCTNotPreloaded) {
HostPortPair host_port("not-expect-ct-preloaded.test", 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
host_port.set_host(kExpectCTStaticHostname);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is notified for noncompliant
// connections.
TEST_F(TransportSecurityStateTest, ExpectCTReporter) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert1);
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl_info.signed_certificate_timestamps);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ(host_port.host(), reporter.host_port_pair().host());
EXPECT_EQ(host_port.port(), reporter.host_port_pair().port());
EXPECT_TRUE(reporter.expiration().is_null());
EXPECT_EQ(GURL(kExpectCTStaticReportURI), reporter.report_uri());
EXPECT_EQ(cert1.get(), reporter.served_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.validated_certificate_chain());
EXPECT_EQ(ssl_info.signed_certificate_timestamps.size(),
reporter.signed_certificate_timestamps().size());
EXPECT_EQ(ssl_info.signed_certificate_timestamps[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(ssl_info.signed_certificate_timestamps[0].sct,
reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that the Expect CT reporter is not notified for repeated noncompliant
// connections to the same preloaded host.
TEST_F(TransportSecurityStateTest, RepeatedExpectCTReportsForStaticExpectCT) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl_info.signed_certificate_timestamps);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
// After processing a second header, the report should not be sent again.
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Simple test for the HSTS preload process. The trie (generated from
// transport_security_state_static_unittest1.json) contains 1 entry. Test that
// the lookup methods can find the entry and correctly decode the different
// preloaded states (HSTS, HPKP, and Expect-CT).
TEST_F(TransportSecurityStateTest, DecodePreloadedSingle) {
SetTransportSecurityStateSourceForTesting(&test1::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
ASSERT_EQ(1u, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x2));
TransportSecurityState::ExpectCTState ct_state;
EXPECT_FALSE(GetExpectCTState(&state, "hsts.example.com", &ct_state));
}
// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest2.json) contains multiple
// entries with a common prefix. Test that the lookup methods can find all
// entries and correctly decode the different preloaded states (HSTS, HPKP,
// and Expect-CT) for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultiplePrefix) {
SetTransportSecurityStateSourceForTesting(&test2::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::ExpectCTState ct_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "hsts.example.com", &ct_state));
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "hpkp.example.com", &ct_state));
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(GetStaticDomainState(&state, "expect-ct.example.com", &sts_state,
&pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_TRUE(GetExpectCTState(&state, "expect-ct.example.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "mix.example.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_TRUE(GetExpectCTState(&state, "mix.example.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload-alt"),
ct_state.report_uri);
}
// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest3.json) contains a mix of
// entries. Some entries share a prefix with the prefix also having its own
// preloaded state while others share no prefix. This results in a trie with
// several different internal structures. Test that the lookup methods can find
// all entries and correctly decode the different preloaded states (HSTS, HPKP,
// and Expect-CT) for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultipleMix) {
SetTransportSecurityStateSourceForTesting(&test3::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::ExpectCTState ct_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "example.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "hpkp.example.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "example.org", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_TRUE(GetExpectCTState(&state, "example.org", &ct_state));
EXPECT_EQ(GURL("https://report.example.org/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "badssl.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "badssl.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "mix.badssl.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_TRUE(GetExpectCTState(&state, "mix.badssl.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
// This should be a simple entry in the context of
// TrieWriter::IsSimpleEntry().
EXPECT_TRUE(GetStaticDomainState(&state, "simple-entry.example.com",
&sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "simple-entry.example.com", &ct_state));
}
TEST_F(TransportSecurityStateTest, HstsHostBypassList) {
SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
std::string preloaded_tld = "example";
std::string subdomain = "sub.example";
{
TransportSecurityState state;
// Check that "example" is preloaded with subdomains.
EXPECT_TRUE(state.ShouldUpgradeToSSL(preloaded_tld));
EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
}
{
// Add "example" to the bypass list.
TransportSecurityState state({preloaded_tld});
EXPECT_FALSE(state.ShouldUpgradeToSSL(preloaded_tld));
// The preloaded entry should still apply to the subdomain.
EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
}
}
// Tests that TransportSecurityState always consults the RequireCTDelegate,
// if supplied.
TEST_F(TransportSecurityStateTest, RequireCTConsultsDelegate) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
// Dummy cert to use as the validate chain. The contents do not matter.
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert);
HashValueVector hashes;
hashes.push_back(
HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));
// If CT is required, then the requirements are not met if the CT policy
// wasn't met, but are met if the policy was met or the build was out of
// date.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate always_require_delegate;
EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
state.SetRequireCTDelegate(&always_require_delegate);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// If CT is not required, then regardless of the CT state for the host,
// it should indicate CT is not required.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate never_require_delegate;
EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
state.SetRequireCTDelegate(&never_require_delegate);
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// If the Delegate is in the default state, then it should return the same
// result as if there was no delegate in the first place.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate default_require_ct_delegate;
EXPECT_CALL(default_require_ct_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::DEFAULT));
state.SetRequireCTDelegate(&default_require_ct_delegate);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
}
// Tests that Certificate Transparency is required for Symantec-issued
// certificates, unless the certificate was issued prior to 1 June 2016
// or the issuing CA is permitted as independently operated.
TEST_F(TransportSecurityStateTest, RequireCTForSymantec) {
// Test certificates before and after the 1 June 2016 deadline.
scoped_refptr<X509Certificate> before_cert =
ImportCertFromFile(GetTestCertsDirectory(), "pre_june_2016.pem");
ASSERT_TRUE(before_cert);
scoped_refptr<X509Certificate> after_cert =
ImportCertFromFile(GetTestCertsDirectory(), "post_june_2016.pem");
ASSERT_TRUE(after_cert);
const SHA256HashValue symantec_hash_value = {
{0xb2, 0xde, 0xf5, 0x36, 0x2a, 0xd3, 0xfa, 0xcd, 0x04, 0xbd, 0x29,
0x04, 0x7a, 0x43, 0x84, 0x4f, 0x76, 0x70, 0x34, 0xea, 0x48, 0x92,
0xf8, 0x0e, 0x56, 0xbe, 0xe6, 0x90, 0x24, 0x3e, 0x25, 0x02}};
const SHA256HashValue google_hash_value = {
{0xec, 0x72, 0x29, 0x69, 0xcb, 0x64, 0x20, 0x0a, 0xb6, 0x63, 0x8f,
0x68, 0xac, 0x53, 0x8e, 0x40, 0xab, 0xab, 0x5b, 0x19, 0xa6, 0x48,
0x56, 0x61, 0x04, 0x2a, 0x10, 0x61, 0xc4, 0x61, 0x27, 0x76}};
TransportSecurityState state;
HashValueVector hashes;
hashes.push_back(HashValue(symantec_hash_value));
// Certificates issued by Symantec prior to 1 June 2016 should not
// be required to be disclosed via CT.
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// ... but certificates issued after 1 June 2016 are required to be...
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
// ... unless they were issued by an excluded intermediate.
hashes.push_back(HashValue(google_hash_value));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// And other certificates should remain unaffected.
SHA256HashValue unrelated_hash_value = {{0x01, 0x02}};
HashValueVector unrelated_hashes;
unrelated_hashes.push_back(HashValue(unrelated_hash_value));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, unrelated_hashes,
before_cert.get(), before_cert.get(),
SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, unrelated_hashes,
after_cert.get(), after_cert.get(),
SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// Tests that CAs can enable CT for testing their issuance practices, prior
// to CT becoming mandatory.
TEST_F(TransportSecurityStateTest, RequireCTViaFieldTrial) {
// Test certificates before and after the 1 June 2016 deadline.
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "dec_2017.pem");
ASSERT_TRUE(cert);
// The hashes here do not matter, but add some dummy values to simulate
// a 'real' chain.
HashValueVector hashes;
const SHA256HashValue hash_a = {{0xAA, 0xAA}};
hashes.push_back(HashValue(hash_a));
const SHA256HashValue hash_b = {{0xBB, 0xBB}};
hashes.push_back(HashValue(hash_b));
TransportSecurityState state;
// CT should not be required for this pre-existing certificate.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// However, simulating a Field Trial in which CT is required for certificates
// after 2017-12-01 should cause CT to be required for this certificate, as
// it was issued 2017-12-20.
base::FieldTrialParams params;
// Set the enforcement date to 2017-12-01 00:00:00;
params["date"] = "1512086400";
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeatureWithParameters(kEnforceCTForNewCerts,
params);
// It should fail if it doesn't comply with policy.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// It should succeed if it does comply with policy.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
// It should succeed if the build is outdated.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
// It should succeed if it was a locally-trusted CA.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), false, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
}
// Tests that Certificate Transparency is required for all of the Symantec
// Managed CAs, regardless of when the certificate was issued.
TEST_F(TransportSecurityStateTest, RequireCTForSymantecManagedCAs) {
const SHA256HashValue symantec_hash_value = {
{0xb2, 0xde, 0xf5, 0x36, 0x2a, 0xd3, 0xfa, 0xcd, 0x04, 0xbd, 0x29,
0x04, 0x7a, 0x43, 0x84, 0x4f, 0x76, 0x70, 0x34, 0xea, 0x48, 0x92,
0xf8, 0x0e, 0x56, 0xbe, 0xe6, 0x90, 0x24, 0x3e, 0x25, 0x02}};
const SHA256HashValue managed_hash_value = {
{0x7c, 0xac, 0x9a, 0x0f, 0xf3, 0x15, 0x38, 0x77, 0x50, 0xba, 0x8b,
0xaf, 0xdb, 0x1c, 0x2b, 0xc2, 0x9b, 0x3f, 0x0b, 0xba, 0x16, 0x36,
0x2c, 0xa9, 0x3a, 0x90, 0xf8, 0x4d, 0xa2, 0xdf, 0x5f, 0x3e}};
TransportSecurityState state;
HashValueVector hashes;
hashes.push_back(HashValue(symantec_hash_value));
hashes.push_back(HashValue(managed_hash_value));
// All certificates, both before and after the pre-existing 1 June 2016
// date, are expected to be compliant.
scoped_refptr<X509Certificate> before_cert =
ImportCertFromFile(GetTestCertsDirectory(), "pre_june_2016.pem");
ASSERT_TRUE(before_cert);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
scoped_refptr<X509Certificate> after_cert =
ImportCertFromFile(GetTestCertsDirectory(), "post_june_2016.pem");
ASSERT_TRUE(after_cert);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
}
// Tests that dynamic Expect-CT state is cleared from ClearDynamicData().
TEST_F(TransportSecurityStateTest, DynamicExpectCTStateCleared) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_TRUE(expect_ct_state.report_uri.is_empty());
EXPECT_EQ(expiry, expect_ct_state.expiry);
state.ClearDynamicData();
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that dynamic Expect-CT state can be added and retrieved.
TEST_F(TransportSecurityStateTest, DynamicExpectCTState) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Test that Expect-CT state can be added and retrieved.
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_TRUE(expect_ct_state.report_uri.is_empty());
EXPECT_EQ(expiry, expect_ct_state.expiry);
// Test that Expect-CT can be updated (e.g. by changing |enforce| to false and
// adding a report-uri).
const GURL report_uri("https://example-report.test");
state.AddExpectCT(host, expiry, false, report_uri);
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_FALSE(expect_ct_state.enforce);
EXPECT_EQ(report_uri, expect_ct_state.report_uri);
EXPECT_EQ(expiry, expect_ct_state.expiry);
// Test that Expect-CT state is discarded when expired.
state.AddExpectCT(host, current_time - base::TimeDelta::FromSeconds(1000),
true, report_uri);
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that the Expect-CT reporter is not notified for repeated dynamic
// Expect-CT violations for the same host/port.
TEST_F(TransportSecurityStateTest, DynamicExpectCTDeduping) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
base::Time now = base::Time::Now();
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(GURL("http://foo.test"), expect_ct_state.report_uri);
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_LT(now, expect_ct_state.expiry);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(0u, reporter.num_failures());
// The first time the host fails to meet CT requirements, a report should be
// sent.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
// The second time it fails to meet CT requirements, a report should not be
// sent.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect-CT reporter is not notified for CT-compliant
// connections.
TEST_F(TransportSecurityStateTest, DynamicExpectCTCompliantConnection) {
const char kHeader[] = "max-age=123,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that the Expect-CT reporter is not notified when the Expect-CT header
// is received repeatedly over non-compliant connections.
TEST_F(TransportSecurityStateTest, DynamicExpectCTHeaderProcessingDeduping) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
// The first time the header was received over a connection that failed to
// meet CT requirements, a report should be sent.
EXPECT_EQ(1u, reporter.num_failures());
// The second time the header was received, no report should be sent.
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that dynamic Expect-CT state cannot be added when the feature is not
// enabled.
TEST_F(TransportSecurityStateTest, DynamicExpectCTStateDisabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that dynamic Expect-CT opt-ins are processed correctly (when the
// feature is enabled).
TEST_F(TransportSecurityStateTest, DynamicExpectCT) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
// First test that the header is not processed when the feature is disabled.
{
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(
state.GetDynamicExpectCTState("example.test", &expect_ct_state));
}
// Now test that the header is processed when the feature is enabled.
{
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
base::Time now = base::Time::Now();
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(
state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(GURL("http://foo.test"), expect_ct_state.report_uri);
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_LT(now, expect_ct_state.expiry);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(0u, reporter.num_failures());
}
}
// Tests that dynamic Expect-CT is not processed for private roots.
TEST_F(TransportSecurityStateTest, DynamicExpectCTPrivateRoot) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = false;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that dynamic Expect-CT is not processed when CT compliance status
// wasn't computed.
TEST_F(TransportSecurityStateTest, DynamicExpectCTNoComplianceDetails) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl.unverified_cert = cert1;
ssl.cert = cert2;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that Expect-CT reports are sent when an Expect-CT header is received
// over a non-compliant connection.
TEST_F(TransportSecurityStateTest,
DynamicExpectCTHeaderProcessingNonCompliant) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl.unverified_cert = cert1;
ssl.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl.signed_certificate_timestamps);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_TRUE(reporter.expiration().is_null());
EXPECT_EQ(cert1.get(), reporter.served_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.validated_certificate_chain());
EXPECT_EQ(ssl.signed_certificate_timestamps.size(),
reporter.signed_certificate_timestamps().size());
EXPECT_EQ(ssl.signed_certificate_timestamps[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(ssl.signed_certificate_timestamps[0].sct,
reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that CheckCTRequirements() returns the correct response if a connection
// to a host violates an Expect-CT header, and that it reports violations.
TEST_F(TransportSecurityStateTest, CheckCTRequirementsWithExpectCT) {
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, true /* enforce */,
GURL("https://example-report.test"));
state.AddExpectCT("example-report-only.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
state.AddExpectCT("example-enforce-only.test", expiry, true /* enforce */,
GURL());
// Test that a connection to an unrelated host is not affected.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example2.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example2.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(0u, reporter.num_failures());
// A connection to an Expect-CT host should be closed and reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
// A compliant connection to an Expect-CT host should not be closed or
// reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(1u, reporter.num_failures());
// A connection to a report-only host should be reported only.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example-report-only.test", 443), true,
HashValueVector(), cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
EXPECT_EQ("example-report-only.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
// A connection to an enforce-only host should be closed but not reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example-enforce-only.test", 443), true,
HashValueVector(), cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
// A connection with a private root should be neither enforced nor reported.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), false, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
// A connection with DISABLE_EXPECT_CT_REPORTS should not send a report.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
}
// Tests that for a host that requires CT by delegate and is also
// Expect-CT-enabled, CheckCTRequirements() sends reports.
TEST_F(TransportSecurityStateTest, CheckCTRequirementsWithExpectCTAndDelegate) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
// A connection to an Expect-CT host, which also requires CT by the delegate,
// should be closed and reported.
MockRequireCTDelegate always_require_delegate;
EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
state.SetRequireCTDelegate(&always_require_delegate);
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that for a host that explicitly disabled CT by delegate and is also
// Expect-CT-enabled, CheckCTRequirements() sends reports.
TEST_F(TransportSecurityStateTest,
CheckCTRequirementsWithExpectCTAndDelegateDisables) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
// A connection to an Expect-CT host, which is exempted from the CT
// requirements by the delegate, should be reported but not closed.
MockRequireCTDelegate never_require_delegate;
EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
state.SetRequireCTDelegate(&never_require_delegate);
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that the dynamic Expect-CT UMA histogram is recorded correctly.
TEST_F(TransportSecurityStateTest, DynamicExpectCTUMA) {
const char kHistogramName[] = "Net.ExpectCTHeader.ParseSuccess";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
// Test that the histogram is recorded correctly when the header successfully
// parses.
{
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
base::HistogramTester histograms;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
histograms.ExpectTotalCount(kHistogramName, 1);
histograms.ExpectBucketCount(kHistogramName, true, 1);
}
// Test that the histogram is recorded correctly when the header fails to
// parse (due to semi-colons instead of commas).
{
const char kHeader[] = "max-age=123;enforce;report-uri=\"http://foo.test\"";
base::HistogramTester histograms;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
histograms.ExpectTotalCount(kHistogramName, 1);
histograms.ExpectBucketCount(kHistogramName, false, 1);
}
}
// Tests the Net.HstsInfo histogram is recorded correctly. See
// https://crbug.com/821811.
TEST_F(TransportSecurityStateTest, HstsInfoHistogram) {
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromDays(1000);
TransportSecurityState state;
// a.test is not on the static list, so the dynamic set applies.
state.AddHSTS("a.test", expiry, /*include_subdomains=*/true);
state.AddHSTS("a.a.test", expiry, /*include_subdomains=*/false);
// Also test the interaction with the HSTS preload list.
state.AddHSTS("a.include-subdomains-hsts-preloaded.test", expiry,
/*include_subdomains=*/true);
state.AddHSTS("a.a.include-subdomains-hsts-preloaded.test", expiry,
/*include_subdomains=*/false);
const struct {
const char* host;
HstsInfo expected;
} kTests[] = {
// HSTS was not enabled.
{"b.test", HstsInfo::kDisabled},
// HSTS was enabled via the header.
{"a.test", HstsInfo::kEnabled},
{"a.a.test", HstsInfo::kEnabled},
// HSTS was enabled via the preload list.
{"b.include-subdomains-hsts-preloaded.test", HstsInfo::kEnabled},
// HSTS should have been enabled but was not due to spec non-compliance.
{"a.a.a.test", HstsInfo::kDynamicIncorrectlyMasked},
// Spec non-compliance was masked by the preload list.
{"a.a.a.include-subdomains-hsts-preloaded.test",
HstsInfo::kDynamicIncorrectlyMaskedButMatchedStatic},
};
for (const auto& test : kTests) {
SCOPED_TRACE(test.host);
bool enabled =
test.expected == HstsInfo::kEnabled ||
test.expected == HstsInfo::kDynamicIncorrectlyMaskedButMatchedStatic;
{
base::HistogramTester histograms;
EXPECT_EQ(enabled, state.ShouldUpgradeToSSL(test.host));
histograms.ExpectTotalCount("Net.HstsInfo", 1);
histograms.ExpectBucketCount("Net.HstsInfo", test.expected, 1);
}
{
base::HistogramTester histograms;
EXPECT_EQ(enabled, state.ShouldSSLErrorsBeFatal(test.host));
histograms.ExpectTotalCount("Net.HstsInfo", 1);
histograms.ExpectBucketCount("Net.HstsInfo", test.expected, 1);
}
}
}
#if BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
const char kSubdomain[] = "foo.example.test";
class TransportSecurityStateStaticTest : public TransportSecurityStateTest {
public:
TransportSecurityStateStaticTest() {
SetTransportSecurityStateSourceForTesting(nullptr);
}
};
static bool StaticShouldRedirect(const char* hostname) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
return state.GetStaticDomainState(hostname, &sts_state, &pkp_state) &&
sts_state.ShouldUpgradeToSSL();
}
static bool HasStaticState(const char* hostname) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
return state.GetStaticDomainState(hostname, &sts_state, &pkp_state);
}
static bool HasStaticPublicKeyPins(const char* hostname) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
if (!state.GetStaticDomainState(hostname, &sts_state, &pkp_state))
return false;
return pkp_state.HasPublicKeyPins();
}
static bool OnlyPinningInStaticState(const char* hostname) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
if (!state.GetStaticDomainState(hostname, &sts_state, &pkp_state))
return false;
return (pkp_state.spki_hashes.size() > 0 ||
pkp_state.bad_spki_hashes.size() > 0) &&
!sts_state.ShouldUpgradeToSSL();
}
TEST_F(TransportSecurityStateStaticTest, EnableStaticPins) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EnableStaticPins(&state);
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
}
TEST_F(TransportSecurityStateStaticTest, DisableStaticPins) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
DisableStaticPins(&state);
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_TRUE(pkp_state.spki_hashes.empty());
}
TEST_F(TransportSecurityStateStaticTest, IsPreloaded) {
const std::string paypal = "paypal.com";
const std::string www_paypal = "www.paypal.com";
const std::string foo_paypal = "foo.paypal.com";
const std::string a_www_paypal = "a.www.paypal.com";
const std::string abc_paypal = "a.b.c.paypal.com";
const std::string example = "example.com";
const std::string aypal = "aypal.com";
const std::string google = "google";
const std::string www_google = "www.google";
const std::string foo = "foo";
const std::string bank = "example.bank";
const std::string insurance = "sub.example.insurance";
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(GetStaticDomainState(&state, paypal, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, www_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_TRUE(GetStaticDomainState(&state, google, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, www_google, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, foo, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, bank, &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_TRUE(GetStaticDomainState(&state, insurance, &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_FALSE(
GetStaticDomainState(&state, a_www_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(
GetStaticDomainState(&state, abc_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(GetStaticDomainState(&state, example, &sts_state, &pkp_state));
EXPECT_FALSE(GetStaticDomainState(&state, aypal, &sts_state, &pkp_state));
}
TEST_F(TransportSecurityStateStaticTest, PreloadedDomainSet) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// The domain wasn't being set, leading to a blank string in the
// chrome://net-internals/#hsts UI. So test that.
EXPECT_TRUE(
state.GetStaticDomainState("market.android.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.domain, "market.android.com");
EXPECT_EQ(pkp_state.domain, "market.android.com");
EXPECT_TRUE(state.GetStaticDomainState("sub.market.android.com", &sts_state,
&pkp_state));
EXPECT_EQ(sts_state.domain, "market.android.com");
EXPECT_EQ(pkp_state.domain, "market.android.com");
}
TEST_F(TransportSecurityStateStaticTest, Preloaded) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// We do more extensive checks for the first domain.
EXPECT_TRUE(
state.GetStaticDomainState("www.paypal.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.upgrade_mode,
TransportSecurityState::STSState::MODE_FORCE_HTTPS);
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_TRUE(HasStaticState("paypal.com"));
EXPECT_FALSE(HasStaticState("www2.paypal.com"));
// Google hosts:
EXPECT_TRUE(StaticShouldRedirect("chrome.google.com"));
EXPECT_TRUE(StaticShouldRedirect("checkout.google.com"));
EXPECT_TRUE(StaticShouldRedirect("wallet.google.com"));
EXPECT_TRUE(StaticShouldRedirect("docs.google.com"));
EXPECT_TRUE(StaticShouldRedirect("sites.google.com"));
EXPECT_TRUE(StaticShouldRedirect("drive.google.com"));
EXPECT_TRUE(StaticShouldRedirect("spreadsheets.google.com"));
EXPECT_TRUE(StaticShouldRedirect("appengine.google.com"));
EXPECT_TRUE(StaticShouldRedirect("market.android.com"));
EXPECT_TRUE(StaticShouldRedirect("encrypted.google.com"));
EXPECT_TRUE(StaticShouldRedirect("accounts.google.com"));
EXPECT_TRUE(StaticShouldRedirect("profiles.google.com"));
EXPECT_TRUE(StaticShouldRedirect("mail.google.com"));
EXPECT_TRUE(StaticShouldRedirect("chatenabled.mail.google.com"));
EXPECT_TRUE(StaticShouldRedirect("talkgadget.google.com"));
EXPECT_TRUE(StaticShouldRedirect("hostedtalkgadget.google.com"));
EXPECT_TRUE(StaticShouldRedirect("talk.google.com"));
EXPECT_TRUE(StaticShouldRedirect("plus.google.com"));
EXPECT_TRUE(StaticShouldRedirect("groups.google.com"));
EXPECT_TRUE(StaticShouldRedirect("apis.google.com"));
EXPECT_TRUE(StaticShouldRedirect("oauthaccountmanager.googleapis.com"));
EXPECT_TRUE(StaticShouldRedirect("passwordsleakcheck-pa.googleapis.com"));
EXPECT_TRUE(StaticShouldRedirect("ssl.google-analytics.com"));
EXPECT_TRUE(StaticShouldRedirect("google"));
EXPECT_TRUE(StaticShouldRedirect("foo.google"));
EXPECT_TRUE(StaticShouldRedirect("foo"));
EXPECT_TRUE(StaticShouldRedirect("domaintest.foo"));
EXPECT_TRUE(StaticShouldRedirect("gmail.com"));
EXPECT_TRUE(StaticShouldRedirect("www.gmail.com"));
EXPECT_TRUE(StaticShouldRedirect("googlemail.com"));
EXPECT_TRUE(StaticShouldRedirect("www.googlemail.com"));
EXPECT_TRUE(StaticShouldRedirect("googleplex.com"));
EXPECT_TRUE(StaticShouldRedirect("www.googleplex.com"));
EXPECT_TRUE(StaticShouldRedirect("www.google-analytics.com"));
EXPECT_TRUE(StaticShouldRedirect("www.youtube.com"));
EXPECT_TRUE(StaticShouldRedirect("youtube.com"));
// These domains used to be only HSTS when SNI was available.
EXPECT_TRUE(state.GetStaticDomainState("gmail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("www.gmail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("googlemail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("www.googlemail.com", &sts_state, &pkp_state));
// fi.g.co should not force HTTPS because there are still HTTP-only services
// on it.
EXPECT_FALSE(StaticShouldRedirect("fi.g.co"));
// Other hosts:
EXPECT_TRUE(StaticShouldRedirect("aladdinschools.appspot.com"));
EXPECT_TRUE(StaticShouldRedirect("ottospora.nl"));
EXPECT_TRUE(StaticShouldRedirect("www.ottospora.nl"));
EXPECT_TRUE(StaticShouldRedirect("www.paycheckrecords.com"));
EXPECT_TRUE(StaticShouldRedirect("lastpass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.lastpass.com"));
EXPECT_FALSE(HasStaticState("blog.lastpass.com"));
EXPECT_TRUE(StaticShouldRedirect("keyerror.com"));
EXPECT_TRUE(StaticShouldRedirect("www.keyerror.com"));
EXPECT_TRUE(StaticShouldRedirect("entropia.de"));
EXPECT_TRUE(StaticShouldRedirect("www.entropia.de"));
EXPECT_FALSE(HasStaticState("foo.entropia.de"));
EXPECT_TRUE(StaticShouldRedirect("www.elanex.biz"));
EXPECT_FALSE(HasStaticState("elanex.biz"));
EXPECT_FALSE(HasStaticState("foo.elanex.biz"));
EXPECT_TRUE(StaticShouldRedirect("sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("www.sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("a.b.sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("www.noisebridge.net"));
EXPECT_FALSE(HasStaticState("noisebridge.net"));
EXPECT_FALSE(HasStaticState("foo.noisebridge.net"));
EXPECT_TRUE(StaticShouldRedirect("neg9.org"));
EXPECT_FALSE(HasStaticState("www.neg9.org"));
EXPECT_TRUE(StaticShouldRedirect("riseup.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.riseup.net"));
EXPECT_TRUE(StaticShouldRedirect("factor.cc"));
EXPECT_FALSE(HasStaticState("www.factor.cc"));
EXPECT_TRUE(StaticShouldRedirect("members.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("support.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("id.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("lists.mayfirst.org"));
EXPECT_FALSE(HasStaticState("www.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("romab.com"));
EXPECT_TRUE(StaticShouldRedirect("www.romab.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.romab.com"));
EXPECT_TRUE(StaticShouldRedirect("logentries.com"));
EXPECT_TRUE(StaticShouldRedirect("www.logentries.com"));
EXPECT_FALSE(HasStaticState("foo.logentries.com"));
EXPECT_TRUE(StaticShouldRedirect("stripe.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.stripe.com"));
EXPECT_TRUE(StaticShouldRedirect("cloudsecurityalliance.org"));
EXPECT_TRUE(StaticShouldRedirect("foo.cloudsecurityalliance.org"));
EXPECT_TRUE(StaticShouldRedirect("login.sapo.pt"));
EXPECT_TRUE(StaticShouldRedirect("foo.login.sapo.pt"));
EXPECT_TRUE(StaticShouldRedirect("mattmccutchen.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.mattmccutchen.net"));
EXPECT_TRUE(StaticShouldRedirect("betnet.fr"));
EXPECT_TRUE(StaticShouldRedirect("foo.betnet.fr"));
EXPECT_TRUE(StaticShouldRedirect("uprotect.it"));
EXPECT_TRUE(StaticShouldRedirect("foo.uprotect.it"));
EXPECT_TRUE(StaticShouldRedirect("cert.se"));
EXPECT_TRUE(StaticShouldRedirect("foo.cert.se"));
EXPECT_TRUE(StaticShouldRedirect("crypto.is"));
EXPECT_TRUE(StaticShouldRedirect("foo.crypto.is"));
EXPECT_TRUE(StaticShouldRedirect("simon.butcher.name"));
EXPECT_TRUE(StaticShouldRedirect("foo.simon.butcher.name"));
EXPECT_TRUE(StaticShouldRedirect("linx.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.linx.net"));
EXPECT_TRUE(StaticShouldRedirect("dropcam.com"));
EXPECT_TRUE(StaticShouldRedirect("www.dropcam.com"));
EXPECT_FALSE(HasStaticState("foo.dropcam.com"));
EXPECT_TRUE(StaticShouldRedirect("ebanking.indovinabank.com.vn"));
EXPECT_TRUE(StaticShouldRedirect("foo.ebanking.indovinabank.com.vn"));
EXPECT_TRUE(StaticShouldRedirect("epoxate.com"));
EXPECT_FALSE(HasStaticState("foo.epoxate.com"));
EXPECT_FALSE(HasStaticState("foo.torproject.org"));
EXPECT_TRUE(StaticShouldRedirect("www.moneybookers.com"));
EXPECT_FALSE(HasStaticState("moneybookers.com"));
EXPECT_TRUE(StaticShouldRedirect("ledgerscope.net"));
EXPECT_TRUE(StaticShouldRedirect("www.ledgerscope.net"));
EXPECT_FALSE(HasStaticState("status.ledgerscope.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.app.recurly.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.api.recurly.com"));
EXPECT_TRUE(StaticShouldRedirect("greplin.com"));
EXPECT_TRUE(StaticShouldRedirect("www.greplin.com"));
EXPECT_FALSE(HasStaticState("foo.greplin.com"));
EXPECT_TRUE(StaticShouldRedirect("luneta.nearbuysystems.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.luneta.nearbuysystems.com"));
EXPECT_TRUE(StaticShouldRedirect("ubertt.org"));
EXPECT_TRUE(StaticShouldRedirect("foo.ubertt.org"));
EXPECT_TRUE(StaticShouldRedirect("pixi.me"));
EXPECT_TRUE(StaticShouldRedirect("www.pixi.me"));
EXPECT_TRUE(StaticShouldRedirect("grepular.com"));
EXPECT_TRUE(StaticShouldRedirect("www.grepular.com"));
EXPECT_TRUE(StaticShouldRedirect("mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("developer.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.developer.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.developer.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.developer.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("sandbox.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.sandbox.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.sandbox.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.sandbox.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("bigshinylock.minazo.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.bigshinylock.minazo.net"));
EXPECT_TRUE(StaticShouldRedirect("crate.io"));
EXPECT_TRUE(StaticShouldRedirect("foo.crate.io"));
EXPECT_TRUE(StaticShouldRedirect("sub.bank"));
EXPECT_TRUE(StaticShouldRedirect("sub.insurance"));
}
TEST_F(TransportSecurityStateStaticTest, PreloadedPins) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// We do more extensive checks for the first domain.
EXPECT_TRUE(
state.GetStaticDomainState("www.paypal.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.upgrade_mode,
TransportSecurityState::STSState::MODE_FORCE_HTTPS);
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_TRUE(OnlyPinningInStaticState("www.google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("foo.google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("i.ytimg.com"));
EXPECT_TRUE(OnlyPinningInStaticState("ytimg.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleusercontent.com"));
EXPECT_TRUE(OnlyPinningInStaticState("www.googleusercontent.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleapis.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleadservices.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googlecode.com"));
EXPECT_TRUE(OnlyPinningInStaticState("appspot.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googlesyndication.com"));
EXPECT_TRUE(OnlyPinningInStaticState("doubleclick.net"));
EXPECT_TRUE(OnlyPinningInStaticState("googlegroups.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("check.torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("blog.torproject.org"));
EXPECT_FALSE(HasStaticState("foo.torproject.org"));
EXPECT_TRUE(
state.GetStaticDomainState("torproject.org", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(
state.GetStaticDomainState("www.torproject.org", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(state.GetStaticDomainState("check.torproject.org", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(state.GetStaticDomainState("blog.torproject.org", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(HasStaticPublicKeyPins("www.twitter.com"));
// Check that Facebook subdomains have pinning but not HSTS.
EXPECT_TRUE(
state.GetStaticDomainState("facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("facebook.com"));
EXPECT_TRUE(
state.GetStaticDomainState("foo.facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_FALSE(StaticShouldRedirect("foo.facebook.com"));
EXPECT_TRUE(
state.GetStaticDomainState("www.facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("www.facebook.com"));
EXPECT_TRUE(state.GetStaticDomainState("foo.www.facebook.com", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("foo.www.facebook.com"));
}
TEST_F(TransportSecurityStateStaticTest, BuiltinCertPins) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_TRUE(HasStaticPublicKeyPins("chrome.google.com"));
HashValueVector hashes;
std::string failure_log;
// Checks that a built-in list does exist.
EXPECT_FALSE(pkp_state.CheckPublicKeyPins(hashes, &failure_log));
EXPECT_FALSE(HasStaticPublicKeyPins("www.paypal.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("docs.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("1.docs.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("sites.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("drive.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("spreadsheets.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("wallet.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("checkout.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("appengine.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("market.android.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("encrypted.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("accounts.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("profiles.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mail.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("chatenabled.mail.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("talkgadget.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("hostedtalkgadget.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("talk.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("plus.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("groups.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("apis.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.google-analytics.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ssl.gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ssl.google-analytics.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.googleplex.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("twitter.com"));
EXPECT_FALSE(HasStaticPublicKeyPins("foo.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("api.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("oauth.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mobile.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("dev.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("business.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("platform.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("si0.twimg.com"));
}
TEST_F(TransportSecurityStateStaticTest, OptionalHSTSCertPins) {
TransportSecurityState state;
EnableStaticPins(&state);
EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mail-attachment.googleusercontent.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("i.ytimg.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googleapis.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ajax.googleapis.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googleadservices.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("pagead2.googleadservices.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googlecode.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("kibbles.googlecode.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("appspot.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googlesyndication.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("doubleclick.net"));
EXPECT_TRUE(HasStaticPublicKeyPins("ad.doubleclick.net"));
EXPECT_TRUE(HasStaticPublicKeyPins("redirector.gvt1.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("a.googlegroups.com"));
}
TEST_F(TransportSecurityStateStaticTest, OverrideBuiltins) {
EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
EXPECT_FALSE(StaticShouldRedirect("google.com"));
EXPECT_FALSE(StaticShouldRedirect("www.google.com"));
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("www.google.com", expiry, true);
EXPECT_TRUE(state.ShouldUpgradeToSSL("www.google.com"));
}
// Tests that redundant reports are rate-limited.
TEST_F(TransportSecurityStateStaticTest, HPKPReportRateLimiting) {
HostPortPair host_port_pair(kHost, kPort);
HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
TransportSecurityState state;
EnableStaticPins(&state);
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// A report should have been sent. Check that it contains the
// right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
cert1.get(), cert2.get(),
good_hashes));
mock_report_sender.Clear();
// Now trigger the same violation; a duplicative report should not be
// sent.
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
}
TEST_F(TransportSecurityStateStaticTest, HPKPReporting) {
HostPortPair host_port_pair(kHost, kPort);
HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
TransportSecurityState state;
EnableStaticPins(&state);
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::DISABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because of the DISABLE_PIN_REPORTS
// argument.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
state.CheckPublicKeyPins(
host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because there was no violation.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::BYPASSED,
state.CheckPublicKeyPins(
host_port_pair, false, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because the certificate chained to a
// non-public root.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
state.CheckPublicKeyPins(
host_port_pair, false, good_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because there was no violation, even though
// the certificate chained to a local trust anchor.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// Now a report should have been sent. Check that it contains the
// right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
cert1.get(), cert2.get(),
good_hashes));
mock_report_sender.Clear();
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(subdomain_host_port_pair, true, bad_hashes,
cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS,
&failure_log));
// Now a report should have been sent for the subdomain. Check that it
// contains the right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, subdomain_host_port_pair,
true, kHost, cert1.get(), cert2.get(),
good_hashes));
}
// Tests that a histogram entry is recorded when TransportSecurityState
// fails to send an HPKP violation report.
TEST_F(TransportSecurityStateStaticTest, UMAOnHPKPReportingFailure) {
base::HistogramTester histograms;
const std::string histogram_name = "Net.PublicKeyPinReportSendingFailure2";
HostPortPair host_port_pair(kHost, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
// The histogram should start off empty.
histograms.ExpectTotalCount(histogram_name, 0);
TransportSecurityState state;
EnableStaticPins(&state);
MockFailingCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// Check that the UMA histogram was updated when the report failed to
// send.
histograms.ExpectTotalCount(histogram_name, 1);
histograms.ExpectBucketCount(histogram_name, -mock_report_sender.net_error(),
1);
}
TEST_F(TransportSecurityStateTest, WriteSizeDecodeSize) {
for (size_t i = 0; i < 300; ++i) {
SCOPED_TRACE(i);
huffman_trie::TrieBitBuffer buffer;
buffer.WriteSize(i);
huffman_trie::BitWriter writer;
buffer.WriteToBitWriter(&writer);
size_t position = writer.position();
writer.Flush();
ASSERT_NE(writer.bytes().data(), nullptr);
extras::PreloadDecoder::BitReader reader(writer.bytes().data(), position);
size_t decoded_size;
EXPECT_TRUE(reader.DecodeSize(&decoded_size));
EXPECT_EQ(i, decoded_size);
}
}
TEST_F(TransportSecurityStateTest, DecodeSizeFour) {
// Test that BitReader::DecodeSize properly handles the number 4, including
// not over-reading input bytes. BitReader::Next only fails if there's not
// another byte to read from; if it reads past the number of bits in the
// buffer but is still in the last byte it will still succeed. For this
// reason, this test puts the encoding of 4 at the end of the byte to check
// that DecodeSize doesn't over-read.
//
// 4 is encoded as 0b010. Shifted right to fill one byte, it is 0x02, with 5
// bits of padding.
uint8_t encoded = 0x02;
extras::PreloadDecoder::BitReader reader(&encoded, 8);
for (size_t i = 0; i < 5; ++i) {
bool unused;
ASSERT_TRUE(reader.Next(&unused));
}
size_t decoded_size;
EXPECT_TRUE(reader.DecodeSize(&decoded_size));
EXPECT_EQ(4u, decoded_size);
}
#endif // BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
} // namespace net
| 143,462
| 49,602
|
#include <iostream>
#include "validate.h"
#include "ogr_spatialref3D.h"
using namespace std;
void proj_mgi_to_geoc_etrs()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOC)" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOC_ETRS);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-x_etrs[row_number]));
err1.add(fabs(r1[row_number]-y_etrs[row_number]));
err2.add(fabs(r2[row_number]-z_etrs[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_etrs()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOG) + Ellipsoidal Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_ETRS);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_grs[row_number]));
err1.add(fabs(r1[row_number]-lat_grs[row_number]));
err2.add(fabs(r2[row_number]-hell_grs[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_etrs_ortho()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r5 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOG) + Orthometric Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_ETRS_ORTH);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
oTargetSRS.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4, err5;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
oTargetSRS.SetDebugData(&(r5[row_number]), 0);
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_grs[row_number]));
err1.add(fabs(r1[row_number]-lat_grs[row_number]));
err2.add(fabs(r2[row_number]-h_orth[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
err5.add(fabs(r5[row_number]-und_grs[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
cout << "Error (target geoid undulation) : " << endl; err5.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
CPLFree(r5);
}
void proj_mgi_to_geoc_mgi()
{
}
void proj_mgi_to_geog_mgi()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: MGI (GEOG)" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_MGI);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_mgi[row_number]));
err1.add(fabs(r1[row_number]-lat_mgi[row_number]));
err2.add(fabs(r2[row_number]-hell_mgi[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_mgi_ortho()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r5 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: MGI (GEOG) + Orthometric Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_MGI_ORTH);
oTargetSRS.importFromWkt3D(&(wkt2));
oTargetSRS.SetDebug(true);
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4, err5;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
oTargetSRS.SetDebugData(&(r5[row_number]), 0);
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_mgi[row_number]));
err1.add(fabs(r1[row_number]-lat_mgi[row_number]));
err2.add(fabs(r2[row_number]-h_orth[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
err5.add(fabs(r5[row_number]-und_bess[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
cout << "Error (target geoid undulation) : " << endl; err5.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
CPLFree(r5);
}
void val_proj_mgi()
{
proj_mgi_to_geoc_etrs();
proj_mgi_to_geog_etrs();
proj_mgi_to_geog_etrs_ortho();
proj_mgi_to_geoc_mgi();
proj_mgi_to_geog_mgi();
proj_mgi_to_geog_mgi_ortho();
}
| 16,901
| 7,946
|
#include <example_add.hpp>
Integer::Integer(unsigned _x): x(_x)
{}
std::unique_ptr<Example_result> Integer::clone() const
{
return std::make_unique<Integer>(x);
}
unsigned Integer::hash() const
{
return x;
}
std::unique_ptr<Example_job> Add::clone() const
{
return std::make_unique<Add>();
}
std::unique_ptr<Result> Add::execute(
const std::vector<const Result *> & args) const
{
unsigned sum = 0; // Modular arithmetic (% 2^32)
for (const Result * arg: args){
const Integer * x = static_cast<const Integer *>(arg);
sum += x->x;
}
return std::make_unique<Integer>(sum);
}
| 635
| 223
|
//#include<bits/stdc++.h>
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string.h>
#include<algorithm>
#define N 1010
using namespace std;
int n,m;
int a[N][N];
int stk[N],top;
int L[N][N],R[N][N],U[N][N],D[N][N];
int readint()
{
char c;
while((c=getchar())&&!(c>='0' && c<='9'));
int ret= c- 48;
while((c=getchar())&&( c>='0' && c<='9'))
ret = ret * 10 + c-48;
return ret;
}
unsigned int calc(int l,int x,int r)
{
unsigned int d1=r-x+1;
unsigned int d2=x-l+1;
unsigned int ret=d1 * (d1+1) / 2 * d2 + d2* (d2-1)/2 *d1;
return ret;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
a[i][j]=readint();
}
}
for(int i=1;i<=n;i++)
{
top=0;
for(int j=1;j<=m;j++)
{
while(top && a[i][stk[top-1]] > a[i][j])
--top;
if(top==0) L[i][j]=1;
else L[i][j]=stk[top-1]+1;
stk[top++]=j;
}
}
for(int i=1;i<=n;i++)
{
top=0;
for(int j=m;j>=1;--j)
{
while(top && a[i][stk[top-1]] > a[i][j])
--top;
if(top==0) R[i][j]=m;
else R[i][j] = stk[top-1] - 1;
stk[top++] = j;
}
}
for(int i=1;i<=m;i++)
{
top=0;
for(int j=1;j<=n;j++)
{
while(top && a[stk[top-1]][i] < a[j][i])
--top;
if(top==0) U[j][i]=1;
else U[j][i] = stk[top-1]+1;
stk[top++]=j;
}
}
for(int i=1;i<=m;i++)
{
top=0;
for(int j=n;j>=1;--j)
{
while(top && a[stk[top-1]][i] < a[j][i])
--top;
if(top==0) D[j][i]=n;
else D[j][i] = stk[top-1]-1;
stk[top++]=j;
}
}
unsigned int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
ans += (unsigned int)a[i][j]*calc(L[i][j],j,R[i][j])*calc(U[i][j],i,D[i][j]);
}
}
printf("%u\n",ans);
}
return 0;
}
| 1,915
| 1,150
|
/**
* Copyright (C) 2022 Elisha Riedlinger
*
* 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.
*/
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "Patches.h"
#include "Common\Utils.h"
#include "Logging\Logging.h"
typedef int(__cdecl *oTextToGameAsmProc)(unsigned __int16* a1, unsigned __int16 a2);
// Forward declarations
DWORD GetDiskSpace();
// Variables
bool DiskSizeSet = false;
char szNewFreeSpaceString[MAX_PATH] = { '\0' };
// Variables for ASM
void *jmpSkipDisk;
void *jmpNewSaveReturnAddr;
void *jmpHardDriveReturnAddr;
void *jmpSkipDisplay;
void *jmpDisplayReturnAddr;
void *jmpRemoveKBAddr;
// ASM function to update 2TB disk limit
__declspec(naked) void __stdcall HardDriveASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x08 // Require at least 8KBs of disk space
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
ja near EnoughDiskSpace
jmp jmpSkipDisk
EnoughDiskSpace:
jmp jmpHardDriveReturnAddr
}
}
// ASM function for new save
__declspec(naked) void __stdcall NewSaveASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x20 // Require at least 32KBs of disk space for new save
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
ja near EnoughDiskSpace
jmp HardDriveASM
EnoughDiskSpace:
jmp jmpNewSaveReturnAddr
}
}
// ASM function to update hard disk display
__declspec(naked) void __stdcall DisplayASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x3FFFFFFF
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
jb near SmallDiskSpace
jmp jmpSkipDisplay
SmallDiskSpace:
cmp esi, 0x3B9AC9FF
jmp jmpDisplayReturnAddr
}
}
// ASM function to update 2TB disk limit
__declspec(naked) void __stdcall oTextToGameAsm()
{
__asm
{
mov eax, dword ptr ss : [esp + 4]
test eax, eax
jmp jmpRemoveKBAddr
}
}
oTextToGameAsmProc oTextToGame = (oTextToGameAsmProc)oTextToGameAsm;
// Remove "KB" text
int __cdecl TextToGame(unsigned __int16* a1, unsigned __int16 a2)
{
int TTG = oTextToGame(a1, a2);
if (a2 == 147)
{
BYTE RemoveKBPatch[2] = { 0x00, 0x00 };
UpdateMemoryAddress((BYTE*)(TTG + 0x11), RemoveKBPatch, 2);
}
return TTG;
}
// Get amount of free disk space in KBs, greater than 0x7FFFFFFF will simply return 0x7FFFFFFF
DWORD GetDiskSpace()
{
static wchar_t DirectoryName[MAX_PATH] = { '\0' };
static bool GetFolder = true;
if (GetFolder)
{
if (GetSH2FolderPath(DirectoryName, MAX_PATH) && wcsrchr(DirectoryName, '\\'))
{
wcscpy_s(wcsrchr(DirectoryName, '\\'), MAX_PATH - wcslen(DirectoryName), L"\0");
}
GetFolder = false;
}
ULARGE_INTEGER FreeBytesAvailableToCaller = { NULL };
if (!GetDiskFreeSpaceEx(DirectoryName, &FreeBytesAvailableToCaller, nullptr, nullptr))
{
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Error: failed to get available disk space!");
DiskSizeSet = false;
return NULL;
}
DiskSizeSet = true;
if (FreeBytesAvailableToCaller.QuadPart < 0xF4240)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%f KB", (double)FreeBytesAvailableToCaller.QuadPart);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 < 0xF4240)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%f MB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 < 0x3B9ACA00)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%.1f GB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f / 1024.0f);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 >= 0x3B9ACA00)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%.2f TB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f / 1024.0f / 1024.0f);
}
ULONGLONG FreeSpace = FreeBytesAvailableToCaller.QuadPart / 1024;
if (FreeSpace > 0x7FFFFFFF)
{
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Available disk space larger than 2TBs: " << FreeSpace);
return 0x7FFFFFFF; // Largest unsigned number
}
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Available disk space smaller than 2TBs: " << FreeSpace);
return (DWORD)(FreeSpace);
}
// sprintf replacement for printing diskspace
int PrintFreeDiskSpace(char* Buffer, const char* a1, ...)
{
if (Buffer == nullptr || a1 == nullptr)
{
return sprintf(Buffer, a1);
}
char FullMessageBufferReturn[MAX_PATH] = { 0 };
va_list vaReturn;
va_start(vaReturn, a1);
_vsnprintf_s(FullMessageBufferReturn, MAX_PATH, _TRUNCATE, a1, vaReturn);
va_end(vaReturn);
if (DiskSizeSet)
{
return sprintf(Buffer, szNewFreeSpaceString);
}
else
{
strcat_s(FullMessageBufferReturn, MAX_PATH, " KB");
return sprintf(Buffer, FullMessageBufferReturn);
}
}
// Patch SH2 code to Fix 2TB disk limit
void Patch2TBHardDrive()
{
// 2TB disk check fix
constexpr BYTE HardDriveSearchBytes[]{ 0x75, 0x08, 0x5F, 0xB8, 0x02, 0x00, 0x00, 0x00, 0x5E, 0xC3, 0x84, 0xDB, 0x75, 0x14, 0x83, 0xFE, 0x20, 0x7C, 0x0F };
DWORD HardDriveAddr = SearchAndGetAddresses(0x0044B86E, 0x0044BA0E, 0x0044BA0E, HardDriveSearchBytes, sizeof(HardDriveSearchBytes), 0x22);
// Checking address pointer
if (!HardDriveAddr)
{
Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!";
return;
}
jmpSkipDisk = (void*)(HardDriveAddr + 0x1A);
jmpHardDriveReturnAddr = (void*)(HardDriveAddr + 0x05);
jmpNewSaveReturnAddr = (void*)(HardDriveAddr - 0x0F);
// Disk display fix
constexpr BYTE DisplaySearchBytes[]{ 0x8B, 0xF0, 0x83, 0xC4, 0x04, 0x85, 0xF6, 0x7D, 0x02, 0x33, 0xF6, 0x6A, 0x00 };
DWORD DisplayFix = SearchAndGetAddresses(0x0044FB54, 0x0044FDB4, 0x0044FDB4, DisplaySearchBytes, sizeof(DisplaySearchBytes), 0x1A);
constexpr BYTE RemoveKBSearchBytes[]{ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x74, 0x16, 0x66, 0x8B, 0x4C, 0x24, 0x08 };
DWORD RemoveKBAddr = SearchAndGetAddresses(0x0047EC60, 0x0047EF00, 0x0047F110, RemoveKBSearchBytes, sizeof(RemoveKBSearchBytes), 0x0);
// Checking address pointer
if (!DisplayFix || !RemoveKBAddr)
{
Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!";
return;
}
jmpSkipDisplay = (void*)(DisplayFix + 0x08);
jmpDisplayReturnAddr = (void*)(DisplayFix + 0x06);
jmpRemoveKBAddr = (void*)(RemoveKBAddr + 6);
DWORD sprintfAddr = DisplayFix + 0x42;
// Update SH2 code
Logging::Log() << "Setting 2TB hard disk Fix...";
WriteJMPtoMemory((BYTE*)(HardDriveAddr - 0x14), *NewSaveASM, 5);
WriteJMPtoMemory((BYTE*)HardDriveAddr, *HardDriveASM, 5);
WriteJMPtoMemory((BYTE*)DisplayFix, *DisplayASM, 6);
WriteCalltoMemory((BYTE*)sprintfAddr, *PrintFreeDiskSpace, 6);
WriteJMPtoMemory((BYTE*)RemoveKBAddr, *TextToGame, 6);
}
| 7,592
| 3,331
|
/*
* This file belongs to the Galois project, a C++ library for exploiting
* parallelism. The code is being released under the terms of the 3-Clause BSD
* License (a copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#include "galois/SharedMemSys.h"
#include "galois/CommBackend.h"
#include "galois/Logging.h"
#include "galois/Statistics.h"
#include "galois/substrate/SharedMem.h"
#include "tsuba/FileStorage.h"
#include "tsuba/tsuba.h"
namespace {
galois::NullCommBackend comm_backend;
} // namespace
struct galois::SharedMemSys::Impl {
galois::substrate::SharedMem shared_mem;
galois::StatManager stat_manager;
};
galois::SharedMemSys::SharedMemSys() : impl_(std::make_unique<Impl>()) {
if (auto init_good = tsuba::Init(&comm_backend); !init_good) {
GALOIS_LOG_FATAL("tsuba::Init: {}", init_good.error());
}
galois::internal::setSysStatManager(&impl_->stat_manager);
}
galois::SharedMemSys::~SharedMemSys() {
galois::PrintStats();
galois::internal::setSysStatManager(nullptr);
if (auto fini_good = tsuba::Fini(); !fini_good) {
GALOIS_LOG_ERROR("tsuba::Fini: {}", fini_good.error());
}
}
| 2,043
| 734
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/teslamaxcompute/model/ListUserQuotasResult.h>
#include <json/json.h>
using namespace AlibabaCloud::TeslaMaxCompute;
using namespace AlibabaCloud::TeslaMaxCompute::Model;
ListUserQuotasResult::ListUserQuotasResult() :
ServiceResult()
{}
ListUserQuotasResult::ListUserQuotasResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListUserQuotasResult::~ListUserQuotasResult()
{}
void ListUserQuotasResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allDetail = value["Detail"]["Quotas"];
for (auto value : allDetail)
{
Data::Quotas quotasObject;
if(!value["Quotaid"].isNull())
quotasObject.quotaid = std::stol(value["Quotaid"].asString());
if(!value["Cluster"].isNull())
quotasObject.cluster = value["Cluster"].asString();
if(!value["Region"].isNull())
quotasObject.region = value["Region"].asString();
if(!value["Name"].isNull())
quotasObject.name = value["Name"].asString();
if(!value["Parentid"].isNull())
quotasObject.parentid = std::stol(value["Parentid"].asString());
if(!value["Nick"].isNull())
quotasObject.nick = value["Nick"].asString();
data_.detail.push_back(quotasObject);
}
auto errorNode = dataNode["Error"];
if(!errorNode["Code"].isNull())
data_.error.code = errorNode["Code"].asString();
if(!errorNode["Message"].isNull())
data_.error.message = errorNode["Message"].asString();
if(!errorNode["Timestamp"].isNull())
data_.error.timestamp = errorNode["Timestamp"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["Code"].isNull())
code_ = std::stoi(value["Code"].asString());
}
std::string ListUserQuotasResult::getMessage()const
{
return message_;
}
ListUserQuotasResult::Data ListUserQuotasResult::getData()const
{
return data_;
}
int ListUserQuotasResult::getCode()const
{
return code_;
}
| 2,637
| 895
|
#include "stdafx.h"
#include "InputSystem.h"
InputSystem::ResizeEventData InputSystem::resizeEvent;
InputSystem::KeyTypedData InputSystem::keyTypedEvent;
bool InputSystem::addCubeButton;
bool InputSystem::removeCubeButton;
void InputSystem::Initialize(void)
{
// Setup all the event handlers to indicate that nothing occurred.
resizeEvent.resizeEvent = false;
keyTypedEvent.charEvent = false;
addCubeButton = false;
removeCubeButton = false;
}
void InputSystem::KeyTyped(GLFWwindow *pWindow, unsigned int character)
{
keyTypedEvent.newChar = static_cast<char>(character);
keyTypedEvent.charEvent = true;
}
bool InputSystem::KeyTypedEvent(char& character)
{
if (keyTypedEvent.charEvent)
{
character = keyTypedEvent.newChar;
keyTypedEvent.charEvent = false;
return true;
}
return false;
}
void InputSystem::KeyEvent(GLFWwindow *pWindow, int key, int scancode, int action, int mods)
{
switch (key)
{
case GLFW_KEY_A:
if (action == GLFW_PRESS)
{
addCubeButton = true;
}
else if (action == GLFW_RELEASE)
{
addCubeButton = false;
}
break;
case GLFW_KEY_R:
if (action == GLFW_PRESS)
{
removeCubeButton = true;
}
else if (action == GLFW_RELEASE)
{
removeCubeButton = false;
}
break;
}
}
void InputSystem::MouseButtonEvent(GLFWwindow *pWindow, int button, int action, int mods)
{
}
void InputSystem::ScrollEvent(GLFWwindow *pWindow, double xDelta, double yDelta)
{
}
void InputSystem::CursorTravel(GLFWwindow *pWindow, int action)
{
}
void InputSystem::CursorMove(GLFWwindow *pWindow, double xNew, double yNew)
{
}
// Simple resize handling.
void InputSystem::Resize(GLFWwindow *pWindow, int widthNew, int heightHew)
{
resizeEvent.newWidth = widthNew;
resizeEvent.newHeight = heightHew;
resizeEvent.resizeEvent = true;
}
bool InputSystem::ResizeEvent(int& width, int& height)
{
if (resizeEvent.resizeEvent)
{
width = resizeEvent.newWidth;
height = resizeEvent.newHeight;
resizeEvent.resizeEvent = false;
return true;
}
return false;
}
// Very simple error callbacks
void InputSystem::ErrorCallback(int errCode, const char *pError)
{
std::cout << "GLFW error " << errCode << ": " << pError << std::endl;
}
void APIENTRY InputSystem::GLCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *pMessage, void *userParam)
{
std::cout << "OpenGL debug error (" << source << ", " << type << ", " << id << ", " << severity << ", " << length << "): " << pMessage << std::endl;
}
| 2,727
| 870
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/events/keycodes/dom/dom_keyboard_layout_map_base.h"
#include <cstdint>
#include <memory>
#include <string>
#include "base/logging.h"
#include "ui/events/keycodes/dom/dom_key.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout_manager.h"
namespace ui {
DomKeyboardLayoutMapBase::DomKeyboardLayoutMapBase() = default;
DomKeyboardLayoutMapBase::~DomKeyboardLayoutMapBase() = default;
base::flat_map<std::string, std::string> DomKeyboardLayoutMapBase::Generate() {
uint32_t keyboard_layout_count = GetKeyboardLayoutCount();
if (!keyboard_layout_count)
return {};
std::unique_ptr<ui::DomKeyboardLayoutManager> keyboard_layout_manager =
std::make_unique<ui::DomKeyboardLayoutManager>();
for (size_t i = 0; i < keyboard_layout_count; i++) {
DomKeyboardLayout* const dom_keyboard_layout =
keyboard_layout_manager->GetLayout(i);
PopulateLayout(i, dom_keyboard_layout);
if (dom_keyboard_layout->IsAsciiCapable())
return dom_keyboard_layout->GetMap();
}
return keyboard_layout_manager->GetFirstAsciiCapableLayout()->GetMap();
}
void DomKeyboardLayoutMapBase::PopulateLayout(uint32_t keyboard_layout_index,
ui::DomKeyboardLayout* layout) {
DCHECK(layout);
for (size_t entry = 0; entry < ui::kWritingSystemKeyDomCodeEntries; entry++) {
ui::DomCode dom_code = ui::writing_system_key_domcodes[entry];
ui::DomKey dom_key =
GetDomKeyFromDomCodeForLayout(dom_code, keyboard_layout_index);
if (dom_key == ui::DomKey::NONE)
continue;
uint32_t unicode_value = 0;
if (dom_key.IsCharacter())
unicode_value = dom_key.ToCharacter();
else if (dom_key.IsDeadKey())
unicode_value = dom_key.ToDeadKeyCombiningCharacter();
else if (dom_key == ui::DomKey::ZENKAKU_HANKAKU)
// Placeholder for hankaku/zenkaku string.
unicode_value = kHankakuZenkakuPlaceholder;
if (unicode_value != 0)
layout->AddKeyMapping(dom_code, unicode_value);
}
}
} // namespace ui
| 2,255
| 767
|
#pragma once
#include <azure_entity.h>
#include <cpprest/http_msg.h>
#include <cpprest/json.h>
#include <permissions.hpp>
using namespace web;
using namespace bolt::storage;
class AzureHandler
{
public:
AzureHandler(const http::http_request &request, http::method method);
void InitializeHandlers();
void HandleGet();
void HandlePost();
void HandleDelete();
void HandlePatch();
private:
void insetKeyValuePropery(boltazure::AzureEntity &entity, utility::string_t key, json::value value);
const http::http_request &m_http_request;
http::method m_method;
};
| 568
| 185
|
/******************************************************************************
*
* Project: VSI Virtual File System
* Purpose: Implementation of caching IO layer.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2011, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2011-2014, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "cpl_vsi_virtual.h"
#include <cstddef>
#include <cstring>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <algorithm>
#include <map>
#include <utility>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_vsi.h"
#include "cpl_vsi_virtual.h"
//! @cond Doxygen_Suppress
CPL_CVSID("$Id$")
/************************************************************************/
/* ==================================================================== */
/* VSICacheChunk */
/* ==================================================================== */
/************************************************************************/
class VSICacheChunk
{
public:
VSICacheChunk() :
bDirty(false),
iBlock(0),
poLRUPrev(NULL),
poLRUNext(NULL),
nDataFilled(0),
pabyData(NULL)
{}
virtual ~VSICacheChunk()
{
VSIFree( pabyData );
}
bool Allocate( size_t nChunkSize )
{
CPLAssert( pabyData == NULL );
pabyData = static_cast<GByte *>(VSIMalloc( nChunkSize ));
return (pabyData != NULL);
}
bool bDirty; // TODO(schwehr): Not used? Added in r22564.
vsi_l_offset iBlock;
VSICacheChunk *poLRUPrev;
VSICacheChunk *poLRUNext;
vsi_l_offset nDataFilled;
GByte *pabyData;
};
/************************************************************************/
/* ==================================================================== */
/* VSICachedFile */
/* ==================================================================== */
/************************************************************************/
class VSICachedFile CPL_FINAL : public VSIVirtualHandle
{
public:
VSICachedFile( VSIVirtualHandle *poBaseHandle,
size_t nChunkSize,
size_t nCacheSize );
virtual ~VSICachedFile() { Close(); }
void FlushLRU();
int LoadBlocks( vsi_l_offset nStartBlock, size_t nBlockCount,
void *pBuffer, size_t nBufferSize );
void Demote( VSICacheChunk * );
VSIVirtualHandle *poBase;
vsi_l_offset nOffset;
vsi_l_offset nFileSize;
GUIntBig nCacheUsed;
GUIntBig nCacheMax;
size_t m_nChunkSize;
VSICacheChunk *poLRUStart;
VSICacheChunk *poLRUEnd;
std::map<vsi_l_offset, VSICacheChunk*> oMapOffsetToCache;
bool bEOF;
virtual int Seek( vsi_l_offset nOffset, int nWhence ) override;
virtual vsi_l_offset Tell() override;
virtual size_t Read( void *pBuffer, size_t nSize,
size_t nMemb ) override;
virtual size_t Write( const void *pBuffer, size_t nSize,
size_t nMemb ) override;
virtual int Eof() override;
virtual int Flush() override;
virtual int Close() override;
virtual void *GetNativeFileDescriptor() override
{ return poBase->GetNativeFileDescriptor(); }
};
/************************************************************************/
/* VSICachedFile() */
/************************************************************************/
VSICachedFile::VSICachedFile( VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
size_t nCacheSize ) :
poBase(poBaseHandle),
nOffset(0),
nFileSize(0), // Set below.
nCacheUsed(0),
nCacheMax(nCacheSize),
poLRUStart(NULL),
poLRUEnd(NULL),
bEOF(false)
{
m_nChunkSize = nChunkSize;
if( nCacheSize == 0 )
nCacheMax = CPLScanUIntBig(
CPLGetConfigOption( "VSI_CACHE_SIZE", "25000000" ), 40 );
poBase->Seek( 0, SEEK_END );
nFileSize = poBase->Tell();
}
/************************************************************************/
/* Close() */
/************************************************************************/
int VSICachedFile::Close()
{
for( std::map<vsi_l_offset, VSICacheChunk*>::iterator oIter =
oMapOffsetToCache.begin();
oIter != oMapOffsetToCache.end();
++oIter )
{
delete oIter->second;
}
oMapOffsetToCache.clear();
poLRUStart = NULL;
poLRUEnd = NULL;
nCacheUsed = 0;
if( poBase )
{
poBase->Close();
delete poBase;
poBase = NULL;
}
return 0;
}
/************************************************************************/
/* Seek() */
/************************************************************************/
int VSICachedFile::Seek( vsi_l_offset nReqOffset, int nWhence )
{
bEOF = false;
if( nWhence == SEEK_SET )
{
// Use offset directly.
}
else if( nWhence == SEEK_CUR )
{
nReqOffset += nOffset;
}
else if( nWhence == SEEK_END )
{
nReqOffset += nFileSize;
}
nOffset = nReqOffset;
return 0;
}
/************************************************************************/
/* Tell() */
/************************************************************************/
vsi_l_offset VSICachedFile::Tell()
{
return nOffset;
}
/************************************************************************/
/* FlushLRU() */
/************************************************************************/
void VSICachedFile::FlushLRU()
{
CPLAssert( poLRUStart != NULL );
VSICacheChunk *poBlock = poLRUStart;
CPLAssert( nCacheUsed >= poBlock->nDataFilled );
nCacheUsed -= poBlock->nDataFilled;
poLRUStart = poBlock->poLRUNext;
if( poLRUEnd == poBlock )
poLRUEnd = NULL;
if( poBlock->poLRUNext != NULL )
poBlock->poLRUNext->poLRUPrev = NULL;
CPLAssert( !poBlock->bDirty );
oMapOffsetToCache[poBlock->iBlock] = NULL;
delete poBlock;
}
/************************************************************************/
/* Demote() */
/* */
/* Demote the indicated block to the end of the LRU list. */
/* Potentially integrate the link into the list if it is not */
/* already there. */
/************************************************************************/
void VSICachedFile::Demote( VSICacheChunk *poBlock )
{
// Already at end?
if( poLRUEnd == poBlock )
return;
if( poLRUStart == poBlock )
poLRUStart = poBlock->poLRUNext;
if( poBlock->poLRUPrev != NULL )
poBlock->poLRUPrev->poLRUNext = poBlock->poLRUNext;
if( poBlock->poLRUNext != NULL )
poBlock->poLRUNext->poLRUPrev = poBlock->poLRUPrev;
poBlock->poLRUNext = NULL;
poBlock->poLRUPrev = NULL;
if( poLRUEnd != NULL )
poLRUEnd->poLRUNext = poBlock;
poLRUEnd = poBlock;
if( poLRUStart == NULL )
poLRUStart = poBlock;
}
/************************************************************************/
/* LoadBlocks() */
/* */
/* Load the desired set of blocks. Use pBuffer as a temporary */
/* buffer if it would be helpful. */
/* */
/* RETURNS: TRUE on success; FALSE on failure. */
/************************************************************************/
int VSICachedFile::LoadBlocks( vsi_l_offset nStartBlock, size_t nBlockCount,
void *pBuffer, size_t nBufferSize )
{
if( nBlockCount == 0 )
return TRUE;
/* -------------------------------------------------------------------- */
/* When we want to load only one block, we can directly load it */
/* into the target buffer with no concern about intermediaries. */
/* -------------------------------------------------------------------- */
if( nBlockCount == 1 )
{
poBase->Seek( static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
SEEK_SET );
VSICacheChunk *poBlock = new VSICacheChunk();
if( !poBlock || !poBlock->Allocate( m_nChunkSize ) )
{
delete poBlock;
return FALSE;
}
oMapOffsetToCache[nStartBlock] = poBlock;
poBlock->iBlock = nStartBlock;
poBlock->nDataFilled =
poBase->Read( poBlock->pabyData, 1, m_nChunkSize );
nCacheUsed += poBlock->nDataFilled;
// Merges into the LRU list.
Demote( poBlock );
return TRUE;
}
/* -------------------------------------------------------------------- */
/* If the buffer is quite large but not quite large enough to */
/* hold all the blocks we will take the pain of splitting the */
/* io request in two in order to avoid allocating a large */
/* temporary buffer. */
/* -------------------------------------------------------------------- */
if( nBufferSize > m_nChunkSize * 20
&& nBufferSize < nBlockCount * m_nChunkSize )
{
if( !LoadBlocks( nStartBlock, 2, pBuffer, nBufferSize ) )
return FALSE;
return LoadBlocks( nStartBlock+2, nBlockCount-2, pBuffer, nBufferSize );
}
if( poBase->Seek( static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
SEEK_SET ) != 0 )
return FALSE;
/* -------------------------------------------------------------------- */
/* Do we need to allocate our own buffer? */
/* -------------------------------------------------------------------- */
GByte *pabyWorkBuffer = static_cast<GByte *>(pBuffer);
if( nBufferSize < m_nChunkSize * nBlockCount )
pabyWorkBuffer =
static_cast<GByte *>( CPLMalloc(m_nChunkSize * nBlockCount) );
/* -------------------------------------------------------------------- */
/* Read the whole request into the working buffer. */
/* -------------------------------------------------------------------- */
const size_t nDataRead =
poBase->Read( pabyWorkBuffer, 1, nBlockCount*m_nChunkSize);
if( nBlockCount * m_nChunkSize > nDataRead + m_nChunkSize - 1 )
nBlockCount = (nDataRead + m_nChunkSize - 1) / m_nChunkSize;
for( size_t i = 0; i < nBlockCount; i++ )
{
VSICacheChunk *poBlock = new VSICacheChunk();
if( !poBlock || !poBlock->Allocate( m_nChunkSize ) )
{
delete poBlock;
return FALSE;
}
poBlock->iBlock = nStartBlock + i;
CPLAssert( oMapOffsetToCache[i+nStartBlock] == NULL );
oMapOffsetToCache[i + nStartBlock] = poBlock;
if( nDataRead >= (i+1) * m_nChunkSize )
poBlock->nDataFilled = m_nChunkSize;
else
poBlock->nDataFilled = nDataRead - i*m_nChunkSize;
memcpy( poBlock->pabyData, pabyWorkBuffer + i*m_nChunkSize,
static_cast<size_t>(poBlock->nDataFilled) );
nCacheUsed += poBlock->nDataFilled;
// Merges into the LRU list.
Demote( poBlock );
}
if( pabyWorkBuffer != pBuffer )
CPLFree( pabyWorkBuffer );
return TRUE;
}
/************************************************************************/
/* Read() */
/************************************************************************/
size_t VSICachedFile::Read( void * pBuffer, size_t nSize, size_t nCount )
{
if( nOffset >= nFileSize )
{
bEOF = true;
return 0;
}
/* ==================================================================== */
/* Make sure the cache is loaded for the whole request region. */
/* ==================================================================== */
const vsi_l_offset nStartBlock = nOffset / m_nChunkSize;
const vsi_l_offset nEndBlock =
(nOffset + nSize * nCount - 1) / m_nChunkSize;
for( vsi_l_offset iBlock = nStartBlock; iBlock <= nEndBlock; iBlock++ )
{
if( oMapOffsetToCache[iBlock] == NULL )
{
size_t nBlocksToLoad = 1;
while( iBlock + nBlocksToLoad <= nEndBlock
&& (oMapOffsetToCache[iBlock+nBlocksToLoad] == NULL) )
nBlocksToLoad++;
LoadBlocks( iBlock, nBlocksToLoad, pBuffer, nSize * nCount );
}
}
/* ==================================================================== */
/* Copy data into the target buffer to the extent possible. */
/* ==================================================================== */
size_t nAmountCopied = 0;
while( nAmountCopied < nSize * nCount )
{
const vsi_l_offset iBlock = (nOffset + nAmountCopied) / m_nChunkSize;
VSICacheChunk * poBlock = oMapOffsetToCache[iBlock];
if( poBlock == NULL )
{
// We can reach that point when the amount to read exceeds
// the cache size.
LoadBlocks(iBlock, 1,
static_cast<GByte *>(pBuffer) + nAmountCopied,
std::min(nSize * nCount - nAmountCopied, m_nChunkSize));
poBlock = oMapOffsetToCache[iBlock];
CPLAssert(poBlock != NULL);
}
const vsi_l_offset nStartOffset =
static_cast<vsi_l_offset>(iBlock) * m_nChunkSize;
size_t nThisCopy = static_cast<size_t>(
((nStartOffset + poBlock->nDataFilled)
- nAmountCopied - nOffset));
if( nThisCopy > nSize * nCount - nAmountCopied )
nThisCopy = nSize * nCount - nAmountCopied;
if( nThisCopy == 0 )
break;
memcpy( static_cast<GByte *>(pBuffer) + nAmountCopied,
poBlock->pabyData
+ (nOffset + nAmountCopied) - nStartOffset,
nThisCopy );
nAmountCopied += nThisCopy;
}
nOffset += nAmountCopied;
/* -------------------------------------------------------------------- */
/* Ensure the cache is reduced to our limit. */
/* -------------------------------------------------------------------- */
while( nCacheUsed > nCacheMax )
FlushLRU();
const size_t nRet = nAmountCopied / nSize;
if( nRet != nCount )
bEOF = true;
return nRet;
}
/************************************************************************/
/* Write() */
/************************************************************************/
size_t VSICachedFile::Write( const void * /* pBuffer */,
size_t /*nSize */ ,
size_t /* nCount */ )
{
return 0;
}
/************************************************************************/
/* Eof() */
/************************************************************************/
int VSICachedFile::Eof()
{
return bEOF;
}
/************************************************************************/
/* Flush() */
/************************************************************************/
int VSICachedFile::Flush()
{
return 0;
}
//! @endcond
/************************************************************************/
/* VSICreateCachedFile() */
/************************************************************************/
VSIVirtualHandle *
VSICreateCachedFile( VSIVirtualHandle *poBaseHandle,
size_t nChunkSize, size_t nCacheSize )
{
return new VSICachedFile( poBaseHandle, nChunkSize, nCacheSize );
}
| 17,889
| 5,039
|
#include "envoy/extensions/filters/network/direct_response/v3/config.pb.h"
#include "envoy/extensions/filters/network/local_ratelimit/v3/local_rate_limit.pb.h"
#include "envoy/extensions/filters/network/thrift_proxy/v3/thrift_proxy.pb.h"
#include "extensions/filters/common/ratelimit/ratelimit_impl.h"
#include "extensions/filters/network/common/utility.h"
#include "extensions/filters/network/well_known_names.h"
#include "test/extensions/filters/common/ext_authz/test_common.h"
#include "test/extensions/filters/network/common/fuzz/uber_readfilter.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace {
// Limit the fill_interval in the config of local_ratelimit filter prevent overflow in
// std::chrono::time_point.
static const int SecondsPerDay = 86400;
} // namespace
std::vector<absl::string_view> UberFilterFuzzer::filterNames() {
// These filters have already been covered by this fuzzer.
// Will extend to cover other network filters one by one.
static std::vector<absl::string_view> filter_names;
if (filter_names.empty()) {
const auto factories = Registry::FactoryRegistry<
Server::Configuration::NamedNetworkFilterConfigFactory>::factories();
const std::vector<absl::string_view> supported_filter_names = {
NetworkFilterNames::get().ExtAuthorization, NetworkFilterNames::get().LocalRateLimit,
NetworkFilterNames::get().RedisProxy, NetworkFilterNames::get().ClientSslAuth,
NetworkFilterNames::get().Echo, NetworkFilterNames::get().DirectResponse,
NetworkFilterNames::get().DubboProxy, NetworkFilterNames::get().SniCluster,
// A dedicated http_connection_manager fuzzer can be found in
// test/common/http/conn_manager_impl_fuzz_test.cc
NetworkFilterNames::get().HttpConnectionManager, NetworkFilterNames::get().ThriftProxy,
NetworkFilterNames::get().ZooKeeperProxy, NetworkFilterNames::get().SniDynamicForwardProxy,
NetworkFilterNames::get().KafkaBroker, NetworkFilterNames::get().RocketmqProxy,
NetworkFilterNames::get().RateLimit, NetworkFilterNames::get().Rbac,
NetworkFilterNames::get().MongoProxy, NetworkFilterNames::get().MySQLProxy
// TODO(jianwendong): add "NetworkFilterNames::get().Postgres" after it supports untrusted
// data.
// TODO(jianwendong): add fuzz test for "NetworkFilterNames::get().TcpProxy".
};
// Check whether each filter is loaded into Envoy.
// Some customers build Envoy without some filters. When they run fuzzing, the use of a filter
// that does not exist will cause fatal errors.
for (auto& filter_name : supported_filter_names) {
if (factories.contains(filter_name)) {
filter_names.push_back(filter_name);
} else {
ENVOY_LOG_MISC(debug, "Filter name not found in the factory: {}", filter_name);
}
}
}
return filter_names;
}
void UberFilterFuzzer::perFilterSetup(const std::string& filter_name) {
// Set up response for ext_authz filter
if (filter_name == NetworkFilterNames::get().ExtAuthorization) {
async_client_factory_ = std::make_unique<Grpc::MockAsyncClientFactory>();
async_client_ = std::make_unique<Grpc::MockAsyncClient>();
// TODO(jianwendong): consider testing on different kinds of responses.
ON_CALL(*async_client_, sendRaw(_, _, _, _, _, _))
.WillByDefault(testing::WithArgs<3>(Invoke([&](Grpc::RawAsyncRequestCallbacks& callbacks) {
Filters::Common::ExtAuthz::GrpcClientImpl* grpc_client_impl =
dynamic_cast<Filters::Common::ExtAuthz::GrpcClientImpl*>(&callbacks);
const std::string empty_body{};
const auto expected_headers =
Filters::Common::ExtAuthz::TestCommon::makeHeaderValueOption({});
auto check_response = Filters::Common::ExtAuthz::TestCommon::makeCheckResponse(
Grpc::Status::WellKnownGrpcStatus::Ok, envoy::type::v3::OK, empty_body,
expected_headers);
// Give response to the grpc_client by calling onSuccess().
grpc_client_impl->onSuccess(std::move(check_response), span_);
return async_request_.get();
})));
EXPECT_CALL(*async_client_factory_, create()).WillOnce(Invoke([&] {
return std::move(async_client_);
}));
EXPECT_CALL(factory_context_.cluster_manager_.async_client_manager_,
factoryForGrpcService(_, _, _))
.WillOnce(Invoke([&](const envoy::config::core::v3::GrpcService&, Stats::Scope&, bool) {
return std::move(async_client_factory_);
}));
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress(
pipe_addr_);
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress(
pipe_addr_);
} else if (filter_name == NetworkFilterNames::get().HttpConnectionManager) {
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress(
pipe_addr_);
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress(
pipe_addr_);
} else if (filter_name == NetworkFilterNames::get().RateLimit) {
async_client_factory_ = std::make_unique<Grpc::MockAsyncClientFactory>();
async_client_ = std::make_unique<Grpc::MockAsyncClient>();
// TODO(jianwendong): consider testing on different kinds of responses.
ON_CALL(*async_client_, sendRaw(_, _, _, _, _, _))
.WillByDefault(testing::WithArgs<3>(Invoke([&](Grpc::RawAsyncRequestCallbacks& callbacks) {
Filters::Common::RateLimit::GrpcClientImpl* grpc_client_impl =
dynamic_cast<Filters::Common::RateLimit::GrpcClientImpl*>(&callbacks);
// Response OK
auto response = std::make_unique<envoy::service::ratelimit::v3::RateLimitResponse>();
// Give response to the grpc_client by calling onSuccess().
grpc_client_impl->onSuccess(std::move(response), span_);
return async_request_.get();
})));
EXPECT_CALL(*async_client_factory_, create()).WillOnce(Invoke([&] {
return std::move(async_client_);
}));
EXPECT_CALL(factory_context_.cluster_manager_.async_client_manager_,
factoryForGrpcService(_, _, _))
.WillOnce(Invoke([&](const envoy::config::core::v3::GrpcService&, Stats::Scope&, bool) {
return std::move(async_client_factory_);
}));
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress(
pipe_addr_);
read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress(
pipe_addr_);
}
}
void UberFilterFuzzer::checkInvalidInputForFuzzer(const std::string& filter_name,
Protobuf::Message* config_message) {
// System calls such as reading files are prohibited in this fuzzer. Some inputs that crash the
// mock/fake objects are also prohibited. We could also avoid fuzzing some unfinished features by
// checking them here. For now there are only three filters {DirectResponse, LocalRateLimit,
// HttpConnectionManager} on which we have constraints.
const std::string name = Extensions::NetworkFilters::Common::FilterNameUtil::canonicalFilterName(
std::string(filter_name));
if (filter_name == NetworkFilterNames::get().DirectResponse) {
envoy::extensions::filters::network::direct_response::v3::Config& config =
dynamic_cast<envoy::extensions::filters::network::direct_response::v3::Config&>(
*config_message);
if (config.response().specifier_case() ==
envoy::config::core::v3::DataSource::SpecifierCase::kFilename) {
throw EnvoyException(
absl::StrCat("direct_response trying to open a file. Config:\n{}", config.DebugString()));
}
} else if (filter_name == NetworkFilterNames::get().LocalRateLimit) {
envoy::extensions::filters::network::local_ratelimit::v3::LocalRateLimit& config =
dynamic_cast<envoy::extensions::filters::network::local_ratelimit::v3::LocalRateLimit&>(
*config_message);
if (config.token_bucket().fill_interval().seconds() > SecondsPerDay) {
// Too large fill_interval may cause "c++/v1/chrono" overflow when simulated_time_system_ is
// converting it to a smaller unit. Constraining fill_interval to no greater than one day is
// reasonable.
throw EnvoyException(
absl::StrCat("local_ratelimit trying to set a large fill_interval. Config:\n{}",
config.DebugString()));
}
} else if (filter_name == NetworkFilterNames::get().HttpConnectionManager) {
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
config = dynamic_cast<envoy::extensions::filters::network::http_connection_manager::v3::
HttpConnectionManager&>(*config_message);
if (config.codec_type() == envoy::extensions::filters::network::http_connection_manager::v3::
HttpConnectionManager::HTTP3) {
// Quiche is still in progress and http_conn_manager has a dedicated fuzzer.
// So we won't fuzz it here with complex mocks.
throw EnvoyException(absl::StrCat(
"http_conn_manager trying to use Quiche which we won't fuzz here. Config:\n{}",
config.DebugString()));
}
}
}
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| 9,535
| 2,733
|
// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "testutil/desc-tbl-builder.h"
#include "util/bit-util.h"
#include "runtime/descriptors.h"
#include "common/names.h"
namespace impala {
DescriptorTblBuilder::DescriptorTblBuilder(ObjectPool* obj_pool) : obj_pool_(obj_pool) {
}
TupleDescBuilder& DescriptorTblBuilder::DeclareTuple() {
TupleDescBuilder* tuple_builder = obj_pool_->Add(new TupleDescBuilder());
tuples_descs_.push_back(tuple_builder);
return *tuple_builder;
}
// item_id of -1 indicates no itemTupleId
static TSlotDescriptor MakeSlotDescriptor(int id, int parent_id, const ColumnType& type,
int slot_idx, int byte_offset, int item_id) {
int null_byte = slot_idx / 8;
int null_bit = slot_idx % 8;
TSlotDescriptor slot_desc;
slot_desc.__set_id(id);
slot_desc.__set_parent(parent_id);
slot_desc.__set_slotType(type.ToThrift());
// For now no tests depend on the materialized path being populated correctly.
slot_desc.__set_materializedPath(vector<int>());
slot_desc.__set_byteOffset(byte_offset);
slot_desc.__set_nullIndicatorByte(null_byte);
slot_desc.__set_nullIndicatorBit(null_bit);
slot_desc.__set_slotIdx(slot_idx);
slot_desc.__set_isMaterialized(true);
if (item_id != -1) slot_desc.__set_itemTupleId(item_id);
return slot_desc;
}
static TTupleDescriptor MakeTupleDescriptor(int id, int byte_size, int num_null_bytes) {
TTupleDescriptor tuple_desc;
tuple_desc.__set_id(id);
tuple_desc.__set_byteSize(byte_size);
tuple_desc.__set_numNullBytes(num_null_bytes);
return tuple_desc;
}
DescriptorTbl* DescriptorTblBuilder::Build() {
DescriptorTbl* desc_tbl;
TDescriptorTable thrift_desc_tbl;
int tuple_id = 0;
int slot_id = 0;
for (int i = 0; i < tuples_descs_.size(); ++i) {
BuildTuple(tuples_descs_[i]->slot_types(), &thrift_desc_tbl, &tuple_id, &slot_id);
}
Status status = DescriptorTbl::Create(obj_pool_, thrift_desc_tbl, &desc_tbl);
DCHECK(status.ok());
return desc_tbl;
}
TTupleDescriptor DescriptorTblBuilder::BuildTuple(
const vector<ColumnType>& slot_types, TDescriptorTable* thrift_desc_tbl,
int* next_tuple_id, int* slot_id) {
// We never materialize struct slots (there's no in-memory representation of structs,
// instead the materialized fields appear directly in the tuple), but array types can
// still have a struct item type. In this case, the array item tuple contains the
// "inlined" struct fields.
if (slot_types.size() == 1 && slot_types[0].type == TYPE_STRUCT) {
return BuildTuple(slot_types[0].children, thrift_desc_tbl, next_tuple_id, slot_id);
}
int num_null_bytes = BitUtil::Ceil(slot_types.size(), 8);
int byte_offset = num_null_bytes;
int tuple_id = *next_tuple_id;
++(*next_tuple_id);
for (int i = 0; i < slot_types.size(); ++i) {
DCHECK_NE(slot_types[i].type, TYPE_STRUCT);
int item_id = -1;
if (slot_types[i].IsCollectionType()) {
TTupleDescriptor item_desc =
BuildTuple(slot_types[i].children, thrift_desc_tbl, next_tuple_id, slot_id);
item_id = item_desc.id;
}
thrift_desc_tbl->slotDescriptors.push_back(
MakeSlotDescriptor(*slot_id, tuple_id, slot_types[i], i, byte_offset, item_id));
byte_offset += slot_types[i].GetSlotSize();
++(*slot_id);
}
TTupleDescriptor result = MakeTupleDescriptor(tuple_id, byte_offset, num_null_bytes);
thrift_desc_tbl->tupleDescriptors.push_back(result);
return result;
}
}
| 3,984
| 1,409
|
////////////////////////////////////////////////////////////////////////
// $Id: ret_far.cc,v 1.20 2008/06/13 08:02:22 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_X86_64==0
// Make life easier merging cpu64 & cpu code.
#define RIP EIP
#define RSP ESP
#endif
void BX_CPP_AttrRegparmN(2)
BX_CPU_C::return_protected(bxInstruction_c *i, Bit16u pop_bytes)
{
Bit16u raw_cs_selector, raw_ss_selector;
bx_selector_t cs_selector, ss_selector;
bx_descriptor_t cs_descriptor, ss_descriptor;
Bit32u stack_param_offset;
bx_address return_RIP, return_RSP, temp_RSP;
Bit32u dword1, dword2;
/* + 6+N*2: SS | +12+N*4: SS | +24+N*8 SS */
/* + 4+N*2: SP | + 8+N*4: ESP | +16+N*8 RSP */
/* parm N | + parm N | + parm N */
/* parm 3 | + parm 3 | + parm 3 */
/* parm 2 | + parm 2 | + parm 2 */
/* + 4: parm 1 | + 8: parm 1 | +16: parm 1 */
/* + 2: CS | + 4: CS | + 8: CS */
/* + 0: IP | + 0: EIP | + 0: RIP */
#if BX_SUPPORT_X86_64
if (StackAddrSize64()) temp_RSP = RSP;
else
#endif
{
if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b) temp_RSP = ESP;
else temp_RSP = SP;
}
#if BX_SUPPORT_X86_64
if (i->os64L()) {
raw_cs_selector = (Bit16u) read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP + 8);
return_RIP = read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 16;
}
else
#endif
if (i->os32L()) {
raw_cs_selector = (Bit16u) read_virtual_dword(BX_SEG_REG_SS, temp_RSP + 4);
return_RIP = read_virtual_dword(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 8;
}
else {
raw_cs_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 2);
return_RIP = read_virtual_word(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 4;
}
// selector must be non-null else #GP(0)
if ((raw_cs_selector & 0xfffc) == 0) {
BX_ERROR(("return_protected: CS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
parse_selector(raw_cs_selector, &cs_selector);
// selector index must be within its descriptor table limits,
// else #GP(selector)
fetch_raw_descriptor(&cs_selector, &dword1, &dword2, BX_GP_EXCEPTION);
// descriptor AR byte must indicate code segment, else #GP(selector)
parse_descriptor(dword1, dword2, &cs_descriptor);
// return selector RPL must be >= CPL, else #GP(return selector)
if (cs_selector.rpl < CPL) {
BX_ERROR(("return_protected: CS.rpl < CPL"));
exception(BX_GP_EXCEPTION, raw_cs_selector & 0xfffc, 0);
}
// check code-segment descriptor
check_cs(&cs_descriptor, raw_cs_selector, 0, cs_selector.rpl);
// if return selector RPL == CPL then
// RETURN TO SAME PRIVILEGE LEVEL
if (cs_selector.rpl == CPL)
{
BX_DEBUG(("return_protected: return to SAME PRIVILEGE LEVEL"));
branch_far64(&cs_selector, &cs_descriptor, return_RIP, CPL);
#if BX_SUPPORT_X86_64
if (StackAddrSize64())
RSP += stack_param_offset + pop_bytes;
else
#endif
{
if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b)
RSP = ESP + stack_param_offset + pop_bytes;
else
SP += stack_param_offset + pop_bytes;
}
return;
}
/* RETURN TO OUTER PRIVILEGE LEVEL */
else {
/* + 6+N*2: SS | +12+N*4: SS | +24+N*8 SS */
/* + 4+N*2: SP | + 8+N*4: ESP | +16+N*8 RSP */
/* parm N | + parm N | + parm N */
/* parm 3 | + parm 3 | + parm 3 */
/* parm 2 | + parm 2 | + parm 2 */
/* + 4: parm 1 | + 8: parm 1 | +16: parm 1 */
/* + 2: CS | + 4: CS | + 8: CS */
/* + 0: IP | + 0: EIP | + 0: RIP */
BX_DEBUG(("return_protected: return to OUTER PRIVILEGE LEVEL"));
#if BX_SUPPORT_X86_64
if (i->os64L()) {
raw_ss_selector = read_virtual_word_64(BX_SEG_REG_SS, temp_RSP + 24 + pop_bytes);
return_RSP = read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP + 16 + pop_bytes);
}
else
#endif
if (i->os32L()) {
raw_ss_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 12 + pop_bytes);
return_RSP = read_virtual_dword(BX_SEG_REG_SS, temp_RSP + 8 + pop_bytes);
}
else {
raw_ss_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 6 + pop_bytes);
return_RSP = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 4 + pop_bytes);
}
/* selector index must be within its descriptor table limits,
* else #GP(selector) */
parse_selector(raw_ss_selector, &ss_selector);
if ((raw_ss_selector & 0xfffc) == 0) {
if (long_mode()) {
if (! IS_LONG64_SEGMENT(cs_descriptor) || (cs_selector.rpl == 3)) {
BX_ERROR(("return_protected: SS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
}
else // not in long or compatibility mode
{
BX_ERROR(("return_protected: SS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
}
fetch_raw_descriptor(&ss_selector, &dword1, &dword2, BX_GP_EXCEPTION);
parse_descriptor(dword1, dword2, &ss_descriptor);
/* selector RPL must = RPL of the return CS selector,
* else #GP(selector) */
if (ss_selector.rpl != cs_selector.rpl) {
BX_ERROR(("return_protected: ss.rpl != cs.rpl"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* descriptor AR byte must indicate a writable data segment,
* else #GP(selector) */
if (ss_descriptor.valid==0 || ss_descriptor.segment==0 ||
IS_CODE_SEGMENT(ss_descriptor.type) ||
!IS_DATA_SEGMENT_WRITEABLE(ss_descriptor.type))
{
BX_ERROR(("return_protected: SS.AR byte not writable data"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* descriptor dpl must = RPL of the return CS selector,
* else #GP(selector) */
if (ss_descriptor.dpl != cs_selector.rpl) {
BX_ERROR(("return_protected: SS.dpl != cs.rpl"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* segment must be present else #SS(selector) */
if (! IS_PRESENT(ss_descriptor)) {
BX_ERROR(("return_protected: ss.present == 0"));
exception(BX_SS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
branch_far64(&cs_selector, &cs_descriptor, return_RIP, cs_selector.rpl);
/* load SS:SP from stack */
/* load SS-cache with return SS descriptor */
load_ss(&ss_selector, &ss_descriptor, cs_selector.rpl);
#if BX_SUPPORT_X86_64
if (StackAddrSize64())
RSP = return_RSP + pop_bytes;
else
#endif
if (ss_descriptor.u.segment.d_b)
RSP = (Bit32u) return_RSP + pop_bytes;
else
SP = (Bit16u) return_RSP + pop_bytes;
/* check ES, DS, FS, GS for validity */
validate_seg_regs();
}
}
| 8,054
| 3,230
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "chrome/common/extensions/manifest_tests/extension_manifest_test.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/value_builder.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace errors = manifest_errors;
namespace {
class BrowserActionManifestTest : public ExtensionManifestTest {
};
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_NoDefaultIcons) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "No default properties")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_title", "Title")))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
EXPECT_TRUE(browser_action_info->default_icon.empty());
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_StringDefaultIcon) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "String default icon")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_icon", "icon.png")))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
ASSERT_FALSE(browser_action_info->default_icon.empty());
const ExtensionIconSet& icons = browser_action_info->default_icon;
EXPECT_EQ(1u, icons.map().size());
EXPECT_EQ("icon.png", icons.Get(38, ExtensionIconSet::MATCH_EXACTLY));
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_DictDefaultIcon) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Dictionary default icon")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_icon", DictionaryBuilder()
.Set("19", "icon19.png")
.Set("24", "icon24.png") // Should be ignored.
.Set("38", "icon38.png"))))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
ASSERT_FALSE(browser_action_info->default_icon.empty());
const ExtensionIconSet& icons = browser_action_info->default_icon;
// 24px icon should be ignored.
EXPECT_EQ(2u, icons.map().size());
EXPECT_EQ("icon19.png", icons.Get(19, ExtensionIconSet::MATCH_EXACTLY));
EXPECT_EQ("icon38.png", icons.Get(38, ExtensionIconSet::MATCH_EXACTLY));
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_InvalidDefaultIcon) {
scoped_ptr<base::DictionaryValue> manifest_value = DictionaryBuilder()
.Set("name", "Invalid default icon").Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action",
DictionaryBuilder().Set(
"default_icon",
DictionaryBuilder().Set("19", std::string()) // Invalid value.
.Set("24", "icon24.png").Set("38", "icon38.png"))).Build();
base::string16 error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidIconPath, "19");
LoadAndExpectError(Manifest(manifest_value.get(), "Invalid default icon"),
errors::kInvalidIconPath);
}
} // namespace
} // namespace extensions
| 4,326
| 1,316
|
// Ordered slots hello world example for Boost.Signals2
// Copyright Douglas Gregor 2001-2004.
// Copyright Frank Mori Hess 2009.
//
// Use, modification and
// distribution is 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)
// For more information, see http://www.boost.org
#include <iostream>
#include <boost/signals2/signal.hpp>
struct Hello
{
void operator()() const
{
std::cout << "Hello";
}
};
struct World
{
void operator()() const
{
std::cout << ", World!" << std::endl;
}
};
//[ good_morning_def_code_snippet
struct GoodMorning
{
void operator()() const
{
std::cout << "... and good morning!" << std::endl;
}
};
//]
int main()
{
//[ hello_world_ordered_code_snippet
boost::signals2::signal<void ()> sig;
sig.connect(1, World()); // connect with group 1
sig.connect(0, Hello()); // connect with group 0
//]
//[ hello_world_ordered_invoke_code_snippet
// by default slots are connected at the end of the slot list
sig.connect(GoodMorning());
// slots are invoked this order:
// 1) ungrouped slots connected with boost::signals2::at_front
// 2) grouped slots according to ordering of their groups
// 3) ungrouped slots connected with boost::signals2::at_back
sig();
//]
return 0;
}
| 1,350
| 478
|
/* Copyright (c) Günter Woigk 1994 - 2021
mailto:kio@little-bat.de
This file is free software
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.
Permission to use, copy, modify, distribute, and sell this software and
its documentation for any purpose is hereby granted without fee, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of the copyright holder not be used
in advertising or publicity pertaining to distribution of the software
without specific, written prior permission. The copyright holder makes no
representations about the suitability of this software for any purpose.
It is provided "as is" without express or implied warranty.
THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
2002-01-20 kio port to unix started
2002-01-28 kio 3.0.0 released
2014-05-21 kio work on 4.0.0 started
4.1.0 2017: included Einar Saukas' ZX7 "optimal" LZ77 compressor
4.2.0 2018: new #target TZX: directly write to .tzx tape files
4.3.0 2020: new option --convert8080
4.4.0 2020: testcode runner
*/
#include "kio/kio.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include "unix/FD.h"
#include "unix/files.h"
#include "Z80Assembler.h"
#include "helpers.h"
#include "Z80/goodies/z80_goodies.h"
//static const char appl_name[] = "zasm";
#define VERSION "4.4.8"
// Help text:
// optimized for 80 characters / column
//
static const char version[] =
"–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n"
" zasm - 8080/z80/z180 assembler (c) 1994 - 2021 Günter Woigk.\n"
" version " VERSION ", %s, for " _PLATFORM ".\n" // version, date, platform
" homepage: https://k1.spdns.de/zasm/\n"
" git repo: https://github.com/Megatokio/zasm\n\n";
static const char syntax[] =
"syntax:\n"
" zasm [options] [-i] inputfile [[-l] listfile|dir] [[-o] outfile|dir]\n"
" zasm [--version|--help]\n\n"
" default output dir = source dir\n"
" default list dir = output dir\n\n";
static const char examples[] =
"examples:\n"
" zasm speccirom.asm\n"
" zasm -uwy emuf_rom.asm rom_v2.0.1.rom\n\n";
static const char options[] =
"options:\n"
" -u --opcodes include object code in list file\n"
" -w --labels append label listing to list file\n"
" -y --cycles include cpu clock cycles in list file\n"
" -b --bin write output to binary file (default)\n"
" -x --hex write output in intel hex format\n"
" -s --s19 write output in motorola s-record format\n"
" -z --clean clear intermediate files, e.g. compiled c files\n"
" -e --compare compare own output to existing output file\n"
" -T --test run self test (requires test directory with test sources)\n"
" -g --cgi prevent access to files outside the source dir\n"
" --maxerrors=NN set maximum for reported errors (default=30, max=999)\n"
" --date=DATETIME for reproducible __date__ and __time__\n"
" --target=ram default to target 'ram' => cpu addresses in hex files\n"
" -o0 don't write output file\n"
" -l0 don't write list file\n"
" --8080 target Intel 8080 (default if --asm8080)\n"
" --z80 target Zilog Z80 (default except if --asm8080)\n"
" --z180 target Zilog Z180 / Hitachi HD64180\n"
" --asm8080 use 8080 assembler syntax\n"
" --convert8080 convert 8080 assembler source to Z80\n"
" -v[0,1,2] verbosity of messages to stderr (0=off, 1=default, 2=more)\n"
" --ixcbr2 enable illegal instructions like 'set b,(ix+d),r'\n"
" --ixcbxh enable illegal instructions like 'set b,xh'\n"
" --dotnames allow label names starting with a dot '.'\n"
" --reqcolon require colon ':' after program label definitions\n"
" => label definitions and instructions may start in any column\n"
" --casefold label names are case insensitive (implied if --asm8080)\n"
" --flatops no operator precedence: evaluate strictly from left to right\n"
" -c [path/to/]cc declare or set path to c compiler (search in $PATH)\n"
" -t path/to/dir set path to temp dir for c compiler (default: output dir)\n"
" -I path/to/dir set path to c system header dir (default: compiler default)\n"
" -L path/to/dir set path to standard library dir (default: none)\n"
"–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n\n"
"";
static cstr compiledatestr ()
{
// helper: get the compile date in preferred format "yyyy-mm-dd":
static const char ansidate[] = __DATE__; // "Jan 1 2014"
static const char months[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
uint m=0; while (strncmp(ansidate, months+3*m++, 3)) {}
uint d = uint(strtol(ansidate+4,nullptr,10));
cptr y = ansidate+7;
return usingstr("%s-%02u-%02u",y,m,d);
}
static cstr help()
{
return catstr(usingstr(version,compiledatestr()),syntax,examples,options);
}
static void read_testdir (cstr path, Array<cstr>& filepaths)
{
// recursively read test directory
// skips symlinks (files and folders)
// skips "original/", "ALT/" and "s/"
// adds all ".asm" files which start with "#!"
assert(eq(path,fullpath(path,no)));
DIR* dir = opendir(path);
if (!dir) return; // error
for (;;)
{
dirent* direntry = readdir(dir);
if (!direntry) break;
cstr filename = direntry->d_name;
if (filename[0]=='.') continue; // "." or ".." or hidden file or folder
cstr filepath = catstr(path,filename);
struct stat filestat;
if (lstat(filepath,&filestat)) continue; // error
if (S_ISDIR(filestat.st_mode) && ne(filename,"original") && ne(filename,"ALT") && ne(filename,"s"))
read_testdir(catstr(filepath,"/"), filepaths);
//if(S_ISLNK(filestat.st_mode)) continue; // skip all symlinks, files or folders
if (!S_ISREG(filestat.st_mode)) continue; // not a file
if (!endswith(filename,".asm")) continue; // no assembler source file
int fd = open(filepath,O_RDONLY,0664); // test for Shebang:
if (fd<0) continue; // failed to open file
char bu[3] = "aa";
r: int n = int(read(fd,bu,2)); // read "#!"
if (n<0 && errno==EINTR) goto r;
if (n<0 && errno==EAGAIN) { usleep(5000); goto r; }
close(fd);
//if (n!=2) continue;
if (ne(bu,"#!")) continue; // does not start with #!/usr/local/zasm …
filepaths.append(filepath);
}
closedir(dir);
}
static void split_command_line (cstr s, Array<cstr>& args)
{
// split command line into words
// split at white space
// keep ".." and '..'
// unescape escaped char except inside '..'
// other bash syntax is ignored – this function is only used to parse our "#!…" in line 1 only
// see: http://wiki.bash-hackers.org/syntax/quoting
// see: https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
// inside double quotes (weak quotes):
// The backslash retains its special meaning only when followed by one of the following characters:
// ‘$’, ‘`’, ‘"’, ‘\’, or newline. Within double quotes, backslashes that are followed by one of these
// characters are removed. Backslashes preceding characters without a special meaning are left unmodified.
char zbu[256];
for (;;)
{
// skip gap:
while (*s && uchar(*s)<=' ') { s++; }
if (*s==0) break;
// copy word:
ptr z = zbu;
while (uchar(*s) > ' ')
{
if (*s == '\'') // strong quote
{
s++;
while (*s && *s!='\'') { *z++ = *s++; }
if (*s) s++;
continue;
}
if (*s=='"') // weak quote
{
s++;
while (*s && *s!='"')
{
if (*s == '\\')
{
char c = *(s+1);
if (c=='$' || c=='`' || c=='"' || c=='\\') s++; // skip over '\'
}
*z++ = *s++;
}
if (*s) s++;
continue;
}
// plain char
if (*s == '\\' && *(s+1)) s++; // skip over '\'
*z++ = *s++;
}
// store word:
args.append(substr(zbu,z));
}
}
static int doit( Array<cstr> argv )
{
// PROGRAM ENTRY POINT!
double start = now();
// options:
int verbose = 1; // 0=off, 1=default, 2=verbose
int outputstyle = 'b'; // 0=none, 'b'=binary, 'x'=intel hex, 's'=motorola s-records
int liststyle = 1; // 0=none, 1=plain, 2=with objcode, 4=with label listing, 6=both, 8=clock cycles
bool clean = no;
bool ixcbr2 = no;
bool ixcbxh = no;
bool targetZ80 = no;
bool target8080 = no;
bool targetZ180 = no;
bool syntax8080 = no;
bool dotnames = no;
bool reqcolon = no;
bool casefold = no;
bool flatops = no;
bool compare = no;
bool selftest = no;
bool cgi_mode = no;
bool convert8080 = no;
uint maxerrors = 30;
double timestamp = start; // __date__ and __time__ and S0 record
Target target = TARGET_UNSET;
// filepaths:
cstr inputfile = nullptr;
cstr outputfile = nullptr; // or dir
cstr listfile = nullptr; // or dir
cstr tempdir = nullptr;
cstr c_compiler = nullptr;
cstr c_includes = nullptr;
cstr stdlib_dir = nullptr; // for #include standard library
// work around Linux kernel limitation:
if (argv.count() >= 3 && strchr(argv[1],' '))
{
// split shebang arguments:
// argv[] = { "/path/to/zasm", "merged arguments from line 1", "executable/sourcefile/as/invocated", "more", "arguments" }
// note: a script can start with "#!" (shebang).
// then the Linux kernel takes everything up to the first space as the command,
// and everything after that space as ONE SINGLE ARGUMENT.
try
{
FD fd(argv[2]);
cstr s = fd.read_str();
if (endswith(s,argv[1]))
{
Array<cstr> multiargs;
split_command_line(argv[1],multiargs);
argv.removeat(1);
argv.insertat(1,multiargs);
}
}
catch (...){}
}
// eval arguments:
for (uint i=1; i<argv.count(); )
{
cptr s = argv[i++];
if (s[0] != '-')
{
if (!inputfile) { inputfile = s; continue; }
// if outfile is not prefixed with -o then it must be the last argument:
if (!outputfile && i==argv.count()) { outputfile = s; continue; }
if (!listfile) { listfile = s; continue; }
goto h;
}
if (s[1]=='-')
{
if (eq(s,"--clean")) { clean = yes; continue; }
if (eq(s,"--bin")) { outputstyle='b'; continue; }
if (eq(s,"--hex")) { outputstyle='x'; continue; }
if (eq(s,"--s19")) { outputstyle='s'; continue; }
if (eq(s,"--opcodes")) { liststyle |= 2; continue; }
if (eq(s,"--labels")) { liststyle |= 4; continue; }
if (eq(s,"--cycles")) { liststyle |= 8; continue; }
if (eq(s,"--ixcbr2")) { ixcbr2 = 1; continue; }
if (eq(s,"--ixcbxh")) { ixcbxh = 1; continue; }
if (eq(s,"--z80")) { targetZ80 = 1; continue; }
if (eq(s,"--8080")) { target8080 = 1; continue; }
if (eq(s,"--asm8080")) { syntax8080 = 1; continue; }
if (eq(s,"--z180")) { targetZ180 = 1; continue; }
if (eq(s,"--dotnames")) { dotnames = 1; continue; }
if (eq(s,"--reqcolon")) { reqcolon = 1; continue; }
if (eq(s,"--casefold")) { casefold = 1; continue; }
if (eq(s,"--flatops")) { flatops = 1; continue; }
if (eq(s,"--compare")) { compare = 1; continue; }
if (eq(s,"--test")) { selftest = 1; continue; }
if (eq(s,"--cgi")) { cgi_mode = 1; continue; }
if (eq(s,"--convert8080")) { convert8080 = 1; continue; }
if (startswith(s,"--maxerrors="))
{
char* ep; ulong n = strtoul(s+12,&ep,10);
if (*ep||n==0||n>999) goto h;
maxerrors = uint(n); continue;
}
if (startswith(s,"--date="))
{
timestamp = double(dateval(s));
continue;
}
if (startswith(s,"--target=")) // 4.4.6
{
cstr t = lowerstr(s+9);
if (eq(t,"ram")) target = BIN; else
if (eq(t,"bin")) target = BIN; else
if (eq(t,"rom")) target = ROM; else goto h;
continue;
}
goto h;
}
while (char c = *++s)
{
switch (c)
{
case 'e': compare = 1; continue;
case 'T': selftest = 1; continue;
case 'u': liststyle |= 2; continue;
case 'w': liststyle |= 4; continue;
case 'y': liststyle |= 8; continue;
case 's': outputstyle=c; continue;
case 'x': outputstyle=c; continue;
case 'b': outputstyle=c; continue;
case 'z': clean=yes; continue;
case 'g': cgi_mode=yes; continue;
case 'v': if (*(s+1)>='0' && *(s+1)<='3') verbose = *++s - '0'; else ++verbose; continue;
case 'i': if (inputfile || i==argv.count()) goto h; else inputfile = argv[i++]; continue;
case 'o': if (*(s+1)=='0') { outputstyle = 0; ++s; continue; }
if (outputfile || i==argv.count()) goto h; else outputfile = argv[i++]; continue;
case 'l': if (*(s+1)=='0') { liststyle = 0; ++s; continue; }
if (listfile || i==argv.count()) goto h; else listfile = argv[i++]; continue;
case 'c': if (c_compiler || i==argv.count()) goto h; else c_compiler = argv[i++]; continue;
case 'I': if (c_includes || i==argv.count()) goto h; else c_includes = argv[i++]; continue;
case 'L': if (stdlib_dir || i==argv.count()) goto h; else stdlib_dir = argv[i++]; continue;
case 't': if (tempdir || i==argv.count()) goto h; else tempdir = argv[i++]; continue;
default: goto h;
}
}
}
if (selftest && !compare)
{
// assemble a bunch of sources from a test directory
// and compare them to old versions found in the original/ subdirectories.
if (verbose) logline("zasm: +++ Regression Test +++");
if (verbose) logline("zasm: version " VERSION ", %s, for " _PLATFORM " on " _PROCESSOR ".", compiledatestr());
// if no path to the $TESTDIR directory is given, then the current working directory is used.
// ".asm" source files which start with "#!" will be assembled and compared to the original output file.
cstr testdir = fullpath( inputfile ? inputfile : outputfile ? outputfile : "./" );
if (errno==ok && lastchar(testdir)!='/') errno = ENOTDIR;
if (errno)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", testdir, strerror(errno));
return 1;
}
// collect all test sources:
Array<cstr> testfiles;
if (verbose) logline("zasm: scanning directory for test sources ... ");
read_testdir(testdir,testfiles);
if (verbose) logline("zasm: found %u test source files\n",testfiles.count());
// assemble & compare all test sources:
int errors = 0;
for (uint i=0; i<testfiles.count(); i++)
{
cstr testfile = testfiles[i];
if (verbose) logline("assemble file: %s",testfile);
// read line 1:
int fd = open(testfile,O_RDONLY,0664);
if (fd<0) { errors++; logline("%s",strerror(errno)); continue; } // error
char bu[256];
r: int n = int(read(fd,bu,255)); // read line 1
if (n<0)
{
if (errno==EINTR) goto r;
if (errno==EAGAIN) { usleep(5000); goto r; }
errors++; logline("%s",strerror(errno)); close(fd); continue;
}
close(fd);
bu[n] = '\n';
*strchr(bu,'\n') = 0;
// split args[] and combine argument lists for recursive call:
Array<cstr> args;
split_command_line(bu,args);
assert(args.count()>0);
args[0] = argv[0]; // path/to/zasm
args.append("-l0");
args.append("-i");
args.append(testfile);
args.append("--compare");
for (uint j=1; j<argv.count(); j++) { args.append(argv[j]); }
// recursively call self:
change_working_dir(directory_from_path(testfile)); // to find output dir
errors += doit(std::move(args));
}
if (verbose)
{
log( "\ntotal time: %3.4f sec.\n", now()-start);
if (errors>1) log( "\nzasm: %u errors\n\n", errors);
else log( errors ? "\nzasm: 1 error\n\n" : "zasm: no errors\n");
}
return errors>0;
}
// check options:
if ((targetZ80 + target8080 + targetZ180) > 1)
{
log("--> %s\nzasm: 1 error\n", "multiple cpu targets selected.");
return 1;
}
// check source file:
if (!inputfile)
{
h: log("%s",help());
return 1;
}
inputfile = fullpath(inputfile,no);
if (errno)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", inputfile, strerror(errno));
return 1;
}
if (!is_file(inputfile))
{
if (verbose) log( "--> %s: not a regular file\nzasm: 1 error\n", inputfile);
return 1;
}
// check output file or dir:
if (!outputfile) outputfile = directory_from_path(inputfile);
outputfile = fullpath(outputfile);
if (errno && errno!=ENOENT)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", outputfile, strerror(errno));
return 1;
}
if (convert8080 && lastchar(outputfile)!='/')
{
// output file must be a text file. reject at least the most common binary files:
cstr ext = lowerstr(extension_from_path(outputfile));
if (eq(ext,".bin") || eq(ext,".rom") || eq(ext,".hex") || eq(ext,".s19"))
{
if (verbose) log( "--> output file must specify a z80 source file name\nzasm: 1 error\n");
return 1;
}
}
// check list file or dir:
// must not be tested here: in some cases assemble() must see whether it was set
// check temp dir:
if (!tempdir) tempdir = directory_from_path(outputfile);
tempdir = fullpath(tempdir);
if (errno && errno!=ENOENT)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", tempdir, strerror(errno));
return 1;
}
if (lastchar(tempdir)!='/')
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", tempdir, strerror(ENOTDIR));
return 1;
}
// check c_includes path:
if (c_includes)
{
c_includes = fullpath(c_includes);
if (errno==ok && lastchar(c_includes)!='/') errno = ENOTDIR;
if (errno)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", c_includes, strerror(errno));
return 1;
}
}
// check standard library directory path:
if (stdlib_dir)
{
stdlib_dir = fullpath(stdlib_dir);
if (errno==ok && lastchar(stdlib_dir)!='/') errno = ENOTDIR;
if (errno)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", stdlib_dir, strerror(errno));
return 1;
}
}
// check c_compiler path:
if (c_compiler)
{
if (c_compiler[0]!='/')
{
cstr s = find_executable(c_compiler);
if (s) c_compiler = s;
}
c_compiler = fullpath(c_compiler);
if (errno)
{
if (verbose) log( "--> %s: %s\nzasm: 1 error\n", c_compiler, strerror(errno));
return 1;
}
if (!is_file(c_compiler))
{
if (verbose) log( "--> %s: not a regular file\nzasm: 1 error\n", c_compiler);
return 1;
}
if (!is_executable(c_compiler))
{
if (verbose) log( "--> %s: not executable\nzasm: 1 error\n", c_compiler);
return 1;
}
}
// DO IT!
Z80Assembler ass;
if (targetZ180) ass.cpu = CpuZ180;
if (target8080) ass.cpu = Cpu8080;
if (targetZ80) ass.cpu = CpuZ80;
ass.timestamp = timestamp;
ass.verbose = verbose;
ass.ixcbr2_enabled = ixcbr2;
ass.ixcbxh_enabled = ixcbxh;
ass.syntax_8080 = syntax8080;
ass.convert_8080 = convert8080;
ass.require_colon = reqcolon;
ass.allow_dotnames = dotnames;
ass.casefold = casefold;
ass.flat_operators = flatops;
ass.max_errors = maxerrors;
ass.default_target = target;
ass.compare_to_old = compare;
ass.cgi_mode = cgi_mode;
ass.c_compiler = c_compiler;
ass.c_includes = c_includes;
ass.stdlib_dir = stdlib_dir;
ass.assembleFile( inputfile, outputfile, listfile, tempdir, liststyle, outputstyle, clean );
uint errors = ass.errors.count();
if (verbose) // show errors on stderr:
{
cstr current_file = nullptr;
for (uint i=0; i<errors; i++)
{
Error const& e = ass.errors[i];
SourceLine* sourceline = e.sourceline;
if (!sourceline)
{
if (current_file) log("\n");
current_file = nullptr;
log("--> %s\n",e.text);
continue;
}
cstr filename = sourceline->sourcefile;
if (filename!=current_file) // note: compare pointers!
{
current_file = filename;
log( "\nin file %s:\n", filename_from_path(filename));
}
cstr linenumber = tostr(sourceline->sourcelinenumber+1);
log( "%s: %s\n", linenumber, sourceline->text);
log( "%s%s^ %s\n", spacestr(int(strlen(linenumber))+2), sourceline->whitestr(), e.text);
}
log( "assembled file: %s\n %u lines, %u pass%s, %3.4f sec.\n",
filename_from_path(inputfile), ass.numSourcelines(), ass.numPasses(), ass.numPasses()==1?"":"es", now()-start);
if (errors>1) log( " %u errors\n\n", errors);
else log( errors ? " 1 error\n\n" : " no errors\n\n");
}
return errors>0; // 0=ok, 1=errors
}
int main (int argc, cstr argv[])
{
if (argc==2)
{
if (eq(argv[1], "--version")) { printf(version,compiledatestr()); return 0; }
if (eq(argv[1], "--help")) { printf("%s", help()); return 0; }
}
return doit(Array<cstr>(argv,uint(argc)));
}
| 20,958
| 8,998
|
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int k{0};
for(int i=0;i<n;i++){
if(nums[i] != val){
nums[k] = nums[i];
k++;
}
}
return k;
}
};
| 293
| 102
|
/*
* Copyright (c) 2021, NVIDIA 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 <model_oversubscriber/parameter_server.hpp>
#include <fstream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
namespace HugeCTR {
namespace {
void open_and_get_size(const std::string& file_name, std::ifstream& stream,
size_t& file_size_in_byte) {
stream.open(file_name, std::ifstream::binary);
if (!stream.is_open()) {
CK_THROW_(Error_t::WrongInput, "Cannot open the file: " + file_name);
}
file_size_in_byte = fs::file_size(file_name);
}
} // namespace
template <typename TypeKey>
ParameterServer<TypeKey>::ParameterServer(bool use_host_ps,
const std::string &sparse_model_file, Embedding_t embedding_type,
size_t emb_vec_size, std::shared_ptr<ResourceManager> resource_manager)
: use_host_ps_(use_host_ps),
sparse_model_entity_(SparseModelEntity<TypeKey>(use_host_ps,
sparse_model_file, embedding_type, emb_vec_size, resource_manager)) {}
template <typename TypeKey>
void ParameterServer<TypeKey>::load_keyset_from_file(
std::string keyset_file) {
try {
std::ifstream keyset_stream;
size_t file_size_in_byte = 0;
open_and_get_size(keyset_file, keyset_stream, file_size_in_byte);
if (file_size_in_byte == 0) {
CK_THROW_(Error_t::WrongInput, std::string(keyset_file) + " is empty");
}
size_t num_keys_in_file = file_size_in_byte / sizeof(TypeKey);
keyset_.resize(num_keys_in_file);
keyset_stream.read((char*)keyset_.data(), file_size_in_byte);
#ifdef ENABLE_MPI
CK_MPI_THROW_(MPI_Barrier(MPI_COMM_WORLD));
#endif
} catch (const internal_runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
} catch (const std::exception& err) {
std::cerr << err.what() << std::endl;
throw;
}
}
template <typename TypeKey>
void ParameterServer<TypeKey>::pull(BufferBag& buf_bag, size_t& hit_size) {
if (keyset_.size() == 0) {
CK_THROW_(Error_t::WrongInput, "keyset is empty");
}
sparse_model_entity_.load_vec_by_key(keyset_, buf_bag, hit_size);
}
template <typename TypeKey>
void ParameterServer<TypeKey>::push(BufferBag &buf_bag, size_t dump_size) {
if (dump_size == 0) return;
sparse_model_entity_.dump_vec_by_key(buf_bag, dump_size);
}
template class ParameterServer<long long>;
template class ParameterServer<unsigned>;
} // namespace HugeCTR
| 2,956
| 1,035
|
/*
* Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#ifdef USE_PCH
#include "lno_pch.h"
#endif // USE_PCH
#pragma hdrstop
#ifdef _KEEP_RCS_ID
/*REFERENCED*/
static char *rcs_id = "$Source$ $Revision$";
#endif /* _KEEP_RCS_ID */
#include <sys/types.h>
#include <ctype.h>
#include <limits.h>
#include <alloca.h>
#include "pu_info.h"
#include "lnoutils.h"
#include "lnopt_main.h"
#include "stab.h"
#include "targ_const.h"
#include "wn_simp.h"
#include "stdlib.h"
#include "lwn_util.h"
#include "strtab.h"
#include "config.h"
#include "optimizer.h"
#include "opt_du.h"
#include "name.h"
#include "wintrinsic.h"
#include "lno_bv.h"
#include "dep_graph.h"
#include "debug.h"
#include "cxx_memory.h"
#include "lego_pragma.h"
#include "lego_util.h"
#include "lego_skew.h"
#include "tlog.h"
//-----------------------------------------------------------------------
// NAME: Lego_Reshaped_Array
// FUNCTION: Returns TRUE if the OPR_ARRAY node 'wn_array' is a lego
// reshaped array, FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL Lego_Reshaped_Array(WN* wn_array)
{
if (WN_operator(wn_array) != OPR_ARRAY)
return FALSE;
ST* st_array;
WN *array_base = WN_array_base(wn_array);
st_array = (WN_has_sym(array_base) ? WN_st(array_base) : NULL);
DISTR_ARRAY* dact = Lookup_DACT(st_array);
if (dact == NULL || !dact->Dinfo()->IsReshaped())
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Canonical
// FUNCTION: Returns TRUE if the access vector is canonical with respect
// to the loop 'wn_loop'. Right now, this means that it has the form
// 'c1*i+x-c2' where "i" is the index variable of 'wn_loop', "x" is some
// linear combination of loop invariant variables, and "c1" and "c2" are
// literal constants. Also, "c1" must be either 1 or -1.
//-----------------------------------------------------------------------
static BOOL Lego_Skew_Canonical(WN* wn_loop,
ACCESS_VECTOR* av)
{
if (av->Too_Messy)
return FALSE;
if (av->Contains_Non_Lin_Symb())
return FALSE;
if (!av->Has_Loop_Coeff())
return FALSE;
INT loop_depth = Do_Depth(wn_loop);
INT loop_coeff = av->Loop_Coeff(loop_depth);
if (loop_coeff != 1 && loop_coeff != -1)
return FALSE;
for (INT i = 0; i < av->Nest_Depth(); i++)
if (i != loop_depth && av->Loop_Coeff(i) != 0)
return FALSE;
if (!av->Contains_Lin_Symb())
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Equivalent
// FUNCTION: Returns TRUE if the canonical access vectors 'av1' and 'av2'
// are equivalent. Right now, this means that their linear portions are
// equivalent and the coefficients corresponding to 'wn_loop' are equal.
//-----------------------------------------------------------------------
static BOOL Lego_Skew_Equivalent(WN* wn_loop,
ACCESS_VECTOR* av1,
ACCESS_VECTOR* av2)
{
if (av1->Loop_Coeff(Do_Depth(wn_loop)) != av2->Loop_Coeff(Do_Depth(wn_loop)))
return FALSE;
INTSYMB_LIST* isl = NULL;
isl = Subtract(av1->Lin_Symb, av2->Lin_Symb, &LNO_local_pool);
if (isl != NULL)
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Update_Skew_Count
// FUNCTION: For the given array 'wn_array' with respect to the loop
// 'wn_loop', enter all canonical skew accesses into separate buckets
// of 'st_skew'.
//-----------------------------------------------------------------------
static void Lego_Update_Skew_Count(WN* wn_loop,
WN* wn_array,
STACK<LEGO_SKEW*>* st_skew)
{
DISTR_ARRAY* dact = Lookup_DACT(WN_has_sym(WN_array_base(wn_array)) ?
WN_st(WN_array_base(wn_array)) :
NULL);
ACCESS_ARRAY *aa = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, wn_array);
if (aa == NULL || aa->Too_Messy)
return;
for (INT i = 0; i < aa->Num_Vec(); i++) {
ACCESS_VECTOR* av = aa->Dim(i);
if (Lego_Skew_Canonical(wn_loop, av)) {
INT j;
for (j = 0; j < st_skew->Elements(); j++) {
LEGO_SKEW* lsk = st_skew->Bottom_nth(j);
ST* st_old = (WN_has_sym(WN_array_base(lsk->Array())) ?
WN_st(WN_array_base(lsk->Array())) :
NULL);
DISTR_ARRAY* dact_old = Lookup_DACT(st_old);
if (dact->DACT_Equiv(dact_old, i, lsk->Dim())
&& Lego_Skew_Equivalent(wn_loop, av, lsk->Av())) {
lsk->Increment();
break;
}
}
if (j == st_skew->Elements()) {
LEGO_SKEW* lsk_new = CXX_NEW(LEGO_SKEW(av, wn_array, i, 1),
&LNO_default_pool);
st_skew->Push(lsk_new);
}
}
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Offset
// FUNCTION: Returns a WN* to an expression tree corresponding to the
// LEGO_SKEW 'lsk'.
//-----------------------------------------------------------------------
static WN* Lego_Skew_Offset(LEGO_SKEW* lsk,
BOOL negative_stride,
DU_MANAGER* du)
{
WN* wn_skew = NULL;
INTSYMB_CONST_ITER iter(lsk->Av()->Lin_Symb);
const INTSYMB_NODE *first = iter.First();
for (const INTSYMB_NODE *node=first; !iter.Is_Empty(); node = iter.Next()) {
WN* wn_variable = Find_Node(node->Symbol, lsk->Array());
WN* wn_constant = LWN_Make_Icon(WN_rtype(wn_variable), node->Coeff);
WN* wn_varcopy = LWN_Copy_Tree(wn_variable);
LWN_Copy_Def_Use(wn_variable, wn_varcopy, du);
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_variable), MTYPE_V);
WN* wn_prod = LWN_CreateExp2(op_mpy, wn_constant, wn_varcopy);
if (wn_skew == NULL) {
wn_skew = wn_prod;
} else {
TYPE_ID type_add = Max_Wtype(WN_rtype(wn_skew), WN_rtype(wn_prod));
OPCODE op_add = OPCODE_make_op(OPR_ADD, type_add, MTYPE_V);
wn_skew = LWN_CreateExp2(op_add, wn_skew, wn_prod);
}
}
if (negative_stride) {
WN* wn_minusone = LWN_Make_Icon(WN_rtype(wn_skew), -1);
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_skew), MTYPE_V);
wn_skew = LWN_CreateExp2(op_mpy, wn_minusone, wn_skew);
}
return wn_skew;
}
//-----------------------------------------------------------------------
// NAME: Lego_Loop_Want_Skew
// FUNCTION: Returns TRUE if we would like to skew the indices of the
// loop 'wn_loop'.
// NOTE: On exit, the value of the skew factor is copied back into
// 'wn_lego_skew_addr'.
//-----------------------------------------------------------------------
static BOOL Lego_Loop_Want_Skew(WN* wn_loop,
WN** wn_lego_skew_addr,
DU_MANAGER* du)
{
*wn_lego_skew_addr = NULL;
WN* wn_step = Loop_Step(wn_loop);
if (WN_operator(wn_step) != OPR_INTCONST)
return FALSE;
if (WN_const_val(wn_step) != 1)
return FALSE;
if (!Upper_Bound_Standardize(WN_end(wn_loop), TRUE))
return FALSE;
STACK<LEGO_SKEW*> st_skew(&LNO_local_pool);
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (Lego_Reshaped_Array(wn))
Lego_Update_Skew_Count(wn_loop, wn, &st_skew);
}
if (st_skew.Elements() == 0)
return FALSE;
LEGO_SKEW* lsk_best = st_skew.Bottom_nth(0);
for (INT i = 1; i < st_skew.Elements(); i++) {
LEGO_SKEW* lsk = st_skew.Bottom_nth(i);
if (lsk->Count() > lsk_best->Count())
lsk_best = lsk;
}
BOOL negative_stride = lsk_best->Av()->Loop_Coeff(Do_Depth(wn_loop)) < 0;
*wn_lego_skew_addr = Lego_Skew_Offset(lsk_best, negative_stride, du);
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Parent_Array
// FUNCTION: Returns the closest enclosing OPR_ARRAY node which is a
// parent of 'wn_node'. Returns NULL if there is none.
//-----------------------------------------------------------------------
static WN* Lego_Parent_Array(WN* wn_node)
{
for (WN* wn = wn_node; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_operator(wn) == OPR_ARRAY)
return wn;
return NULL;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Index
// FUNCTION: Returns an expression 'index - offset' where "index"
// is the index variable of 'wn_loop' and "offset" is the expression
// in 'wn_lego_skew_offset'.
//-----------------------------------------------------------------------
static WN* Lego_Skew_Index(WN* wn_loop,
WN* wn_lego_skew_offset,
DU_MANAGER* du)
{
TYPE_ID type = Promote_Type(Do_Wtype(wn_loop));
WN* wn_index = UBvar(WN_end(wn_loop));
WN* wn_index_copy = LWN_Copy_Tree(wn_index);
LWN_Copy_Def_Use(wn_index, wn_index_copy, du);
WN* wn_ldid = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_ldid, du);
OPCODE op = OPCODE_make_op(OPR_SUB, type, MTYPE_V);
WN* wn_skew = LWN_CreateExp2(op, wn_index_copy, wn_ldid);
return wn_skew;
}
//-----------------------------------------------------------------------
// NAME: Lego_Contains_Non_Index_Ldid
// FUNCTION: Returns TRUE if the expression 'wn_index' contains an LDID
// of a symbol other than the index variable of 'wn_loop', FALSE
// otherwise.
//-----------------------------------------------------------------------
static BOOL Lego_Contains_Non_Index_Ldid(WN* wn_loop,
WN* wn_index)
{
LWN_ITER* itr = LWN_WALK_TreeIter(wn_index);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_LDID
&& SYMBOL(wn) != SYMBOL(WN_index(wn_loop)))
return TRUE;
}
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Index_From_Access_Vector
// FUNCTION: Returns a WN* to an expression equivalent to the access
// vector 'av'. The expressions value should be equivalent to that
// in 'wn_index'.
//-----------------------------------------------------------------------
static WN* Lego_Index_From_Access_Vector(ACCESS_VECTOR* av,
WN* wn_index,
DU_MANAGER* du)
{
WN* wn_new_index = NULL;
for (INT i = 0; i < av->Nest_Depth(); i++) {
if (av->Loop_Coeff(i) == 0)
continue;
WN* wn = 0;
for (wn = wn_index; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP && Do_Depth(wn) == i)
break;
FmtAssert(wn != NULL, ("Could not find do loop with given depth"));
OPCODE op_ldid = Matching_Load_Opcode(WN_opcode(WN_start(wn)));
WN* wn_ldid = LWN_CreateLdid(op_ldid, WN_start(wn));
du->Add_Def_Use(WN_start(wn), wn_ldid);
du->Add_Def_Use(WN_step(wn), wn_ldid);
du->Ud_Get_Def(wn_ldid)->Set_loop_stmt(wn);
WN* wn_constant = LWN_Make_Icon(WN_rtype(wn_ldid), av->Loop_Coeff(i));
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_ldid), MTYPE_V);
WN* wn_prod = LWN_CreateExp2(op_mpy, wn_constant, wn_ldid);
if (wn_new_index == NULL) {
wn_new_index = wn_prod;
} else {
TYPE_ID type_add = Max_Wtype(WN_rtype(wn_ldid), WN_rtype(wn_new_index));
OPCODE op_add = OPCODE_make_op(OPR_ADD, type_add, MTYPE_V);
wn_new_index = LWN_CreateExp2(op_add, wn_new_index, wn_prod);
}
}
if (av->Const_Offset != 0) {
if (wn_new_index == 0) {
wn_new_index = LWN_Make_Icon(av->Const_Offset, WN_rtype(wn_index));
} else {
WN* wn_offset = LWN_Make_Icon(WN_rtype(wn_new_index), av->Const_Offset);
OPCODE op_add = OPCODE_make_op(OPR_ADD, WN_rtype(wn_new_index), MTYPE_V);
wn_new_index = LWN_CreateExp2(op_add, wn_new_index, wn_offset);
}
}
return wn_new_index;
}
//-----------------------------------------------------------------------
// NAME: Lego_Simplify
// FUNCTION: Simplify the subscripts of the array expression 'wn_loop'
// which contain the index variable of loop 'wn_loop' if their access
// vectors contain only index variables and constants and if the
// subscripts also contain other symbols.
//-----------------------------------------------------------------------
static void Lego_Simplify(WN* wn_loop,
WN* wn_array,
DU_MANAGER* du)
{
ACCESS_ARRAY *aa = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, wn_array);
if (aa == NULL || aa->Too_Messy)
return;
INT loop_depth = Do_Depth(wn_loop);
INT i;
for (i = 0; i < aa->Num_Vec(); i++)
if (aa->Dim(i)->Delinearized_Symbol != NULL)
return;
for (i = 0; i < aa->Num_Vec(); i++) {
ACCESS_VECTOR* av = aa->Dim(i);
if (av->Too_Messy)
continue;
INT loop_coeff = av->Loop_Coeff(loop_depth);
if (av->Loop_Coeff(loop_depth)== 0 || av->Contains_Non_Lin_Symb())
continue;
if (av->Contains_Lin_Symb())
continue;
WN* wn_index = WN_array_index(wn_array, i);
if (!Lego_Contains_Non_Index_Ldid(wn_loop, wn_index))
continue;
WN* wn_new_index = Lego_Index_From_Access_Vector(av, wn_index, du);
Replace_Wnexp_With_Exp_Copy(wn_index, wn_new_index, du);
LWN_Delete_Tree(wn_new_index);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Simplify_Loop
// FUNCTION: Simplify the subscripts of array elements in 'wn_loop' using
// access vectors.
//-----------------------------------------------------------------------
static void Lego_Simplify_Loop(WN* wn_loop,
DU_MANAGER* du)
{
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_ARRAY)
Lego_Simplify(wn_loop, wn, du);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Loop
// FUNCTION: Skew the loop 'wn_loop' by subtracting 'wn_lego_skew_index'
// from each instance of the index variable of 'wn_loop' and adding the
// same value to the loop bounds.
//-----------------------------------------------------------------------
static void Lego_Skew_Loop(WN* wn_loop,
WN* wn_lego_skew_offset,
DU_MANAGER* du)
{
if (LNO_Verbose) {
fprintf(stdout, "Lego skewing loop %s on line %d\n",
WB_Whirl_Symbol(wn_loop), Srcpos_To_Line(WN_linenum(wn_loop)));
fprintf(TFile, "Lego skewing loop %s on line %d\n",
WB_Whirl_Symbol(wn_loop), Srcpos_To_Line(WN_linenum(wn_loop)));
if (LNO_Tlog)
Generate_Tlog("LNO", "lego_skewing", Srcpos_To_Line(WN_linenum(wn_loop)),
(char *) WB_Whirl_Symbol(wn_loop), "", "", "");
}
if (Index_Variable_Live_At_Exit(wn_loop))
Finalize_Index_Variable(wn_loop, TRUE, TRUE);
TYPE_ID type = Promote_Type(Do_Wtype(wn_loop));
OPCODE op_skew = OPCODE_make_op(OPR_ADD, type, MTYPE_V);
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
STACK<WN*> index_stack(&LNO_local_pool);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_LDID
&& SYMBOL(wn) == SYMBOL(WN_index(wn_loop)))
index_stack.Push(wn);
}
INT i;
for (i = 0; i < index_stack.Elements(); i++) {
WN* wn = index_stack.Bottom_nth(i);
WN* wn_array = Lego_Parent_Array(wn);
WN* wn_new_index = Lego_Skew_Index(wn_loop, wn_lego_skew_offset, du);
Replace_Wnexp_With_Exp_Copy(wn, wn_new_index, du);
if (wn_array != NULL)
LWN_Simplify_Tree(wn_array);
LWN_Delete_Tree(wn_new_index);
}
WN* wn_start = WN_kid0(WN_start(wn_loop));
WN* wn_stop = UBexp(WN_end(wn_loop));
for (i = 0; i < WN_kid_count(WN_end(wn_loop)); i++)
if (WN_kid(WN_end(wn_loop), i) == wn_stop)
break;
INT stop_index = i;
WN* wn_skew = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_skew, du);
WN* wn_new_start = LWN_CreateExp2(op_skew, wn_start, wn_skew);
wn_skew = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_skew, du);
WN* wn_new_stop = LWN_CreateExp2(op_skew, wn_stop, wn_skew);
WN_kid0(WN_start(wn_loop)) = wn_new_start;
LWN_Set_Parent(wn_new_start, WN_start(wn_loop));
WN_kid(WN_end(wn_loop), stop_index) = wn_new_stop;
LWN_Set_Parent(wn_new_stop, WN_end(wn_loop));
LWN_Delete_Tree(wn_lego_skew_offset);
DOLOOP_STACK shortstack(&LNO_local_pool);
Build_Doloop_Stack(LWN_Get_Parent(wn_loop), &shortstack);
LNO_Build_Access(wn_loop, &shortstack, &LNO_default_pool, 0, TRUE);
Lego_Simplify_Loop(wn_loop, du);
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Traverse
// FUNCTION: Traverse 'wn_tree' preforming lego skewing on loops for
// which is it appropriate.
//-----------------------------------------------------------------------
static void Lego_Skew_Traverse(WN* wn_tree,
DU_MANAGER* du)
{
if (WN_opcode(wn_tree) == OPC_DO_LOOP) {
WN* wn_lego_skew_offset = NULL;
if (Lego_Loop_Want_Skew(wn_tree, &wn_lego_skew_offset, du))
Lego_Skew_Loop(wn_tree, wn_lego_skew_offset, du);
}
if (WN_opcode(wn_tree) == OPC_BLOCK) {
for (WN* wn = WN_first(wn_tree); wn != NULL; wn = WN_next(wn))
Lego_Skew_Traverse(wn, du);
} else {
for (INT i = 0; i < WN_kid_count(wn_tree); i++)
Lego_Skew_Traverse(WN_kid(wn_tree, i), du);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Indices
// FUNCTION: Apply lego skewing to all appropriate loops in the tree
// 'wn_tree'.
//-----------------------------------------------------------------------
extern void Lego_Skew_Indices(WN* wn_tree)
{
DU_MANAGER* du = Du_Mgr;
Lego_Skew_Traverse(wn_tree, du);
}
| 19,031
| 7,535
|
#include <stdio.h>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
int a[1005][4];
int siz[1005];
int n;
int r[4];
class Event {
public:
int t, L, R, v;
Event(int tt=0, int ll=0, int rr=0, int vv=0) {
t = tt; L = ll; R = rr; v=vv;
}
bool operator<(const Event &e) const {
return t < e.t || t==e.t && v < e.v;
}
} e[2005];
class Segment {
public:
int maxvalue, maxpos, value;
Segment(int m=0,int p=0, int v=0) {
maxvalue = m; maxpos = p; value = v;
}
};
Segment seg[100005];
int ne;
int yy[50005];
inline void init(int x, int L, int R) {
if(L==R) {
seg[x].maxvalue = 0;
seg[x].maxpos = L;
seg[x].value = 0;
} else {
seg[x].maxvalue = 0;
seg[x].maxpos = L;
seg[x].value = 0;
init(x*2, L, (L+R)/2);
init(x*2+1, (L+R)/2+1, R);
}
}
inline void combine(int x) {
int y = x*2, z = x*2+1;
if(seg[y].maxvalue >= seg[z].maxvalue) {
seg[x].maxvalue = seg[y].maxvalue + seg[x].value;
seg[x].maxpos = seg[y].maxpos;
} else {
seg[x].maxvalue = seg[z].maxvalue + seg[x].value;
seg[x].maxpos = seg[z].maxpos;
}
}
int cnt=0;
inline void update(int x, int L, int R, int vL, int vR, int v) {
++cnt;
if(vL <= L && vR >= R) {
seg[x].value += v;
seg[x].maxvalue += v;
} else {
int M = (L+R)/2;
if(vL <= M) update(x*2, L, M, vL, vR, v);
if(vR > M) update(x*2+1, M+1, R, vL, vR, v);
combine(x);
}
}
int ans=0;
int go(int side) {
int i, d=0;
ne = 0;
set<int> s;
map<int, int> ymap;
for(i=0;i<n;i++) {
if(siz[i] >= side) {
e[ne].t = a[i][0] - side + 1;
e[ne].L = a[i][1] - side + 1;
e[ne].R = a[i][3] - 1;
s.insert(e[ne].L);
s.insert(e[ne].R);
e[ne++].v = 1;
e[ne].t = a[i][2];
e[ne].L = a[i][1] - side + 1;
e[ne].R = a[i][3] - 1;
s.insert(e[ne].L);
s.insert(e[ne].R);
e[ne++].v = -1;
++d;
}
}
if(d<=ans) return -1;
i=0;
int len = s.size();
for(set<int>::iterator it = s.begin(); it != s.end(); it++) {
ymap[*it] = ++i;
yy[i] = *it;
}
sort(e, e+ne);
init(1, 1, len);
int mx=0;
for(i=0;i<ne;i++) {
//printf("t=%d %d %d %d\n", e[i].t, e[i].L, e[i].R, e[i].v);
update(1, 1, len, ymap[e[i].L], ymap[e[i].R], e[i].v);
if(seg[1].maxvalue > mx) {
mx = seg[1].maxvalue;
r[0] = e[i].t;
r[1] = yy[seg[1].maxpos];
r[2] = r[0]+side;
r[3] = r[1]+side;
}
}
return mx;
}
int main(void)
{
int i, j;
while(scanf("%d", &n)!=EOF) {
if(n==0) break;
for(i=0;i<n;i++) {
for(j=0;j<4;j++)
scanf("%d", &a[i][j]);
siz[i] = a[i][2]-a[i][0];
}
int mx=0, v;
int p[4];
set<int> usedsiz;
ans = 0;
for(i=0;i<n;i++) {
if(usedsiz.count(siz[i])) continue;
usedsiz.insert(siz[i]);
v=go(siz[i]);
if(v>mx){
mx = v;
ans = mx;
for(j=0;j<4;j++)
p[j] = r[j];
//printf("ans=%d\n", ans);
if(ans>=4) break;
}
}
printf("%d %d %d %d\n", p[0], p[1], p[2], p[3]);
}
return 0;
}
| 3,104
| 1,588
|
#include "mex.h"
#include <iostream>
#include "drakeMexUtil.h"
#include <Eigen/Dense>
#include "RigidBodyConstraint.h"
#include "RigidBodyManipulator.h"
#include "constructPtrRigidBodyConstraint.h"
#include <cstdio>
using namespace Eigen;
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
RigidBodyConstraint* constraint = (RigidBodyConstraint*) getDrakeMexPointer(prhs[0]);
int constraint_type = constraint->getType();
if (nrhs<2) { // then it's just calling delete
destroyDrakeMexPointer<RigidBodyConstraint*>(prhs[0]);
return;
}
mwSize strlen = static_cast<mwSize>(mxGetNumberOfElements(prhs[1]) + 1);
char* field = new char[strlen];
mxGetString(prhs[1],field,strlen);
string field_str(field);
switch(constraint_type)
{
case RigidBodyConstraint::QuasiStaticConstraintType:
{
QuasiStaticConstraint* cnst = (QuasiStaticConstraint*) constraint;
if(field_str=="active")
{
// setActive(qsc_ptr,flag)
if(mxGetNumberOfElements(prhs[2]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:flag must be a single boolean");
}
bool* flag = mxGetLogicals(prhs[2]);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->setActive(*flag);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="factor")
{// setShrinkFactor(qsc_ptr,factor)
if(mxGetNumberOfElements(prhs[2]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:shrink factor must be a double scalar");
}
double factor = mxGetScalar(prhs[2]);
if(factor<=0.0)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:shrink factor should be a positive scalar");
}
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->setShrinkFactor(factor);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="contact")
{
// addContact(qsc_ptr,body1, body1_pts, body2, body2_pts,...)
int num_new_bodies = (nrhs-2)/2;
int* new_bodies = new int[num_new_bodies];
Matrix3Xd* new_body_pts = new Matrix3Xd[num_new_bodies];
for(int idx = 0;idx<num_new_bodies;idx++)
{
new_bodies[idx] = (int) mxGetScalar(prhs[2+idx*2])-1;
size_t npts = mxGetN(prhs[3+idx*2]);
Matrix3Xd new_body_pts_tmp(3,npts);
memcpy(new_body_pts_tmp.data(),mxGetPrSafe(prhs[3+idx*2]),sizeof(double)*3*npts);
new_body_pts[idx].resize(3,npts);
new_body_pts[idx].block(0,0,3,npts) = new_body_pts_tmp;
}
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->addContact(num_new_bodies,new_bodies,new_body_pts);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
delete[] new_bodies;
delete[] new_body_pts;
}
else if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="robotnum")
{
size_t num_robot = mxGetNumberOfElements(prhs[2]);
double* robotnum_tmp = new double[num_robot];
int* robotnum = new int[num_robot];
memcpy(robotnum_tmp,mxGetPrSafe(prhs[2]),sizeof(double)*num_robot);
for(int i = 0;i<num_robot;i++)
{
robotnum[i] = (int) robotnum_tmp[i]-1;
}
set<int> robotnumset(robotnum,robotnum+num_robot);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->updateRobotnum(robotnumset);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
delete[] robotnum_tmp;
delete[] robotnum;
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::PostureConstraintType:
{
PostureConstraint* pc = (PostureConstraint*) constraint;
if(field_str=="bounds")
{ // setJointLimits(pc,joint_idx,lb,ub)
size_t num_idx = mxGetM(prhs[2]);
if(!mxIsNumeric(prhs[2]) || mxGetN(prhs[2]) != 1 || !mxIsNumeric(prhs[3]) || mxGetM(prhs[3]) != num_idx || mxGetN(prhs[3]) != 1 || !mxIsNumeric(prhs[4]) || mxGetM(prhs[4]) != num_idx || mxGetN(prhs[4]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","PostureConstraint:joint_idx, lb and ub must be of the same length numerical vector");
}
int* joint_idx = new int[num_idx];
for(int i = 0;i<num_idx;i++)
{
joint_idx[i] = (int) *(mxGetPrSafe(prhs[2])+i)-1;
}
VectorXd lb(num_idx),ub(num_idx);
memcpy(lb.data(),mxGetPrSafe(prhs[3]),sizeof(double)*num_idx);
memcpy(ub.data(),mxGetPrSafe(prhs[4]),sizeof(double)*num_idx);
PostureConstraint* pc_new = new PostureConstraint(*pc);
pc_new->setJointLimits(static_cast<int>(num_idx), joint_idx, lb, ub);
delete[] joint_idx;
plhs[0] = createDrakeConstraintMexPointer((void*)pc_new,"PostureConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","PostureConstraint: argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::AllBodiesClosestDistanceConstraintType:
{
AllBodiesClosestDistanceConstraint* cnst = (AllBodiesClosestDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
AllBodiesClosestDistanceConstraint* cnst_new = new AllBodiesClosestDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"AllBodiesClosestDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","AllBodiesClosestDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldEulerConstraintType:
{
WorldEulerConstraint* cnst = (WorldEulerConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldEulerConstraint* cnst_new = new WorldEulerConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldEulerConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldEulerConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeDirConstraintType:
{
WorldGazeDirConstraint* cnst = (WorldGazeDirConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeDirConstraint* cnst_new = new WorldGazeDirConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeDirConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeDirConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeOrientConstraintType:
{
WorldGazeOrientConstraint* cnst = (WorldGazeOrientConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeOrientConstraint* cnst_new = new WorldGazeOrientConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeOrientConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeOrientConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeTargetConstraintType:
{
WorldGazeTargetConstraint* cnst = (WorldGazeTargetConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeTargetConstraint* cnst_new = new WorldGazeTargetConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeTargetConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeTargetConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeGazeTargetConstraintType:
{
RelativeGazeTargetConstraint* cnst = (RelativeGazeTargetConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeGazeTargetConstraint* cnst_new = new RelativeGazeTargetConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeGazeTargetConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeGazeTargetConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeGazeDirConstraintType:
{
RelativeGazeDirConstraint* cnst = (RelativeGazeDirConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeGazeDirConstraint* cnst_new = new RelativeGazeDirConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeGazeDirConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeGazeDirConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldCoMConstraintType:
{
WorldCoMConstraint* cnst = (WorldCoMConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldCoMConstraint* cnst_new = new WorldCoMConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldCoMConstraint");
}
else if(field_str=="robotnum")
{
size_t num_robot = mxGetNumberOfElements(prhs[2]);
double* robotnum_tmp = new double[num_robot];
int* robotnum = new int[num_robot];
memcpy(robotnum_tmp,mxGetPrSafe(prhs[2]),sizeof(double)*num_robot);
for(int i = 0;i<num_robot;i++)
{
robotnum[i] = (int) robotnum_tmp[i]-1;
}
set<int> robotnumset(robotnum,robotnum+num_robot);
WorldCoMConstraint* cnst_new = new WorldCoMConstraint(*cnst);
cnst_new->updateRobotnum(robotnumset);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldCoMConstraint");
delete[] robotnum_tmp;
delete[] robotnum;
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldCoMConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldPositionConstraintType:
{
WorldPositionConstraint* cnst = (WorldPositionConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldPositionConstraint* cnst_new = new WorldPositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"WorldPositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldPositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldPositionInFrameConstraintType:
{
WorldPositionInFrameConstraint* cnst = (WorldPositionInFrameConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldPositionInFrameConstraint* cnst_new = new WorldPositionInFrameConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"WorldPositionInFrameConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldPositionInFrameConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldQuatConstraintType:
{
WorldQuatConstraint* cnst = (WorldQuatConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldQuatConstraint* cnst_new = new WorldQuatConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldQuatConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldQuatConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::Point2PointDistanceConstraintType:
{
Point2PointDistanceConstraint* cnst = (Point2PointDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
Point2PointDistanceConstraint* cnst_new = new Point2PointDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"Point2PointDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Point2PointDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::Point2LineSegDistConstraintType:
{
Point2LineSegDistConstraint* cnst = (Point2LineSegDistConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
Point2LineSegDistConstraint* cnst_new = new Point2LineSegDistConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"Point2LineSegDistConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Point2LineSegDistConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedPositionConstraintType:
{
WorldFixedPositionConstraint* cnst = (WorldFixedPositionConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedPositionConstraint* cnst_new = new WorldFixedPositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedPositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedPositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedOrientConstraintType:
{
WorldFixedOrientConstraint* cnst = (WorldFixedOrientConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedOrientConstraint* cnst_new = new WorldFixedOrientConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedOrientConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedOrientConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedBodyPoseConstraintType:
{
WorldFixedBodyPoseConstraint* cnst = (WorldFixedBodyPoseConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedBodyPoseConstraint* cnst_new = new WorldFixedBodyPoseConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedBodyPoseConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedBodyPoseConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativePositionConstraintType:
{
RelativePositionConstraint* cnst = static_cast<RelativePositionConstraint*>(constraint);
if(field_str == "robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativePositionConstraint* cnst_new = new RelativePositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativePositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativePositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeQuatConstraintType:
{
RelativeQuatConstraint* cnst = static_cast<RelativeQuatConstraint*>(constraint);
if(field_str == "robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeQuatConstraint* cnst_new = new RelativeQuatConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeQuatConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeQuatConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::MinDistanceConstraintType:
{
MinDistanceConstraint* cnst = (MinDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
MinDistanceConstraint* cnst_new = new MinDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"MinDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","MinDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::GravityCompensationTorqueConstraintType:
{
GravityCompensationTorqueConstraint* cnst = (GravityCompensationTorqueConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
GravityCompensationTorqueConstraint* cnst_new = new GravityCompensationTorqueConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"GravityCompensationTorqueConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","GravityCompensationTorqueConstraint:argument 2 is not accepted");
}
}
break;
default:
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Unsupported constraint type");
break;
}
delete[] field;
}
| 21,317
| 6,729
|
#pragma once
#include "screen.hpp"
class EndScreen : public Screen
{
sf::Sprite &background_sp;
public:
EndScreen(const sf::Font &font, sf::Sprite &background_sp, const sf::Color &fillColor, const sf::Color &outlineColor);
virtual void processEvent(const sf::Event &event);
private:
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};
| 382
| 121
|
#include <any>
#include <complex>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
/**
* C++17 adds `std::any` - a value type that's able to change its type, but while still having
* type safety. std::any accepts an arbitrary type - it holds the contained value and the
* `typeid` of its type - thus there's both a size and a runtime cost, including the possibility
* that std::any might allocate - the implementation should be able to hold small type like int
* without allocating, but larger type (larger than a pointer, two pointers?) will be allocated
* on the heap.
* The underlying type can be checked by comparing against typeid(T),
* value can be accessed via std::any_cast<T>
*/
/*
| Operation | Effect |
| ------------- | ----------------------------------------------------------------- |
| constructors | Create an any object (might call constructor for underlying type) |
| make_any() | Create an any object (passing value(s) to initialize it) |
| destructor | Destroys an any object |
| = | Assign a new value |
| emplace<T>() | Assign a new value having the type T |
| reset() | Destroys any value (makes the object empty) |
| has_value() | Returns whether the object has a value |
| type() | Returns the current type as std::type_info object |
| any_cast<T>() | Use current value as value of type T (exception if other type) |
| swap() | Swaps values between two objects |
*/
int main()
{
// --- construction
// - initialized empty by default, .type() of an empty std::any is equal to typeid(void)
{
std::any a{}; // empty
if (a.type() == typeid(void)) {
std::cerr << "std::any{}.type() == typeid(void)\n";
}
// deduce the type by direct initialization or assignment, deduced type decays
std::any a1{42};
if (a1.type() == typeid(int)) {
std::cerr << "std::any{42}.type() == typeid(int)\n";
}
std::any a2 = "hello any!";
if (a2.type() == typeid(char const*)) {
std::cerr << "std::any{\"hello any!\"} == typeid(char const*)\n";
}
// std::in_place_type can be used for construction, it allows to specify the type
// directly, and avoids copy/move
std::any a3{std::in_place_type<std::string>, "hello any!"};
// note that even the type passed to std::in_place_type decays!
std::any a4{std::in_place_type<char const[6]>, "Hello"};
if (a4.type() == typeid(char const*)) {
std::cerr << "std::any{std::in_place_type<char const[6]>{'hello'} == typeid(char "
"const*) -> decays!\n";
}
// std::make_any - always have to specify the type, also decays
auto a5 = std::make_any<long>(42);
auto a6 = std::make_any<std::string>("hello make_any!");
}
// --- assignment
// values can be assigned using operator=() or .emplace<T>
{
std::any a{};
a = 42; // .type() == typeid(int)
// .emplace()
a.emplace<std::string>("hello emplace");
if (a.type() == typeid(std::string)) {
std::cerr << "a.emplace<std::string> -> value == "
<< std::any_cast<std::string const&>(a) << "\n";
}
// .reset() - makes the std::any empty
a.reset();
if (a.type() == typeid(void)) {
std::cerr << "std::any empty after .reset() -> .type() == typeid(void)\n";
}
}
// --- value access
// check if holds a value using .has_value()
// check type of value using .type() -> std::type_info -> compare against typeid(T)
// access using std::any_cast<T> -> throws std::bad_any_cast if doesn't hold a value
// of the requested type. Can cast to references or pointers
{
std::any a{42};
// casting to an unqualified type, returns by value - copy
auto i = std::any_cast<int>(a);
std::cerr << "std::any holds an int value = " << i << "\n";
a.emplace<std::string>("Hello any_cast");
// we might want to avoid a copy by casting to a const&:
auto const& scr = std::any_cast<std::string const&>(a);
std::cerr << "std::any_cast<std::string const&>(a) = " << scr << "\n";
// casting to a non-const allows us to assign to the value held:
std::any_cast<std::string&>(a) = "Update using any_cast";
std::cerr << "std::any after update, value = " << std::any_cast<std::string const&>(a)
<< "\n";
// We can also move assign the same way
std::string s{"move assign using any_cast"};
std::any_cast<std::string&>(a) = std::move(s);
// using std::any_cast on a pointer to std::any returns a pointer to the held value,
// if the actual type matches the requested type, or nullptr if it doesn't
// this might be a convenient option instead of explicitly checking .type()
// Cast to type `T` when using this from,
// attempting to cast to `T*` will result in the implementation assuming that you're
// expecting the held type to be `T*` (and not `T`)
// attempting to cast to `T&` is an error
auto pi = std::any_cast<int>(&a); // returns nullptr, would throw if used on ref to any
auto ps = std::any_cast<std::string const>(&a); // returns pointer to std::string
if (pi != nullptr ){
std::cerr << "std::any_cast<int>(&a) returned a valid pointer, value = " << *pi << "\n";
}
else {
std::cerr << "std::any_cast<int>(&a) returned a nullptr\n";
}
if (ps != nullptr) {
std::cerr << "std::any_cast<std::string>(&a) returned a valid pointer, value = "
<< *ps << "\n";
}
else {
std::cerr << "std::any_cast<std::string>(&a) returned a nullptr\n";
}
}
}
| 6,230
| 1,814
|
// Copyright 2021 Xilinx Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file
* @brief Defines the VartTensorBuffer class
*/
#ifndef GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
#define GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
#include <stddef.h> // for size_t
#include <cstdint> // for int32_t
#include <memory> // for unique_ptr
#include <string> // for string
#include <vart/experimental/runner_helper.hpp> // for CpuFlatTensorBufferOwned
#include <vector> // for vector
#include <xir/tensor/tensor.hpp> // for Tensor
#include <xir/util/data_type.hpp> // for DataType
#include "proteus/buffers/buffer.hpp"
namespace vart {
class TensorBuffer;
}
namespace proteus {
/**
* @brief VartTensorBuffer uses vart::CpuFlatTensorBufferOwned for storing data
*
*/
class VartTensorBuffer : public Buffer {
public:
VartTensorBuffer(const std::string& name, std::vector<int32_t>& shape,
xir::DataType data_type);
VartTensorBuffer(const char* name, std::vector<int32_t>& shape,
xir::DataType data_type);
/**
* @brief Returns a pointer to the underlying data.
*
* @param index Used to index to the correct tensor in the batch
*
* @return void*
*/
void* data(size_t offset) override;
/**
* @brief Perform any cleanup before returning the buffer to the pool
*/
void reset() override;
/// Get a pointer to the underlying TensorBuffer
vart::TensorBuffer* getTensorBuffer();
private:
std::unique_ptr<xir::Tensor> tensor_;
vart::CpuFlatTensorBufferOwned data_;
};
} // namespace proteus
#endif // GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
| 2,294
| 738
|
//===-- SBFrame.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 <algorithm>
#include <set>
#include <string>
#include "lldb/API/SBFrame.h"
#include "lldb/lldb-types.h"
#include "Utils.h"
#include "lldb/Core/Address.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/StructuredDataImpl.h"
#include "lldb/Core/ValueObjectRegister.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/Expression/ExpressionVariable.h"
#include "lldb/Expression/UserExpression.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/Block.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/StackFrameRecognizer.h"
#include "lldb/Target/StackID.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Instrumentation.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Stream.h"
#include "lldb/API/SBAddress.h"
#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBExpressionOptions.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBStructuredData.h"
#include "lldb/API/SBSymbolContext.h"
#include "lldb/API/SBThread.h"
#include "lldb/API/SBValue.h"
#include "lldb/API/SBVariablesOptions.h"
#include "llvm/Support/PrettyStackTrace.h"
// BEGIN SWIFT
#include "lldb/Target/LanguageRuntime.h"
#ifdef LLDB_ENABLE_SWIFT
#include "Plugins/LanguageRuntime/Swift/SwiftLanguageRuntime.h"
#endif
// END SWIFT
using namespace lldb;
using namespace lldb_private;
SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) {
LLDB_INSTRUMENT_VA(this);
}
SBFrame::SBFrame(const StackFrameSP &lldb_object_sp)
: m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) {
LLDB_INSTRUMENT_VA(this, lldb_object_sp);
}
SBFrame::SBFrame(const SBFrame &rhs) {
LLDB_INSTRUMENT_VA(this, rhs);
m_opaque_sp = clone(rhs.m_opaque_sp);
}
SBFrame::~SBFrame() = default;
const SBFrame &SBFrame::operator=(const SBFrame &rhs) {
LLDB_INSTRUMENT_VA(this, rhs);
if (this != &rhs)
m_opaque_sp = clone(rhs.m_opaque_sp);
return *this;
}
StackFrameSP SBFrame::GetFrameSP() const {
return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP());
}
void SBFrame::SetFrameSP(const StackFrameSP &lldb_object_sp) {
return m_opaque_sp->SetFrameSP(lldb_object_sp);
}
bool SBFrame::IsValid() const {
LLDB_INSTRUMENT_VA(this);
return this->operator bool();
}
SBFrame::operator bool() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock()))
return GetFrameSP().get() != nullptr;
}
// Without a target & process we can't have a valid stack frame.
return false;
}
SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const {
LLDB_INSTRUMENT_VA(this, resolve_scope);
SBSymbolContext sb_sym_ctx;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr())
sb_sym_ctx = frame->GetSymbolContext(scope);
}
}
return sb_sym_ctx;
}
SBModule SBFrame::GetModule() const {
LLDB_INSTRUMENT_VA(this);
SBModule sb_module;
ModuleSP module_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp;
sb_module.SetSP(module_sp);
}
}
}
return sb_module;
}
SBCompileUnit SBFrame::GetCompileUnit() const {
LLDB_INSTRUMENT_VA(this);
SBCompileUnit sb_comp_unit;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_comp_unit.reset(
frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit);
}
}
}
return sb_comp_unit;
}
SBFunction SBFrame::GetFunction() const {
LLDB_INSTRUMENT_VA(this);
SBFunction sb_function;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_function.reset(
frame->GetSymbolContext(eSymbolContextFunction).function);
}
}
}
return sb_function;
}
SBSymbol SBFrame::GetSymbol() const {
LLDB_INSTRUMENT_VA(this);
SBSymbol sb_symbol;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol);
}
}
}
return sb_symbol;
}
SBBlock SBFrame::GetBlock() const {
LLDB_INSTRUMENT_VA(this);
SBBlock sb_block;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block);
}
}
return sb_block;
}
SBBlock SBFrame::GetFrameBlock() const {
LLDB_INSTRUMENT_VA(this);
SBBlock sb_block;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_block.SetPtr(frame->GetFrameBlock());
}
}
return sb_block;
}
SBLineEntry SBFrame::GetLineEntry() const {
LLDB_INSTRUMENT_VA(this);
SBLineEntry sb_line_entry;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_line_entry.SetLineEntry(
frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
}
}
}
return sb_line_entry;
}
uint32_t SBFrame::GetFrameID() const {
LLDB_INSTRUMENT_VA(this);
uint32_t frame_idx = UINT32_MAX;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
frame_idx = frame->GetFrameIndex();
return frame_idx;
}
lldb::addr_t SBFrame::GetCFA() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
return frame->GetStackID().GetCallFrameAddress();
return LLDB_INVALID_ADDRESS;
}
addr_t SBFrame::GetPC() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress(
target, AddressClass::eCode);
}
}
}
return addr;
}
bool SBFrame::SetPC(addr_t new_pc) {
LLDB_INSTRUMENT_VA(this, new_pc);
bool ret_val = false;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
ret_val = reg_ctx_sp->SetPC(new_pc);
}
}
}
}
return ret_val;
}
addr_t SBFrame::GetSP() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
addr = reg_ctx_sp->GetSP();
}
}
}
}
return addr;
}
addr_t SBFrame::GetFP() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
addr = reg_ctx_sp->GetFP();
}
}
}
}
return addr;
}
SBAddress SBFrame::GetPCAddress() const {
LLDB_INSTRUMENT_VA(this);
SBAddress sb_addr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_addr.SetAddress(frame->GetFrameCodeAddress());
}
}
return sb_addr;
}
void SBFrame::Clear() {
LLDB_INSTRUMENT_VA(this);
m_opaque_sp->Clear();
}
lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) {
LLDB_INSTRUMENT_VA(this, var_path);
SBValue sb_value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
sb_value = GetValueForVariablePath(var_path, use_dynamic);
}
return sb_value;
}
lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path,
DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, var_path, use_dynamic);
SBValue sb_value;
if (var_path == nullptr || var_path[0] == '\0') {
return sb_value;
}
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableSP var_sp;
Status error;
ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath(
var_path, eNoDynamicValues,
StackFrame::eExpressionPathOptionCheckPtrVsMember |
StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
var_sp, error));
sb_value.SetSP(value_sp, use_dynamic);
}
}
}
return sb_value;
}
SBValue SBFrame::FindVariable(const char *name) {
LLDB_INSTRUMENT_VA(this, name);
SBValue value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
value = FindVariable(name, use_dynamic);
}
return value;
}
SBValue SBFrame::FindVariable(const char *name,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, name, use_dynamic);
VariableSP var_sp;
SBValue sb_value;
if (name == nullptr || name[0] == '\0') {
return sb_value;
}
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
value_sp = frame->FindVariable(ConstString(name));
if (value_sp)
sb_value.SetSP(value_sp, use_dynamic);
}
}
}
return sb_value;
}
SBValue SBFrame::FindValue(const char *name, ValueType value_type) {
LLDB_INSTRUMENT_VA(this, name, value_type);
SBValue value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
value = FindValue(name, value_type, use_dynamic);
}
return value;
}
SBValue SBFrame::FindValue(const char *name, ValueType value_type,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, name, value_type, use_dynamic);
SBValue sb_value;
if (name == nullptr || name[0] == '\0') {
return sb_value;
}
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableList variable_list;
switch (value_type) {
case eValueTypeVariableGlobal: // global variable
case eValueTypeVariableStatic: // static variable
case eValueTypeVariableArgument: // function argument variables
case eValueTypeVariableLocal: // function local variables
case eValueTypeVariableThreadLocal: // thread local variables
{
SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock));
const bool can_create = true;
const bool get_parent_variables = true;
const bool stop_if_block_is_inlined_function = true;
if (sc.block)
sc.block->AppendVariables(
can_create, get_parent_variables,
stop_if_block_is_inlined_function,
[frame](Variable *v) { return v->IsInScope(frame); },
&variable_list);
if (value_type == eValueTypeVariableGlobal) {
const bool get_file_globals = true;
VariableList *frame_vars = frame->GetVariableList(get_file_globals);
if (frame_vars)
frame_vars->AppendVariablesIfUnique(variable_list);
}
ConstString const_name(name);
VariableSP variable_sp(
variable_list.FindVariable(const_name, value_type));
if (variable_sp) {
value_sp = frame->GetValueObjectForFrameVariable(variable_sp,
eNoDynamicValues);
sb_value.SetSP(value_sp, use_dynamic);
}
} break;
case eValueTypeRegister: // stack frame register value
{
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
if (const RegisterInfo *reg_info =
reg_ctx->GetRegisterInfoByName(name)) {
value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info);
sb_value.SetSP(value_sp);
}
}
} break;
case eValueTypeRegisterSet: // A collection of stack frame register
// values
{
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
const RegisterSet *reg_set = reg_ctx->GetRegisterSet(set_idx);
if (reg_set &&
(llvm::StringRef(reg_set->name).equals_insensitive(name) ||
llvm::StringRef(reg_set->short_name)
.equals_insensitive(name))) {
value_sp =
ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx);
sb_value.SetSP(value_sp);
break;
}
}
}
} break;
case eValueTypeConstResult: // constant result variables
{
ConstString const_name(name);
ExpressionVariableSP expr_var_sp(
target->GetPersistentVariable(const_name));
if (expr_var_sp) {
value_sp = expr_var_sp->GetValueObject();
sb_value.SetSP(value_sp, use_dynamic);
}
} break;
default:
break;
}
}
}
}
return sb_value;
}
bool SBFrame::IsEqual(const SBFrame &that) const {
LLDB_INSTRUMENT_VA(this, that);
lldb::StackFrameSP this_sp = GetFrameSP();
lldb::StackFrameSP that_sp = that.GetFrameSP();
return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID());
}
bool SBFrame::operator==(const SBFrame &rhs) const {
LLDB_INSTRUMENT_VA(this, rhs);
return IsEqual(rhs);
}
bool SBFrame::operator!=(const SBFrame &rhs) const {
LLDB_INSTRUMENT_VA(this, rhs);
return !IsEqual(rhs);
}
SBThread SBFrame::GetThread() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
ThreadSP thread_sp(exe_ctx.GetThreadSP());
SBThread sb_thread(thread_sp);
return sb_thread;
}
const char *SBFrame::Disassemble() const {
LLDB_INSTRUMENT_VA(this);
const char *disassembly = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
disassembly = frame->Disassemble();
}
}
}
return disassembly;
}
SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics,
bool in_scope_only) {
LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
const bool include_runtime_support_values =
target ? target->GetDisplayRuntimeSupportValues() : false;
SBVariablesOptions options;
options.SetIncludeArguments(arguments);
options.SetIncludeLocals(locals);
options.SetIncludeStatics(statics);
options.SetInScopeOnly(in_scope_only);
options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
options.SetUseDynamic(use_dynamic);
value_list = GetVariables(options);
}
return value_list;
}
lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals,
bool statics, bool in_scope_only,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only,
use_dynamic);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
const bool include_runtime_support_values =
target ? target->GetDisplayRuntimeSupportValues() : false;
SBVariablesOptions options;
options.SetIncludeArguments(arguments);
options.SetIncludeLocals(locals);
options.SetIncludeStatics(statics);
options.SetInScopeOnly(in_scope_only);
options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
options.SetUseDynamic(use_dynamic);
return GetVariables(options);
}
SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) {
LLDB_INSTRUMENT_VA(this, options);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
const bool statics = options.GetIncludeStatics();
const bool arguments = options.GetIncludeArguments();
const bool recognized_arguments =
options.GetIncludeRecognizedArguments(SBTarget(exe_ctx.GetTargetSP()));
const bool locals = options.GetIncludeLocals();
const bool in_scope_only = options.GetInScopeOnly();
const bool include_runtime_support_values =
options.GetIncludeRuntimeSupportValues();
const lldb::DynamicValueType use_dynamic = options.GetUseDynamic();
std::set<VariableSP> variable_set;
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableList *variable_list = nullptr;
variable_list = frame->GetVariableList(true);
if (variable_list) {
const size_t num_variables = variable_list->GetSize();
if (num_variables) {
for (const VariableSP &variable_sp : *variable_list) {
if (variable_sp) {
bool add_variable = false;
switch (variable_sp->GetScope()) {
case eValueTypeVariableGlobal:
case eValueTypeVariableStatic:
case eValueTypeVariableThreadLocal:
add_variable = statics;
break;
case eValueTypeVariableArgument:
add_variable = arguments;
break;
case eValueTypeVariableLocal:
add_variable = locals;
break;
default:
break;
}
if (add_variable) {
// Only add variables once so we don't end up with duplicates
if (variable_set.find(variable_sp) == variable_set.end())
variable_set.insert(variable_sp);
else
continue;
if (in_scope_only && !variable_sp->IsInScope(frame))
continue;
ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable(
variable_sp, eNoDynamicValues));
if (!include_runtime_support_values && valobj_sp != nullptr &&
valobj_sp->IsRuntimeSupportValue())
continue;
SBValue value_sb;
value_sb.SetSP(valobj_sp, use_dynamic);
value_list.Append(value_sb);
}
}
}
}
}
if (recognized_arguments) {
auto recognized_frame = frame->GetRecognizedFrame();
if (recognized_frame) {
ValueObjectListSP recognized_arg_list =
recognized_frame->GetRecognizedArguments();
if (recognized_arg_list) {
for (auto &rec_value_sp : recognized_arg_list->GetObjects()) {
SBValue value_sb;
value_sb.SetSP(rec_value_sp, use_dynamic);
value_list.Append(value_sb);
}
}
}
}
}
}
}
return value_list;
}
SBValueList SBFrame::GetRegisters() {
LLDB_INSTRUMENT_VA(this);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
value_list.Append(
ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx));
}
}
}
}
}
return value_list;
}
SBValue SBFrame::FindRegister(const char *name) {
LLDB_INSTRUMENT_VA(this, name);
SBValue result;
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
if (const RegisterInfo *reg_info =
reg_ctx->GetRegisterInfoByName(name)) {
value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info);
result.SetSP(value_sp);
}
}
}
}
}
return result;
}
bool SBFrame::GetDescription(SBStream &description) {
LLDB_INSTRUMENT_VA(this, description);
Stream &strm = description.ref();
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
frame->DumpUsingSettingsFormat(&strm);
}
}
} else
strm.PutCString("No value");
return true;
}
SBValue SBFrame::EvaluateExpression(const char *expr) {
LLDB_INSTRUMENT_VA(this, expr);
SBValue result;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
SBExpressionOptions options;
lldb::DynamicValueType fetch_dynamic_value =
frame->CalculateTarget()->GetPreferDynamicValue();
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(true);
options.SetIgnoreBreakpoints(true);
if (target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
return result;
}
SBValue
SBFrame::EvaluateExpression(const char *expr,
lldb::DynamicValueType fetch_dynamic_value) {
LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value);
SBExpressionOptions options;
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(true);
options.SetIgnoreBreakpoints(true);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (target && target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else if (frame)
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
SBValue SBFrame::EvaluateExpression(const char *expr,
lldb::DynamicValueType fetch_dynamic_value,
bool unwind_on_error) {
LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value, unwind_on_error);
SBExpressionOptions options;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(unwind_on_error);
options.SetIgnoreBreakpoints(true);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (target && target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else if (frame)
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
lldb::SBValue SBFrame::EvaluateExpression(const char *expr,
const SBExpressionOptions &options) {
LLDB_INSTRUMENT_VA(this, expr, options);
Log *expr_log = GetLog(LLDBLog::Expressions);
SBValue expr_result;
if (expr == nullptr || expr[0] == '\0') {
return expr_result;
}
ValueObjectSP expr_value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
std::unique_ptr<llvm::PrettyStackTraceFormat> stack_trace;
if (target->GetDisplayExpressionsInCrashlogs()) {
StreamString frame_description;
frame->DumpUsingSettingsFormat(&frame_description);
stack_trace = std::make_unique<llvm::PrettyStackTraceFormat>(
"SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value "
"= %u) %s",
expr, options.GetFetchDynamicValue(),
frame_description.GetData());
}
target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());
}
}
}
LLDB_LOGF(expr_log,
"** [SBFrame::EvaluateExpression] Expression result is "
"%s, summary %s **",
expr_result.GetValue(), expr_result.GetSummary());
return expr_result;
}
bool SBFrame::IsInlined() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->IsInlined();
}
bool SBFrame::IsInlined() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
if (block)
return block->GetContainingInlinedBlock() != nullptr;
}
}
}
return false;
}
bool SBFrame::IsArtificial() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->IsArtificial();
}
bool SBFrame::IsArtificial() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
return frame->IsArtificial();
return false;
}
const char *SBFrame::GetFunctionName() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->GetFunctionName();
}
lldb::LanguageType SBFrame::GuessLanguage() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
return frame->GuessLanguage();
}
}
}
return eLanguageTypeUnknown;
}
lldb::SBStructuredData SBFrame::GetLanguageSpecificData() const {
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
auto *process = exe_ctx.GetProcessPtr();
auto *frame = exe_ctx.GetFramePtr();
if (process && frame)
if (auto *runtime = process->GetLanguageRuntime(frame->GuessLanguage()))
if (auto *data = runtime->GetLanguageSpecificData(*frame))
return SBStructuredData(*data);
return {};
}
// BEGIN SWIFT
bool SBFrame::IsSwiftThunk() const {
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (!target || !process)
return false;
Process::StopLocker stop_locker;
if (!stop_locker.TryLock(&process->GetRunLock()))
return false;
frame = exe_ctx.GetFramePtr();
if (!frame)
return false;
SymbolContext sc;
sc = frame->GetSymbolContext(eSymbolContextSymbol);
if (!sc.symbol)
return false;
auto *runtime = process->GetLanguageRuntime(eLanguageTypeSwift);
if (!runtime)
return false;
return runtime->IsSymbolARuntimeThunk(*sc.symbol);
}
// END SWIFT
const char *SBFrame::GetFunctionName() const {
LLDB_INSTRUMENT_VA(this);
const char *name = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
eSymbolContextBlock |
eSymbolContextSymbol));
if (sc.block) {
Block *inlined_block = sc.block->GetContainingInlinedBlock();
if (inlined_block) {
const InlineFunctionInfo *inlined_info =
inlined_block->GetInlinedFunctionInfo();
name = inlined_info->GetName().AsCString();
}
}
if (name == nullptr) {
if (sc.function)
name = sc.function->GetName().GetCString();
}
if (name == nullptr) {
if (sc.symbol)
name = sc.symbol->GetName().GetCString();
}
}
}
}
return name;
}
const char *SBFrame::GetDisplayFunctionName() {
LLDB_INSTRUMENT_VA(this);
const char *name = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
eSymbolContextBlock |
eSymbolContextSymbol));
if (sc.block) {
Block *inlined_block = sc.block->GetContainingInlinedBlock();
if (inlined_block) {
const InlineFunctionInfo *inlined_info =
inlined_block->GetInlinedFunctionInfo();
name = inlined_info->GetDisplayName().AsCString();
}
}
if (name == nullptr) {
if (sc.function)
name = sc.function->GetDisplayName().GetCString();
}
if (name == nullptr) {
if (sc.symbol)
name = sc.symbol->GetDisplayName().GetCString();
}
}
}
}
return name;
}
| 39,046
| 12,979
|
//<Snippet1>
using namespace System;
using namespace System::Threading;
public ref class Example
{
private:
// The EventWaitHandle used to demonstrate the difference
// between AutoReset and ManualReset synchronization events.
//
static EventWaitHandle^ ewh;
// A counter to make sure all threads are started and
// blocked before any are released. A Long is used to show
// the use of the 64-bit Interlocked methods.
//
static __int64 threadCount = 0;
// An AutoReset event that allows the main thread to block
// until an exiting thread has decremented the count.
//
static EventWaitHandle^ clearCount =
gcnew EventWaitHandle( false,EventResetMode::AutoReset );
public:
[MTAThread]
static void main()
{
// Create an AutoReset EventWaitHandle.
//
ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
// Create and start five numbered threads. Use the
// ParameterizedThreadStart delegate, so the thread
// number can be passed as an argument to the Start
// method.
for ( int i = 0; i <= 4; i++ )
{
Thread^ t = gcnew Thread(
gcnew ParameterizedThreadStart( ThreadProc ) );
t->Start( i );
}
// Wait until all the threads have started and blocked.
// When multiple threads use a 64-bit value on a 32-bit
// system, you must access the value through the
// Interlocked class to guarantee thread safety.
//
while ( Interlocked::Read( threadCount ) < 5 )
{
Thread::Sleep( 500 );
}
// Release one thread each time the user presses ENTER,
// until all threads have been released.
//
while ( Interlocked::Read( threadCount ) > 0 )
{
Console::WriteLine( L"Press ENTER to release a waiting thread." );
Console::ReadLine();
// SignalAndWait signals the EventWaitHandle, which
// releases exactly one thread before resetting,
// because it was created with AutoReset mode.
// SignalAndWait then blocks on clearCount, to
// allow the signaled thread to decrement the count
// before looping again.
//
WaitHandle::SignalAndWait( ewh, clearCount );
}
Console::WriteLine();
// Create a ManualReset EventWaitHandle.
//
ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
// Create and start five more numbered threads.
//
for ( int i = 0; i <= 4; i++ )
{
Thread^ t = gcnew Thread(
gcnew ParameterizedThreadStart( ThreadProc ) );
t->Start( i );
}
// Wait until all the threads have started and blocked.
//
while ( Interlocked::Read( threadCount ) < 5 )
{
Thread::Sleep( 500 );
}
// Because the EventWaitHandle was created with
// ManualReset mode, signaling it releases all the
// waiting threads.
//
Console::WriteLine( L"Press ENTER to release the waiting threads." );
Console::ReadLine();
ewh->Set();
}
static void ThreadProc( Object^ data )
{
int index = static_cast<Int32>(data);
Console::WriteLine( L"Thread {0} blocks.", data );
// Increment the count of blocked threads.
Interlocked::Increment( threadCount );
// Wait on the EventWaitHandle.
ewh->WaitOne();
Console::WriteLine( L"Thread {0} exits.", data );
// Decrement the count of blocked threads.
Interlocked::Decrement( threadCount );
// After signaling ewh, the main thread blocks on
// clearCount until the signaled thread has
// decremented the count. Signal it now.
//
clearCount->Set();
}
};
//</Snippet1>
| 3,964
| 1,129
|
#include <trees/nodes.h>
#include <trees/trees.h>
#include <analysis/x86_analysis.h>
#include <utility/defines.h>
#include <utility/print_helper.h>
#include <common/utilities.h>
#include <cassert>
#include <fstream>
#include <iostream>
using namespace std;
Comp_Abs_Tree::Comp_Abs_Tree()
: Tree()
{
}
Comp_Abs_Tree::~Comp_Abs_Tree() { }
/* these routines are specific to compound trees which needs traversal of number
of similar trees together. These can be abstracted and lifted to act on
general trees, but as this is the only case we opt to have these specialized
functions
*/
void Comp_Abs_Tree::build_compound_tree_unrolled(
Comp_Abs_Node* comp_node, std::vector<Abs_Node*> abs_nodes)
{
for (int i = 0; i < abs_nodes[0]->srcs.size(); i++) {
vector<Abs_Node*> nodes;
for (int j = 0; j < abs_nodes.size(); j++) {
nodes.push_back(static_cast<Abs_Node*>(abs_nodes[j]->srcs[i]));
}
Comp_Abs_Node* new_node = new Comp_Abs_Node(nodes);
new_node->prev.push_back(comp_node);
new_node->pos.push_back(i);
comp_node->srcs.push_back(new_node);
build_compound_tree_unrolled(new_node, nodes);
}
}
void Comp_Abs_Tree::build_compound_tree_unrolled(
std::vector<Abs_Tree*> abs_trees)
{
if (abs_trees.size() == 0)
return;
vector<Abs_Node*> nodes;
for (int i = 0; i < abs_trees.size(); i++) {
nodes.push_back(static_cast<Abs_Node*>(abs_trees[i]->get_head()));
}
Comp_Abs_Node* comp_node = new Comp_Abs_Node(nodes);
set_head(comp_node);
this->recursive = abs_trees[0]->recursive;
build_compound_tree_unrolled(comp_node, nodes);
}
void Comp_Abs_Tree::traverse_trees(
vector<Abs_Node*> abs_nodes,
vector<pair<vector<Abs_Node*>, vector<int>>>& node_pos)
{
if (abs_nodes.size() == 0)
return;
int order_num = abs_nodes[0]->order_num;
Abs_Node* abs_node = abs_nodes[0];
if (node_pos[order_num].first.size() == 0) {
node_pos[order_num].first = abs_nodes;
for (int i = 0; i < abs_node->srcs.size(); i++) {
node_pos[order_num].second.push_back(abs_node->srcs[i]->order_num);
vector<Abs_Node*> new_srcs;
for (int j = 0; j < abs_nodes.size(); j++) {
new_srcs.push_back(static_cast<Abs_Node*>(abs_nodes[j]->srcs[i]));
}
traverse_trees(new_srcs, node_pos);
}
}
}
void Comp_Abs_Tree::build_compound_tree_exact(std::vector<Abs_Tree*> abs_trees)
{
if (abs_trees.size() == 0)
return;
/* assumption the tree is numbered and the visited state is cleared */
ASSERT_MSG(
(abs_trees[0]->get_head()->order_num != -1),
("ERROR: the concrete tree is not numbered\n"));
ASSERT_MSG(
(abs_trees[0]->get_head()->visited == false),
("ERROR: the visit state of the concrete tree is not cleared\n"));
/* get all the nodes and the nodes to which it is connected */
vector<pair<vector<Abs_Node*>, vector<int>>> tree_map;
tree_map.resize(
abs_trees[0]->num_nodes); /* allocate space for the the nodes */
/* create the set of Abs_Node heads */
vector<Abs_Node*> nodes;
for (int i = 0; i < abs_trees.size(); i++) {
nodes.push_back(static_cast<Abs_Node*>(abs_trees[i]->get_head()));
}
traverse_trees(nodes, tree_map);
/* now create the new tree as a vector */
vector<pair<Comp_Abs_Node*, vector<int>>> new_tree_map;
for (int i = 0; i < new_tree_map.size(); i++) {
new_tree_map.push_back(
make_pair(new Comp_Abs_Node(tree_map[i].first), tree_map[i].second));
}
set_head(new_tree_map[0].first);
/* now create the linkage structure */
for (int i = 0; i < new_tree_map.size(); i++) {
Node* node = new_tree_map[i].first;
vector<int> srcs = new_tree_map[i].second;
for (int j = 0; j < srcs.size(); i++) {
node->srcs.push_back(new_tree_map[srcs[j]].first);
new_tree_map[srcs[j]].first->prev.push_back(node);
new_tree_map[srcs[j]].first->pos.push_back(j);
}
}
}
Comp_Abs_Node* get_indirect_access_node(Comp_Abs_Node* node)
{
if (node->srcs.size() == 0) {
if (node->nodes[0]->mem_info.associated_mem != NULL) {
return node;
} else {
return NULL;
}
}
Comp_Abs_Node* ret;
for (int i = 0; i < node->srcs.size(); i++) {
ret = get_indirect_access_node((Comp_Abs_Node*)node->srcs[i]);
if (ret != NULL)
break;
}
return ret;
}
int32_t is_indirect_access(Comp_Abs_Node* node)
{
int32_t pos = -1;
// is this node indirect?
for (int i = 0; i < node->srcs.size(); i++) {
Comp_Abs_Node* src = (Comp_Abs_Node*)node->srcs[i];
if (src->nodes[0]->operation == op_indirect) {
pos = i;
break;
}
}
return pos;
}
void remove_same_values(bool* deleted_index, vector<vector<double>>& A)
{
deleted_index[A[0].size() - 1] = false;
uint32_t temp_count = 0;
/* check if a particular dimension is the same? */
for (int j = 0; j < A[0].size() - 1; j++) {
bool same = true;
double value = A[0][j];
for (int i = 1; i < A.size(); i++) {
if (abs(value - A[i][j]) > 1e-6) {
same = false;
break;
}
}
/* if same true */
if (same) {
for (int i = 0; i < A.size(); i++) {
A[i].erase(A[i].begin() + j);
}
j--;
}
deleted_index[temp_count++] = same;
}
}
void abstract_buffer_indexes_traversal(Comp_Abs_Node* head, Comp_Abs_Node* node)
{
Abs_Node* first = node->nodes[0];
if (node->visited) {
return;
} else {
node->visited = true;
}
bool indirect = (is_indirect_access(node) != -1);
if (((first->type == Abs_Node::INPUT_NODE)
|| (first->type == Abs_Node::INTERMEDIATE_NODE)
|| (first->type == Abs_Node::OUTPUT_NODE))
&& !indirect) {
/*make a system of linear equations and solve them*/
vector<vector<double>> A;
// for (int i = 0; i < head->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
vector<double> coeff;
for (int j = 0; j < head->nodes[i]->mem_info.dimensions; j++) {
coeff.push_back((double)head->nodes[i]->mem_info.pos[j]);
}
coeff.push_back(1.0);
A.push_back(coeff);
}
printout_matrices(A);
bool* deleted_index = new bool[A[0].size()];
remove_same_values(deleted_index, A);
cout << endl;
printout_matrices(A);
for (int dim = 0; dim < first->mem_info.dimensions; dim++) {
vector<double> b;
// for (int i = 0; i < node->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
b.push_back((double)node->nodes[i]->mem_info.pos[dim]);
}
printout_vector(b);
vector<double> results = solve_linear_eq(A, b);
uint32_t head_dimensions = head->nodes[0]->mem_info.dimensions;
// ASSERT_MSG((results.size() == (first->mem_info.dimensions + 1)),
// ("ERROR: the result vector is inconsistent\n"));
uint32_t tcount = 0;
for (int i = 0; i < head_dimensions + 1; i++) {
if (deleted_index[i] == false) {
first->mem_info.indexes[dim][i] = double_to_int(results[tcount++]);
} else {
first->mem_info.indexes[dim][i] = 0;
}
}
}
} else if (first->type == Abs_Node::IMMEDIATE_INT) {
vector<vector<double>> A;
// for (int i = 0; i < head->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
vector<double> coeff;
for (int j = 0; j < head->nodes[i]->mem_info.dimensions; j++) {
coeff.push_back((double)head->nodes[i]->mem_info.pos[j]);
}
coeff.push_back(1.0);
A.push_back(coeff);
}
// cout << "imm" << endl;
// printout_matrices(A);
bool* deleted_index = new bool[A[0].size()];
remove_same_values(deleted_index, A);
vector<double> b;
first->mem_info.indexes = new int*[1];
first->mem_info.indexes[0]
= new int[head->nodes[0]->mem_info.dimensions + 1];
first->mem_info.dimensions = 1;
first->mem_info.head_dimensions = head->nodes[0]->mem_info.dimensions;
for (int i = 0; i < node->nodes.size(); i++) {
b.push_back((long long)node->nodes[i]->symbol->value);
}
// printout_vector(b);
vector<double> results = solve_linear_eq(A, b);
uint32_t head_dimensions = head->nodes[0]->mem_info.dimensions;
// ASSERT_MSG((results.size() == (first->mem_info.dimensions + 1)), ("ERROR:
// the result vector is inconsistent\n"));
uint32_t tcount = 0;
for (int i = 0; i < head_dimensions + 1; i++) {
if (deleted_index[i] == false) {
first->mem_info.indexes[0][i] = double_to_int(results[tcount++]);
} else {
first->mem_info.indexes[0][i] = 0;
}
}
} else if ((first->type == Abs_Node::SUBTREE_BOUNDARY)) {
return;
}
for (int i = 0; i < node->srcs.size(); i++) {
abstract_buffer_indexes_traversal(
head, static_cast<Comp_Abs_Node*>(node->srcs[i]));
}
}
void Comp_Abs_Tree::abstract_buffer_indexes()
{
Comp_Abs_Node* act_head = static_cast<Comp_Abs_Node*>(get_head());
int32_t pos = is_indirect_access(act_head);
if (pos != -1) {
Comp_Abs_Node* node = static_cast<Comp_Abs_Node*>(act_head->srcs[pos]);
act_head = get_indirect_access_node(node);
DEBUG_PRINT(("indirect head node access\n"), 2);
}
/* assert that the comp node is an input or an intermediate node */
for (int i = 0; i < head->srcs.size(); i++) {
abstract_buffer_indexes_traversal(
act_head, static_cast<Comp_Abs_Node*>(head->srcs[i]));
}
cleanup_visit();
}
Abs_Tree* Comp_Abs_Tree::compound_to_abs_tree()
{
Abs_Node* node = static_cast<Abs_Node*>(
static_cast<Comp_Abs_Node*>(get_head())->nodes[0]);
Abs_Tree* tree = new Abs_Tree();
tree->recursive = recursive;
tree->set_head(node);
return tree;
}
std::string Comp_Abs_Tree::serialize_tree() { throw "not implemented!"; }
void Comp_Abs_Tree::construct_tree(std::string stree)
{
throw "not implemented!";
}
| 9,874
| 3,884
|
// Copyright 2015 Twin Oaks Computing, Inc.
// Modifications copyright (C) 2017-2018 Twin Oaks Computing, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifdef CoreDX_GLIBCXX_USE_CXX11_ABI_ZERO
#define _GLIBCXX_USE_CXX11_ABI 0
#endif
#include <rmw/rmw.h>
#include <rmw/types.h>
#include <rmw/allocators.h>
#include <rmw/error_handling.h>
#include <rmw/impl/cpp/macros.hpp>
#include <dds/dds.hh>
#include <dds/dds_builtinDataReader.hh>
#include "rmw_coredx_cpp/identifier.hpp"
#include "rmw_coredx_types.hpp"
#include "util.hpp"
#if defined(__cplusplus)
extern "C" {
#endif
/* ************************************************
*/
rmw_ret_t
rmw_send_response( const rmw_service_t * service,
rmw_request_id_t * ros_request_header,
void * ros_response )
{
if (!service) {
RMW_SET_ERROR_MSG("service handle is null");
return RMW_RET_ERROR;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
service handle,
service->implementation_identifier, toc_coredx_identifier,
return RMW_RET_ERROR)
if (!ros_request_header) {
RMW_SET_ERROR_MSG("ros request header handle is null");
return RMW_RET_ERROR;
}
if (!ros_response) {
RMW_SET_ERROR_MSG("ros response handle is null");
return RMW_RET_ERROR;
}
CoreDXStaticServiceInfo * service_info =
static_cast<CoreDXStaticServiceInfo *>(service->data);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
void * replier = service_info->replier_;
if (!replier) {
RMW_SET_ERROR_MSG("replier handle is null");
return RMW_RET_ERROR;
}
const service_type_support_callbacks_t * callbacks = service_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
callbacks->send_response(replier, ros_request_header, ros_response);
return RMW_RET_OK;
}
#if defined(__cplusplus)
}
#endif
| 2,463
| 898
|
#ifndef COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__
#define COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__
#include "defines/defaults.hpp"
#include <vector>
namespace CoAP{
namespace Transmission{
namespace Reliable{
#if COAP_TE_RELIABLE_CONNECTION == 1
template<typename Connection>
class connection_list_vector{
public:
using connection_t = Connection;
using handler = typename Connection::handler;
connection_list_vector();
Connection* find(handler socket) noexcept;
Connection* find_free_slot() noexcept;
void close(handler socket) noexcept;
void close_all() noexcept;
Connection* operator[](unsigned index) noexcept;
unsigned ocupied() const noexcept;
unsigned size() const noexcept;
private:
std::vector<Connection> nodes_;
};
#endif /* COAP_TE_RELIABLE_CONNECTION == 1 */
}//CoAP
}//Transmission
}//Reliable
#include "impl/connection_list_vector_impl.hpp"
#endif /* COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__ */
| 999
| 365
|
// Project: libv.update, File: src/libv/update/resource_server/resource_server_state.cpp, Author: Császár Mátyás [Vader]
// hpp
#include <libv/update/resource_server/resource_server_state.lpp>
// libv
//#include <libv/mt/worker_thread_pool.hpp>
#include <libv/algo/linear_find.hpp>
// pro
//#include <libv/update/log.hpp>
//#include <libv/update/resource_server/resource_file.lpp>
//#include <libv/update/resource_server/resource_peer.lpp>
namespace libv {
namespace update {
// -------------------------------------------------------------------------------------------------
void ServerState::join(libv::net::mtcp::Connection<ResourcePeer> peer) {
const auto lock = std::unique_lock(mutex);
if (active_peers.size() < settings_.limit_peer_count_active || settings_.limit_peer_count_active == 0) {
active_peers.emplace(peer);
return;
}
if (queued_peers.size() < settings_.limit_peer_count_queue || settings_.limit_peer_count_queue == 0) {
queued_peers.emplace_back(peer);
return;
}
// peer.connection().send_async(codec.encode(ResponseBusy(load_trend.busy_time())));
}
// void ServerState::inactivity_scan() {
// const auto now = std::chrono::system_clock::now();
//// const auto limit =
//// for (const auto& peer : active_peers)
//// if (peer->last_activity + settings.kick_inactivity_time > now)
//// erase(peer);
// io_context.execute_async([this] {
// inactivity_scan();
// });
// }
void ServerState::leave(libv::net::mtcp::Connection<ResourcePeer> peer) {
const auto lock = std::unique_lock(mutex);
const auto ita = active_peers.find(peer);
if (ita != active_peers.end()) {
// Active peer disconnecting
active_peers.erase(peer);
if (!queued_peers.empty()) {
const auto active_peer_limit_reached = active_peers.size() >= settings_.limit_peer_count_active && settings_.limit_peer_count_active != 0;
if (!active_peer_limit_reached) {
active_peers.emplace(queued_peers.front());
queued_peers.pop_front();
}
}
} else {
// Queued peer disconnecting
queued_peers.erase(libv::linear_find_iterator(queued_peers, peer));
}
}
void ServerState::disconnect_all() {
const auto lock = std::unique_lock(mutex);
for (const auto& peer : queued_peers)
peer.connection().cancel_and_disconnect_async();
for (const auto& peer : active_peers)
peer.connection().cancel_and_disconnect_async();
}
// -------------------------------------------------------------------------------------------------
} // namespace update
} // namespace libv
| 2,503
| 907
|
/*
* 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 <sys/eventfd.h>
#include <numeric>
#include <folly/FileUtil.h>
#include <folly/String.h>
#include <folly/experimental/io/IoUringBackend.h>
#include <folly/experimental/io/test/IoTestTempFileUtil.h>
#include <folly/init/Init.h>
#include <folly/io/async/AsyncUDPServerSocket.h>
#include <folly/io/async/AsyncUDPSocket.h>
#include <folly/io/async/EventHandler.h>
#include <folly/io/async/test/EventBaseTestLib.h>
#include <folly/portability/GTest.h>
// IoUringBackend specific tests
namespace {
class AlignedBuf {
public:
static constexpr size_t kAlign = 4096;
AlignedBuf() = delete;
AlignedBuf(size_t count, char ch) : size_(count) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memset(data_, ch, count);
}
AlignedBuf(const AlignedBuf& buf) : size_(buf.size_) {
if (size_) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memcpy(data_, buf.data_, size_);
}
}
~AlignedBuf() {
if (data_) {
::free(data_);
}
}
AlignedBuf& operator=(const AlignedBuf& buf) {
if (data_) {
::free(data_);
}
size_ = buf.size_;
if (size_) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memcpy(data_, buf.data_, size_);
}
return *this;
}
bool operator==(const AlignedBuf& buf) const {
if (size_ != buf.size_) {
return false;
}
if (size_ == 0) {
return true;
}
return (0 == ::memcmp(data_, buf.data_, size_));
}
bool operator!=(const AlignedBuf& buf) const {
return !(*this == buf);
}
void* data() const {
return data_;
}
size_t size() const {
return size_;
}
private:
void* data_{nullptr};
size_t size_{0};
};
class EventFD : public folly::EventHandler, public folly::EventReadCallback {
public:
EventFD(
bool valid,
uint64_t num,
uint64_t& total,
bool persist,
folly::EventBase* eventBase)
: EventFD(total, valid ? createFd(num) : -1, persist, eventBase) {}
~EventFD() override {
unregisterHandler();
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
void useAsyncReadCallback(bool val) {
if (val) {
setEventCallback(this);
} else {
resetEventCallback();
}
}
// from folly::EventHandler
void handlerReady(uint16_t /*events*/) noexcept override {
// we do not read to leave the fd signalled
++num_;
if (total_ > 0) {
--total_;
}
if (total_ > 0) {
if (!persist_) {
registerHandler(folly::EventHandler::READ);
}
} else {
if (persist_) {
unregisterHandler();
}
}
}
uint64_t getAsyncNum() const {
return asyncNum_;
}
uint64_t getNum() const {
return num_;
}
// from folly::EventReadCallback
folly::EventReadCallback::IoVec* allocateData() override {
auto* ret = ioVecPtr_.release();
return (ret ? ret : new IoVec(this));
}
private:
struct IoVec : public folly::EventReadCallback::IoVec {
IoVec() = delete;
~IoVec() override = default;
explicit IoVec(EventFD* eventFd) {
arg_ = eventFd;
freeFunc_ = IoVec::free;
cbFunc_ = IoVec::cb;
data_.iov_base = &eventData_;
data_.iov_len = sizeof(eventData_);
}
static void free(EventReadCallback::IoVec* ioVec) {
delete ioVec;
}
static void cb(EventReadCallback::IoVec* ioVec, int res) {
reinterpret_cast<EventFD*>(ioVec->arg_)
->cb(reinterpret_cast<IoVec*>(ioVec), res);
}
uint64_t eventData_{0};
};
static int createFd(uint64_t num) {
// we want it a semaphore
// and blocking for the async reads
int fd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE);
CHECK_GT(fd, 0);
CHECK_EQ(folly::writeNoInt(fd, &num, sizeof(num)), sizeof(num));
return fd;
}
EventFD(uint64_t& total, int fd, bool persist, folly::EventBase* eventBase)
: EventHandler(eventBase, folly::NetworkSocket::fromFd(fd)),
total_(total),
fd_(fd),
persist_(persist),
evb_(eventBase) {
if (persist_) {
registerHandler(folly::EventHandler::READ | folly::EventHandler::PERSIST);
} else {
registerHandler(folly::EventHandler::READ);
}
}
void cb(IoVec* ioVec, int res) {
CHECK_EQ(res, sizeof(IoVec::eventData_));
CHECK_EQ(ioVec->eventData_, 1);
// reset it
ioVec->eventData_ = 0;
// save it for future use
ioVecPtr_.reset(ioVec);
++asyncNum_;
if (total_ > 0) {
--total_;
}
if (total_ > 0) {
if (!persist_) {
registerHandler(folly::EventHandler::READ);
}
} else {
if (persist_) {
unregisterHandler();
}
}
}
uint64_t asyncNum_{0};
uint64_t num_{0};
uint64_t& total_;
int fd_{-1};
bool persist_;
folly::EventBase* evb_;
std::unique_ptr<IoVec> ioVecPtr_;
};
std::unique_ptr<folly::EventBase> getEventBase(
folly::PollIoBackend::Options opts) {
try {
auto factory = [opts] {
return std::make_unique<folly::IoUringBackend>(opts);
};
return std::make_unique<folly::EventBase>(
folly::EventBase::Options().setBackendFactory(std::move(factory)));
} catch (const folly::IoUringBackend::NotAvailable&) {
return nullptr;
}
}
void testEventFD(bool overflow, bool persist, bool asyncRead) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
// for overflow == true we use a greater than kBackendCapacity number of
// EventFD instances and lower when overflow == false
size_t kNumEventFds = overflow ? 2048 : 32;
static constexpr size_t kEventFdCount = 16;
auto total = kNumEventFds * kEventFdCount + kEventFdCount / 2;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
std::vector<std::unique_ptr<EventFD>> eventsVec;
eventsVec.reserve(kNumEventFds);
for (size_t i = 0; i < kNumEventFds; i++) {
auto ev = std::make_unique<EventFD>(
true, 2 * kEventFdCount, total, persist, evbPtr.get());
ev->useAsyncReadCallback(asyncRead);
eventsVec.emplace_back(std::move(ev));
}
evbPtr->loop();
for (size_t i = 0; i < kNumEventFds; i++) {
CHECK_GE(
(asyncRead ? eventsVec[i]->getAsyncNum() : eventsVec[i]->getNum()),
kEventFdCount);
}
}
void testInvalidFd(size_t numTotal, size_t numValid, size_t numInvalid) {
static constexpr size_t kBackendCapacity = 128;
static constexpr size_t kBackendMaxSubmit = 64;
auto total = numTotal;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
std::vector<std::unique_ptr<EventFD>> eventsVec;
eventsVec.reserve(numTotal);
for (size_t i = 0; i < numTotal; i++) {
bool valid = (i % (numValid + numInvalid)) < numValid;
eventsVec.emplace_back(std::make_unique<EventFD>(
valid, 1, total, false /*persist*/, evbPtr.get()));
}
evbPtr->loop();
for (size_t i = 0; i < numTotal; i++) {
CHECK_GE(eventsVec[i]->getNum(), 1);
}
}
class EventRecvmsgCallback : public folly::EventRecvmsgCallback {
private:
struct MsgHdr : public folly::EventRecvmsgCallback::MsgHdr {
static auto constexpr kBuffSize = 1024;
MsgHdr() = delete;
~MsgHdr() override = default;
explicit MsgHdr(EventRecvmsgCallback* cb) {
arg_ = cb;
freeFunc_ = MsgHdr::free;
cbFunc_ = MsgHdr::cb;
ioBuf_ = folly::IOBuf::create(kBuffSize);
}
void reset() {
::memset(&data_, 0, sizeof(data_));
iov_.iov_base = ioBuf_->writableData();
iov_.iov_len = kBuffSize;
data_.msg_iov = &iov_;
data_.msg_iovlen = 1;
::memset(&addrStorage_, 0, sizeof(addrStorage_));
data_.msg_name = reinterpret_cast<sockaddr*>(&addrStorage_);
data_.msg_namelen = sizeof(addrStorage_);
}
static void free(folly::EventRecvmsgCallback::MsgHdr* msgHdr) {
delete msgHdr;
}
static void cb(folly::EventRecvmsgCallback::MsgHdr* msgHdr, int res) {
reinterpret_cast<EventRecvmsgCallback*>(msgHdr->arg_)
->cb(reinterpret_cast<MsgHdr*>(msgHdr), res);
}
// data
std::unique_ptr<folly::IOBuf> ioBuf_;
struct iovec iov_;
// addr
struct sockaddr_storage addrStorage_;
};
void cb(MsgHdr* msgHdr, int res) {
// check the number of bytes
CHECK_EQ(res, static_cast<int>(numBytes_));
// check the contents
std::string data;
data.assign(
reinterpret_cast<const char*>(msgHdr->ioBuf_->data()),
static_cast<size_t>(res));
CHECK_EQ(data, data_);
// check the address
folly::SocketAddress addr;
addr.setFromSockaddr(
reinterpret_cast<sockaddr*>(msgHdr->data_.msg_name),
msgHdr->data_.msg_namelen);
CHECK_EQ(addr, addr_);
// reuse the msgHdr
msgHdr_.reset(msgHdr);
++asyncNum_;
if (total_ > 0) {
--total_;
if (total_ == 0) {
evb_->terminateLoopSoon();
}
}
}
public:
EventRecvmsgCallback(
const std::string& data,
const folly::SocketAddress& addr,
size_t numBytes,
uint64_t& total,
folly::EventBase* eventBase)
: data_(data),
addr_(addr),
numBytes_(numBytes),
total_(total),
evb_(eventBase) {}
~EventRecvmsgCallback() override = default;
// from EventRecvmsgCallback
EventRecvmsgCallback::MsgHdr* allocateData() override {
auto* ret = msgHdr_.release();
if (!ret) {
ret = new MsgHdr(this);
}
ret->reset();
return ret;
}
uint64_t getAsyncNum() const {
return asyncNum_;
}
private:
const std::string& data_;
folly::SocketAddress addr_;
size_t numBytes_{0};
uint64_t& total_;
folly::EventBase* evb_;
uint64_t asyncNum_{0};
std::unique_ptr<MsgHdr> msgHdr_;
};
void testAsyncUDPRecvmsg(bool useRegisteredFds) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
static constexpr size_t kNumSockets = 32;
static constexpr size_t kNumBytes = 16;
static constexpr size_t kNumPackets = 32;
auto total = kNumPackets * kNumSockets;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(useRegisteredFds);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
// create the server sockets
std::vector<std::unique_ptr<folly::AsyncUDPServerSocket>> serverSocketVec;
serverSocketVec.reserve(kNumSockets);
std::vector<std::unique_ptr<folly::AsyncUDPSocket>> clientSocketVec;
serverSocketVec.reserve(kNumSockets);
std::vector<std::unique_ptr<EventRecvmsgCallback>> cbVec;
cbVec.reserve(kNumSockets);
std::string data(kNumBytes, 'A');
for (size_t i = 0; i < kNumSockets; i++) {
auto clientSock = std::make_unique<folly::AsyncUDPSocket>(evbPtr.get());
clientSock->bind(folly::SocketAddress("::1", 0));
auto cb = std::make_unique<EventRecvmsgCallback>(
data, clientSock->address(), kNumBytes, total, evbPtr.get());
auto serverSock = std::make_unique<folly::AsyncUDPServerSocket>(
evbPtr.get(),
1500,
folly::AsyncUDPServerSocket::DispatchMechanism::RoundRobin);
// set the event callback
serverSock->setEventCallback(cb.get());
// bind
serverSock->bind(folly::SocketAddress("::1", 0));
// retrieve the real address
folly::SocketAddress addr = serverSock->address();
serverSock->listen();
serverSocketVec.emplace_back(std::move(serverSock));
// connect the client
clientSock->connect(addr);
for (size_t j = 0; j < kNumPackets; j++) {
auto buf = folly::IOBuf::copyBuffer(data.c_str(), data.size());
CHECK_EQ(clientSock->write(addr, std::move(buf)), data.size());
}
clientSocketVec.emplace_back(std::move(clientSock));
cbVec.emplace_back(std::move(cb));
}
evbPtr->loopForever();
for (size_t i = 0; i < kNumSockets; i++) {
CHECK_GE(cbVec[i]->getAsyncNum(), kNumPackets);
}
}
} // namespace
TEST(IoUringBackend, AsyncUDPRecvmsgNoRegisterFd) {
testAsyncUDPRecvmsg(false);
}
TEST(IoUringBackend, AsyncUDPRecvmsgRegisterFd) {
testAsyncUDPRecvmsg(true);
}
TEST(IoUringBackend, EventFD_NoOverflowNoPersist) {
testEventFD(false, false, false);
}
TEST(IoUringBackend, EventFD_OverflowNoPersist) {
testEventFD(true, false, false);
}
TEST(IoUringBackend, EventFD_NoOverflowPersist) {
testEventFD(false, true, false);
}
TEST(IoUringBackend, EventFD_OverflowPersist) {
testEventFD(true, true, false);
}
TEST(IoUringBackend, EventFD_Persist_AsyncRead) {
testEventFD(false, true, true);
}
// 9 valid fds followed by an invalid one
TEST(IoUringBackend, Invalid_fd_9_1) {
testInvalidFd(32, 10, 1);
}
// only invalid fds
TEST(IoUringBackend, Invalid_fd_0_10) {
testInvalidFd(32, 0, 10);
}
// equal distribution
TEST(IoUringBackend, Invalid_fd_5_5) {
testInvalidFd(32, 10, 10);
}
TEST(IoUringBackend, RegisteredFds) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
std::unique_ptr<folly::IoUringBackend> backendReg;
std::unique_ptr<folly::IoUringBackend> backendNoReg;
try {
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(true);
backendReg = std::make_unique<folly::IoUringBackend>(options);
options.setUseRegisteredFds(false);
backendNoReg = std::make_unique<folly::IoUringBackend>(options);
} catch (const folly::IoUringBackend::NotAvailable&) {
}
SKIP_IF(!backendReg) << "Backend not available";
SKIP_IF(!backendNoReg) << "Backend not available";
int eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE | EFD_NONBLOCK);
CHECK_GT(eventFd, 0);
SCOPE_EXIT {
::close(eventFd);
};
// verify for useRegisteredFds = false we get a nullptr FdRegistrationRecord
auto* record = backendNoReg->registerFd(eventFd);
CHECK(!record);
std::vector<folly::IoUringBackend::FdRegistrationRecord*> records;
// we use kBackendCapacity -1 since we can have the timerFd
// already using one fd
records.reserve(kBackendCapacity - 1);
for (size_t i = 0; i < kBackendCapacity - 1; i++) {
record = backendReg->registerFd(eventFd);
CHECK(record);
records.emplace_back(record);
}
// try to allocate one more and check if we get a nullptr
record = backendReg->registerFd(eventFd);
CHECK(!record);
// deallocate and allocate again
for (size_t i = 0; i < records.size(); i++) {
CHECK(backendReg->unregisterFd(records[i]));
record = backendReg->registerFd(eventFd);
CHECK(record);
records[i] = record;
}
}
TEST(IoUringBackend, FileReadWrite) {
static constexpr size_t kBackendCapacity = 2048;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 512;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kBlockSize, 'A'), readData(kBlockSize, 'Z');
std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData),
readDataVec(kNumBlocks, readData);
CHECK(readData != writeData);
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, writeDataVec[i].size());
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, readDataVec[i].size());
CHECK(readDataVec[i] == writeDataVec[i]);
++num;
};
backendPtr->queueRead(
fd,
readDataVec[i].data(),
readDataVec[i].size(),
i * kBlockSize,
std::move(readCb));
};
backendPtr->queueWrite(
fd,
writeDataVec[i].data(),
writeDataVec[i].size(),
i * kBlockSize,
std::move(writeCb));
}
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileReadvWritev) {
static constexpr size_t kBackendCapacity = 2048;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 512;
static constexpr size_t kNumIov = 4;
static constexpr size_t kIovSize = 4096;
static constexpr size_t kBlockSize = kNumIov * kIovSize;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kIovSize, 'A'), readData(kIovSize, 'Z');
std::vector<AlignedBuf> writeDataVec(kNumIov, writeData),
readDataVec(kNumIov, readData);
std::vector<std::vector<AlignedBuf>> writeDataVecVec(
kNumBlocks, writeDataVec),
readDataVecVec(kNumBlocks, readDataVec);
CHECK(readDataVec != writeDataVec);
std::vector<std::vector<struct iovec>> readDataIov, writeDataIov;
std::vector<size_t> lenVec;
readDataIov.reserve(kNumBlocks);
writeDataIov.reserve(kNumBlocks);
lenVec.reserve(kNumBlocks);
for (size_t i = 0; i < kNumBlocks; i++) {
size_t len = 0;
std::vector<struct iovec> readIov, writeIov;
readIov.reserve(kNumIov);
writeIov.reserve(kNumIov);
for (size_t j = 0; j < kNumIov; j++) {
struct iovec riov {
readDataVecVec[i][j].data(), readDataVecVec[i][j].size()
};
readIov.push_back(riov);
struct iovec wiov {
writeDataVecVec[i][j].data(), writeDataVecVec[i][j].size()
};
writeIov.push_back(wiov);
len += riov.iov_len;
}
readDataIov.emplace_back(std::move(readIov));
writeDataIov.emplace_back(std::move(writeIov));
lenVec.emplace_back(len);
}
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, lenVec[i]);
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, lenVec[i]);
CHECK(readDataVecVec[i] == writeDataVecVec[i]);
if (++num == kNumBlocks) {
evbPtr->terminateLoopSoon();
}
};
backendPtr->queueReadv(
fd, readDataIov[i], i * kBlockSize, std::move(readCb));
};
backendPtr->queueWritev(
fd, writeDataIov[i], i * kBlockSize, std::move(writeCb));
}
evbPtr->loopForever();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileReadMany) {
static constexpr size_t kBackendCapacity = 1024;
static constexpr size_t kBackendMaxSubmit = 128;
static constexpr size_t kBackendMaxGet = 128;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 8 * 1024;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kBigBlockSize = 2 * 1024 * 1024;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf readData(kBlockSize, 'Z');
std::vector<AlignedBuf> readDataVec(kNumBlocks, readData);
AlignedBuf bigReadData(kBigBlockSize, 'Z');
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, readDataVec[i].size());
++num;
};
backendPtr->queueRead(
fd,
readDataVec[i].data(),
readDataVec[i].size(),
i * kBlockSize,
std::move(readCb));
}
folly::IoUringBackend::FileOpCallback bigReadCb = [&](int res) {
CHECK_EQ(res, bigReadData.size());
};
backendPtr->queueRead(
fd, bigReadData.data(), bigReadData.size(), 0, std::move(bigReadCb));
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileWriteMany) {
static constexpr size_t kBackendCapacity = 1024;
static constexpr size_t kBackendMaxSubmit = 128;
static constexpr size_t kBackendMaxGet = 128;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 8 * 1024;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kBigBlockSize = 2 * 1024 * 1024;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kBlockSize, 'A');
std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData);
AlignedBuf bigWriteData(kBigBlockSize, 'A');
bool bFdatasync = false;
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, writeDataVec[i].size());
++num;
if (num == kNumBlocks) {
folly::IoUringBackend::FileOpCallback fdatasyncCb = [&](int res) {
CHECK_EQ(res, 0);
bFdatasync = true;
};
backendPtr->queueFdatasync(fd, std::move(fdatasyncCb));
}
};
backendPtr->queueWrite(
fd,
writeDataVec[i].data(),
writeDataVec[i].size(),
i * kBlockSize,
std::move(writeCb));
}
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
EXPECT_EQ(bFdatasync, true);
bool bFsync = false;
folly::IoUringBackend::FileOpCallback bigWriteCb = [&](int res) {
CHECK_EQ(res, bigWriteData.size());
folly::IoUringBackend::FileOpCallback fsyncCb = [&](int res) {
CHECK_EQ(res, 0);
bFsync = true;
};
backendPtr->queueFsync(fd, std::move(fsyncCb));
};
backendPtr->queueWrite(
fd, bigWriteData.data(), bigWriteData.size(), 0, std::move(bigWriteCb));
evbPtr->loop();
EXPECT_EQ(bFsync, true);
}
namespace folly {
namespace test {
static constexpr size_t kCapacity = 16 * 1024;
static constexpr size_t kMaxSubmit = 128;
static constexpr size_t kMaxGet = static_cast<size_t>(-1);
struct IoUringBackendProvider {
static std::unique_ptr<folly::EventBaseBackendBase> getBackend() {
try {
folly::PollIoBackend::Options options;
options.setCapacity(kCapacity)
.setMaxSubmit(kMaxSubmit)
.setMaxGet(kMaxGet)
.setUseRegisteredFds(false);
return std::make_unique<folly::IoUringBackend>(options);
} catch (const IoUringBackend::NotAvailable&) {
return nullptr;
}
}
};
struct IoUringRegFdBackendProvider {
static std::unique_ptr<folly::EventBaseBackendBase> getBackend() {
try {
folly::PollIoBackend::Options options;
options.setCapacity(kCapacity)
.setMaxSubmit(kMaxSubmit)
.setMaxGet(kMaxGet)
.setUseRegisteredFds(true);
return std::make_unique<folly::IoUringBackend>(options);
} catch (const IoUringBackend::NotAvailable&) {
return nullptr;
}
}
};
// Instantiate the non registered fd tests
INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest, IoUringBackendProvider);
INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest1, IoUringBackendProvider);
// Instantiate the registered fd tests
INSTANTIATE_TYPED_TEST_CASE_P(
IoUringRegFd,
EventBaseTest,
IoUringRegFdBackendProvider);
INSTANTIATE_TYPED_TEST_CASE_P(
IoUringRegFd,
EventBaseTest1,
IoUringRegFdBackendProvider);
} // namespace test
} // namespace folly
| 26,474
| 9,937
|
/*
*
* Tencent is pleased to support the open source community by making
* Hippy available.
*
* Copyright (C) 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 "core/napi/jsc/js-native-api-jsc.h"
#include <iostream>
#include <mutex> // NOLINT(build/c++11)
#include <string>
#include "core/base/logging.h"
#include "core/napi/callback-info.h"
#include "core/napi/js-native-api.h"
#include "core/napi/jsc/js-native-api-jsc.h"
#include "core/napi/jsc/js-native-jsc-helper.h"
namespace hippy {
namespace napi {
JSValueRef JsCallbackFunc(JSContextRef ctx,
JSObjectRef function,
JSObjectRef thisObject,
size_t argumentCount,
const JSValueRef arguments[],
JSValueRef* exception_ref) {
void* data = JSObjectGetPrivate(function);
if (!data) {
return JSValueMakeUndefined(ctx);
}
FunctionData* fn_data = reinterpret_cast<FunctionData*>(data);
std::shared_ptr<Scope> scope = fn_data->scope_.lock();
if (!scope) {
return JSValueMakeUndefined(ctx);
}
JsCallback cb = fn_data->callback_;
std::shared_ptr<JSCCtx> context =
std::static_pointer_cast<JSCCtx>(scope->GetContext());
CallbackInfo info(scope);
for (size_t i = 0; i < argumentCount; i++) {
info.AddValue(
std::make_shared<JSCCtxValue>(context->GetCtxRef(), arguments[i]));
}
cb(info);
std::shared_ptr<JSCCtxValue> exception =
std::static_pointer_cast<JSCCtxValue>(info.GetExceptionValue()->Get());
if (exception) {
*exception_ref = exception->value_;
return JSValueMakeUndefined(ctx);
}
std::shared_ptr<JSCCtxValue> ret_value =
std::static_pointer_cast<JSCCtxValue>(info.GetReturnValue()->Get());
if (!ret_value) {
return JSValueMakeUndefined(ctx);
}
JSValueRef valueRef = ret_value->value_;
return valueRef;
}
JSObjectRef RegisterModule(std::shared_ptr<Scope> scope,
JSContextRef ctx,
std::string module_name,
ModuleClass module) {
JSClassDefinition cls_def = kJSClassDefinitionEmpty;
cls_def.className = module_name.c_str();
JSClassRef cls_ref = JSClassCreate(&cls_def);
JSObjectRef module_obj = JSObjectMake(ctx, cls_ref, nullptr);
JSClassRelease(cls_ref);
for (auto fn : module) {
JSClassDefinition fn_def = kJSClassDefinitionEmpty;
fn_def.className = fn.first.c_str();
fn_def.callAsFunction = JsCallbackFunc;
std::unique_ptr<FunctionData> fn_data =
std::make_unique<FunctionData>(scope, fn.second);
JSClassRef fn_ref = JSClassCreate(&fn_def);
JSObjectRef fn_obj =
JSObjectMake(ctx, fn_ref, reinterpret_cast<void*>(fn_data.get()));
JSStringRef fn_str_ref = JSStringCreateWithUTF8CString(fn_def.className);
JSObjectSetProperty(ctx, module_obj, fn_str_ref, fn_obj,
kJSPropertyAttributeReadOnly, nullptr);
JSStringRelease(fn_str_ref);
JSClassRelease(fn_ref);
scope->SaveFunctionData(std::move(fn_data));
}
std::shared_ptr<JSCCtx> context =
std::static_pointer_cast<JSCCtx>(scope->GetContext());
std::shared_ptr<JSCCtxValue> module_value =
std::make_shared<JSCCtxValue>(context->GetCtxRef(), module_obj);
scope->AddModuleValue(module_name, module_value);
return module_obj;
}
std::shared_ptr<VM> CreateVM() {
return std::make_shared<JSCVM>();
}
void DetachThread() {}
void JSCVM::RegisterUncaughtExceptionCallback() {}
std::shared_ptr<Ctx> JSCVM::CreateContext() {
return std::make_shared<JSCCtx>(vm_);
}
JSValueRef GetInternalBinding(JSContextRef ctx,
JSObjectRef function,
JSObjectRef thisObject,
size_t argc,
const JSValueRef argv[],
JSValueRef* exception) {
if (argc <= 0) {
return JSValueMakeNull(ctx);
}
JSValueRef name_ref = argv[0];
if (!JSValueIsString(ctx, name_ref)) {
return JSValueMakeNull(ctx);
}
BindingData* binding_data =
reinterpret_cast<BindingData*>(JSObjectGetPrivate(function));
std::shared_ptr<Scope> scope = binding_data->scope_.lock();
if (!scope) {
return JSValueMakeNull(ctx);
}
JSStringRef name_str_ref = JSValueToStringCopy(ctx, name_ref, exception);
std::string module_name = JsStrToUTF8(name_str_ref);
JSStringRelease(name_str_ref);
std::shared_ptr<JSCCtxValue> module_value =
std::static_pointer_cast<JSCCtxValue>(scope->GetModuleValue(module_name));
if (module_value) {
return module_value->value_;
}
ModuleClassMap module_class_map = binding_data->map_;
auto it = module_class_map.find(module_name);
if (it == module_class_map.end()) {
return JSValueMakeNull(ctx);
}
return RegisterModule(scope, ctx, module_name, it->second);
}
std::shared_ptr<CtxValue> GetInternalBindingFn(std::shared_ptr<Scope> scope) {
std::shared_ptr<JSCCtx> context =
std::static_pointer_cast<JSCCtx>(scope->GetContext());
JSClassDefinition cls_def = kJSClassDefinitionEmpty;
cls_def.callAsFunction = GetInternalBinding;
JSClassRef cls_ref = JSClassCreate(&cls_def);
JSObjectRef functionObject = JSObjectMake(context->GetCtxRef(), cls_ref,
scope->GetBindingData().get());
JSClassRelease(cls_ref);
std::shared_ptr<CtxValue> retValue =
std::make_shared<JSCCtxValue>(context->GetCtxRef(), functionObject);
return retValue;
}
bool JSCCtx::RegisterGlobalInJs() {
JSStringRef global_ref = JSStringCreateWithUTF8CString("global");
JSValueRef exception_ref = nullptr;
JSObjectSetProperty(context_, JSContextGetGlobalObject(context_), global_ref,
JSContextGetGlobalObject(context_),
kJSPropertyAttributeDontDelete, &exception_ref);
std::string exception_str;
if (exception_ref) {
HandleJsException(exception_ref, exception_str);
}
JSStringRelease(global_ref);
return true;
}
bool JSCCtx::SetGlobalVar(const std::string& name, const char* json) {
JSObjectRef global_obj = JSContextGetGlobalObject(context_);
JSStringRef name_ref = JSStringCreateWithUTF8CString(name.c_str());
JSStringRef json_ref = JSStringCreateWithUTF8CString(json);
JSValueRef value_ref = JSValueMakeFromJSONString(context_, json_ref);
JSValueRef exception_ref = nullptr;
JSObjectSetProperty(context_, global_obj, name_ref, value_ref,
kJSPropertyAttributeNone, &exception_ref);
std::string exception_str;
if (exception_ref) {
HandleJsException(exception_ref, exception_str);
}
JSStringRelease(name_ref);
JSStringRelease(json_ref);
if (exception_ref) {
return false;
}
return true;
}
std::shared_ptr<CtxValue> JSCCtx::GetGlobalVar(const std::string& name) {
JSObjectRef global_obj = JSContextGetGlobalObject(context_);
JSStringRef name_ref = JSStringCreateWithUTF8CString(name.c_str());
JSValueRef exception_ref = nullptr;
JSValueRef value_ref =
JSObjectGetProperty(context_, global_obj, name_ref, &exception_ref);
std::string exception_str;
if (exception_ref) {
HandleJsException(exception_ref, exception_str);
}
bool value_is_undefined = JSValueIsUndefined(context_, value_ref);
JSStringRelease(name_ref);
if (value_is_undefined) {
return nullptr;
} else {
std::shared_ptr<JSCCtxValue> jscctx_value =
std::make_shared<JSCCtxValue>(context_, value_ref);
return jscctx_value;
}
}
std::shared_ptr<CtxValue> JSCCtx::GetProperty(
const std::shared_ptr<CtxValue>& object,
const std::string& name) {
CtxValue* value = object.get();
JSCCtxValue* jsc_value = static_cast<JSCCtxValue*>(value);
if (JSValueIsObject(context_, jsc_value->value_)) {
JSObjectRef obj_ref = (JSObjectRef)jsc_value->value_;
JSStringRef name_ref = JSStringCreateWithUTF8CString(name.c_str());
JSValueRef exception_ref = nullptr;
JSValueRef value_ref =
JSObjectGetProperty(context_, obj_ref, name_ref, &exception_ref);
std::string exception_str;
if (exception_ref) {
HandleJsException(exception_ref, exception_str);
}
bool value_is_undefined = JSValueIsUndefined(context_, value_ref);
JSStringRelease(name_ref);
if (value_is_undefined) {
return nullptr;
} else {
std::shared_ptr<JSCCtxValue> jscctx_value =
std::make_shared<JSCCtxValue>(context_, value_ref);
return jscctx_value;
}
}
return nullptr;
}
void JSCCtx::RegisterGlobalModule(std::shared_ptr<Scope> scope,
const ModuleClassMap& module_cls_map) {
std::shared_ptr<JSCCtx> ctx =
std::static_pointer_cast<JSCCtx>(scope->GetContext());
JSGlobalContextRef ctx_ref = ctx->GetCtxRef();
for (const auto& module : module_cls_map) {
RegisterModule(scope, ctx_ref, module.first, module.second);
}
}
void JSCCtx::RegisterNativeBinding(const std::string& name,
hippy::base::RegisterFunction fn,
void* data) {
return;
};
std::shared_ptr<CtxValue> JSCCtx::EvaluateJavascript(
const uint8_t* data,
size_t len,
const char* name,
std::shared_ptr<std::string>* exception) {
if (!data || !len) {
return nullptr;
}
const char* js = reinterpret_cast<const char*>(data);
JSStringRef js_string = JSStringCreateWithUTF8CString(js);
std::string exception_str;
JSValueRef exception_ref = nullptr;
JSStringRef file_name_ref = nullptr;
if (name && strlen(name) > 0) {
file_name_ref = JSStringCreateWithUTF8CString(name);
}
JSValueRef value = JSEvaluateScript(context_, js_string, nullptr,
file_name_ref, 1, &exception_ref);
if (file_name_ref) {
JSStringRelease(file_name_ref);
}
JSStringRelease(js_string);
if (exception_ref) {
HandleJsException(exception_ref, exception_str);
}
if (exception && exception_ref) {
*exception = std::make_shared<std::string>(exception_str);
}
if (!value) {
return nullptr;
}
return std::make_shared<JSCCtxValue>(context_, value);
}
} // namespace napi
} // namespace hippy
| 10,792
| 3,507
|
//===-- UnixSignals.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/UnixSignals.h"
#include "Plugins/Process/Utility/FreeBSDSignals.h"
#include "Plugins/Process/Utility/LinuxSignals.h"
#include "Plugins/Process/Utility/MipsLinuxSignals.h"
#include "Plugins/Process/Utility/NetBSDSignals.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Utility/ArchSpec.h"
using namespace lldb_private;
UnixSignals::Signal::Signal(const char *name, bool default_suppress,
bool default_stop, bool default_notify,
const char *description, const char *alias)
: m_name(name), m_alias(alias), m_description(),
m_suppress(default_suppress), m_stop(default_stop),
m_notify(default_notify) {
if (description)
m_description.assign(description);
}
lldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) {
const auto &triple = arch.GetTriple();
switch (triple.getOS()) {
case llvm::Triple::Linux: {
switch (triple.getArch()) {
case llvm::Triple::mips:
case llvm::Triple::mipsel:
case llvm::Triple::mips64:
case llvm::Triple::mips64el:
return std::make_shared<MipsLinuxSignals>();
default:
return std::make_shared<LinuxSignals>();
}
}
case llvm::Triple::FreeBSD:
case llvm::Triple::OpenBSD:
return std::make_shared<FreeBSDSignals>();
case llvm::Triple::NetBSD:
return std::make_shared<NetBSDSignals>();
default:
return std::make_shared<UnixSignals>();
}
}
lldb::UnixSignalsSP UnixSignals::CreateForHost() {
static lldb::UnixSignalsSP s_unix_signals_sp =
Create(HostInfo::GetArchitecture());
return s_unix_signals_sp;
}
// UnixSignals constructor
UnixSignals::UnixSignals() { Reset(); }
UnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {}
UnixSignals::~UnixSignals() = default;
void UnixSignals::Reset() {
// This builds one standard set of Unix Signals. If yours aren't quite in
// this order, you can either subclass this class, and use Add & Remove to
// change them or you can subclass and build them afresh in your constructor.
//
// Note: the signals below are the Darwin signals. Do not change these!
m_signals.clear();
// clang-format off
// SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION
// ====== ============ ======== ====== ====== ===================================================
AddSignal(1, "SIGHUP", false, true, true, "hangup");
AddSignal(2, "SIGINT", true, true, true, "interrupt");
AddSignal(3, "SIGQUIT", false, true, true, "quit");
AddSignal(4, "SIGILL", false, true, true, "illegal instruction");
AddSignal(5, "SIGTRAP", true, true, true, "trace trap (not reset when caught)");
AddSignal(6, "SIGABRT", false, true, true, "abort()");
AddSignal(7, "SIGEMT", false, true, true, "pollable event");
AddSignal(8, "SIGFPE", false, true, true, "floating point exception");
AddSignal(9, "SIGKILL", false, true, true, "kill");
AddSignal(10, "SIGBUS", false, true, true, "bus error");
AddSignal(11, "SIGSEGV", false, true, true, "segmentation violation");
AddSignal(12, "SIGSYS", false, true, true, "bad argument to system call");
AddSignal(13, "SIGPIPE", false, false, false, "write on a pipe with no one to read it");
AddSignal(14, "SIGALRM", false, false, false, "alarm clock");
AddSignal(15, "SIGTERM", false, true, true, "software termination signal from kill");
AddSignal(16, "SIGURG", false, false, false, "urgent condition on IO channel");
AddSignal(17, "SIGSTOP", true, true, true, "sendable stop signal not from tty");
AddSignal(18, "SIGTSTP", false, true, true, "stop signal from tty");
AddSignal(19, "SIGCONT", false, true, true, "continue a stopped process");
AddSignal(20, "SIGCHLD", false, false, false, "to parent on child stop or exit");
AddSignal(21, "SIGTTIN", false, true, true, "to readers process group upon background tty read");
AddSignal(22, "SIGTTOU", false, true, true, "to readers process group upon background tty write");
AddSignal(23, "SIGIO", false, false, false, "input/output possible signal");
AddSignal(24, "SIGXCPU", false, true, true, "exceeded CPU time limit");
AddSignal(25, "SIGXFSZ", false, true, true, "exceeded file size limit");
AddSignal(26, "SIGVTALRM", false, false, false, "virtual time alarm");
AddSignal(27, "SIGPROF", false, false, false, "profiling time alarm");
AddSignal(28, "SIGWINCH", false, false, false, "window size changes");
AddSignal(29, "SIGINFO", false, true, true, "information request");
AddSignal(30, "SIGUSR1", false, true, true, "user defined signal 1");
AddSignal(31, "SIGUSR2", false, true, true, "user defined signal 2");
// clang-format on
}
void UnixSignals::AddSignal(int signo, const char *name, bool default_suppress,
bool default_stop, bool default_notify,
const char *description, const char *alias) {
Signal new_signal(name, default_suppress, default_stop, default_notify,
description, alias);
m_signals.insert(std::make_pair(signo, new_signal));
++m_version;
}
void UnixSignals::RemoveSignal(int signo) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
m_signals.erase(pos);
++m_version;
}
const char *UnixSignals::GetSignalAsCString(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos == m_signals.end())
return nullptr;
else
return pos->second.m_name.GetCString();
}
bool UnixSignals::SignalIsValid(int32_t signo) const {
return m_signals.find(signo) != m_signals.end();
}
ConstString UnixSignals::GetShortName(ConstString name) const {
if (name)
return ConstString(name.GetStringRef().substr(3)); // Remove "SIG" from name
return name;
}
int32_t UnixSignals::GetSignalNumberFromName(const char *name) const {
ConstString const_name(name);
collection::const_iterator pos, end = m_signals.end();
for (pos = m_signals.begin(); pos != end; pos++) {
if ((const_name == pos->second.m_name) ||
(const_name == pos->second.m_alias) ||
(const_name == GetShortName(pos->second.m_name)) ||
(const_name == GetShortName(pos->second.m_alias)))
return pos->first;
}
const int32_t signo =
StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return signo;
return LLDB_INVALID_SIGNAL_NUMBER;
}
int32_t UnixSignals::GetFirstSignalNumber() const {
if (m_signals.empty())
return LLDB_INVALID_SIGNAL_NUMBER;
return (*m_signals.begin()).first;
}
int32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const {
collection::const_iterator pos = m_signals.find(current_signal);
collection::const_iterator end = m_signals.end();
if (pos == end)
return LLDB_INVALID_SIGNAL_NUMBER;
else {
pos++;
if (pos == end)
return LLDB_INVALID_SIGNAL_NUMBER;
else
return pos->first;
}
}
const char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress,
bool &should_stop,
bool &should_notify) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos == m_signals.end())
return nullptr;
else {
const Signal &signal = pos->second;
should_suppress = signal.m_suppress;
should_stop = signal.m_stop;
should_notify = signal.m_notify;
return signal.m_name.AsCString("");
}
}
bool UnixSignals::GetShouldSuppress(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_suppress;
return false;
}
bool UnixSignals::SetShouldSuppress(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_suppress = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldSuppress(signo, value);
return false;
}
bool UnixSignals::GetShouldStop(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_stop;
return false;
}
bool UnixSignals::SetShouldStop(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_stop = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldStop(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldStop(signo, value);
return false;
}
bool UnixSignals::GetShouldNotify(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_notify;
return false;
}
bool UnixSignals::SetShouldNotify(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_notify = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldNotify(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldNotify(signo, value);
return false;
}
int32_t UnixSignals::GetNumSignals() const { return m_signals.size(); }
int32_t UnixSignals::GetSignalAtIndex(int32_t index) const {
if (index < 0 || m_signals.size() <= static_cast<size_t>(index))
return LLDB_INVALID_SIGNAL_NUMBER;
auto it = m_signals.begin();
std::advance(it, index);
return it->first;
}
uint64_t UnixSignals::GetVersion() const { return m_version; }
std::vector<int32_t>
UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress,
llvm::Optional<bool> should_stop,
llvm::Optional<bool> should_notify) {
std::vector<int32_t> result;
for (int32_t signo = GetFirstSignalNumber();
signo != LLDB_INVALID_SIGNAL_NUMBER;
signo = GetNextSignalNumber(signo)) {
bool signal_suppress = false;
bool signal_stop = false;
bool signal_notify = false;
GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify);
// If any of filtering conditions are not met, we move on to the next
// signal.
if (should_suppress.hasValue() &&
signal_suppress != should_suppress.getValue())
continue;
if (should_stop.hasValue() && signal_stop != should_stop.getValue())
continue;
if (should_notify.hasValue() && signal_notify != should_notify.getValue())
continue;
result.push_back(signo);
}
return result;
}
| 11,683
| 4,062
|
#pragma once
#include <kizunano/lib/errors.hpp>
namespace nano
{
class jsonconfig;
class tomlconfig;
class opencl_config
{
public:
opencl_config () = default;
opencl_config (unsigned, unsigned, unsigned);
nano::error serialize_json (nano::jsonconfig &) const;
nano::error deserialize_json (nano::jsonconfig &);
nano::error serialize_toml (nano::tomlconfig &) const;
nano::error deserialize_toml (nano::tomlconfig &);
unsigned platform{ 0 };
unsigned device{ 0 };
unsigned threads{ 1024 * 1024 };
};
}
| 512
| 188
|
#ifndef OBJECT_COUNTER_H
#define OBJECT_COUNTER_H
#include <cstddef>
/**
* @brief Template class for couynting the number of objects of type T created and
* currently allocated (a.k.a. the number of objects that are "alive").
*/
template< class T >
class ObjectCounter
{
public:
ObjectCounter()
{
++m_numCreated;
++m_numAlive;
}
ObjectCounter( const ObjectCounter& )
{
++m_numCreated;
++m_numAlive;
}
std::size_t numCreated() const noexcept
{
return m_numCreated;
}
std::size_t numAlive() const noexcept
{
return m_numAlive;
}
protected:
/// @note Objects should never be removed through pointers of this type
~ObjectCounter()
{
--m_numAlive;
}
private:
static std::size_t m_numCreated;
static std::size_t m_numAlive;
};
template< class T > std::size_t ObjectCounter<T>::m_numCreated = 0;
template< class T > std::size_t ObjectCounter<T>::m_numAlive = 0;
#endif // OBJECT_COUNTER_H
| 1,029
| 362
|
//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
// Enable this macro to debug bugpoint itself.
//#define DEBUG_BUGPOINT 1
using namespace llvm;
static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
"on program to find bugs"),
cl::init(false));
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
static cl::opt<unsigned> TimeoutValue(
"timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
static cl::opt<int> MemoryLimit(
"mlimit", cl::init(-1), cl::value_desc("MBytes"),
cl::desc("Maximum amount of memory to use. 0 disables check. Defaults to "
"400MB (800MB under valgrind, 0 with sanitizers)."));
static cl::opt<bool>
UseValgrind("enable-valgrind",
cl::desc("Run optimizations through valgrind"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo *, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
static cl::opt<bool>
StandardLinkOpts("std-link-opts",
cl::desc("Include the standard link time optimizations"));
static cl::opt<bool>
OptLevelO1("O1", cl::desc("Optimization level 1. Identical to 'opt -O1'"));
static cl::opt<bool>
OptLevelO2("O2", cl::desc("Optimization level 2. Identical to 'opt -O2'"));
static cl::opt<bool> OptLevelOs(
"Os",
cl::desc(
"Like -O2 with extra optimizations for size. Similar to clang -Os"));
static cl::opt<bool>
OptLevelO3("O3", cl::desc("Optimization level 3. Identical to 'opt -O3'"));
static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));
/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;
#ifndef DEBUG_BUGPOINT
static void BugpointInterruptFunction() { BugpointIsInterrupted = true; }
#endif
// Hack to capture a pass list.
namespace {
class AddToDriver : public legacy::FunctionPassManager {
BugDriver &D;
public:
AddToDriver(BugDriver &_D) : FunctionPassManager(nullptr), D(_D) {}
void add(Pass *P) override {
const void *ID = P->getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
D.addPass(PI->getPassArgument());
}
};
}
#ifdef LINK_POLLY_INTO_TOOLS
namespace polly {
void initializePollyPasses(llvm::PassRegistry &Registry);
}
#endif
int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
InitLLVM X(argc, argv);
#endif
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeAggressiveInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
#ifdef LINK_POLLY_INTO_TOOLS
polly::initializePollyPasses(Registry);
#endif
if (std::getenv("bar") == (char*) -1) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
}
cl::ParseCommandLineOptions(argc, argv,
"LLVM automatic testcase reducer. See\nhttp://"
"llvm.org/cmds/bugpoint.html"
" for more information.\n");
#ifndef DEBUG_BUGPOINT
sys::SetInterruptFunction(BugpointInterruptFunction);
#endif
LLVMContext Context;
// If we have an override, set it and then track the triple we want Modules
// to use.
if (!OverrideTriple.empty()) {
TargetTriple.setTriple(Triple::normalize(OverrideTriple));
outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
}
if (MemoryLimit < 0) {
// Set the default MemoryLimit. Be sure to update the flag's description if
// you change this.
if (sys::RunningOnValgrind() || UseValgrind)
MemoryLimit = 800;
else
MemoryLimit = 400;
#if (LLVM_ADDRESS_SANITIZER_BUILD || LLVM_MEMORY_SANITIZER_BUILD || \
LLVM_THREAD_SANITIZER_BUILD)
// Starting from kernel 4.9 memory allocated with mmap is counted against
// RLIMIT_DATA. Sanitizers need to allocate tens of terabytes for shadow.
MemoryLimit = 0;
#endif
}
BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit, UseValgrind,
Context);
if (D.addSources(InputFilenames))
return 1;
AddToDriver PM(D);
if (StandardLinkOpts) {
PassManagerBuilder Builder;
Builder.Inliner = createFunctionInliningPass();
Builder.populateLTOPassManager(PM);
}
if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
PassManagerBuilder Builder;
if (OptLevelO1)
Builder.Inliner = createAlwaysInlinerLegacyPass();
else if (OptLevelOs || OptLevelO2)
Builder.Inliner = createFunctionInliningPass(
2, OptLevelOs ? 1 : 0, false);
else
Builder.Inliner = createFunctionInliningPass(275);
Builder.populateFunctionPassManager(PM);
Builder.populateModulePassManager(PM);
}
for (const PassInfo *PI : PassList)
D.addPass(PI->getPassArgument());
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
sys::Process::PreventCoreFiles();
#endif
if (Error E = D.run()) {
errs() << toString(std::move(E));
return 1;
}
return 0;
}
| 7,066
| 2,284
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkGLContext.h"
SkGLContext::SkGLContext()
: fFBO(0)
, fGL(NULL) {
}
SkGLContext::~SkGLContext() {
SkSafeUnref(fGL);
}
bool SkGLContext::init(int width, int height) {
if (fGL) {
fGL->unref();
this->destroyGLContext();
}
fGL = this->createGLContext();
if (fGL) {
// clear any existing GL erorrs
GrGLenum error;
do {
error = SK_GL(*this, GetError());
} while (GR_GL_NO_ERROR != error);
GrGLuint cbID;
GrGLuint dsID;
SK_GL(*this, GenFramebuffers(1, &fFBO));
SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
SK_GL(*this, GenRenderbuffers(1, &cbID));
SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, cbID));
if (fGL->supportsES2()) {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_RGBA8,
width, height));
} else {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_RGBA,
width, height));
}
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_COLOR_ATTACHMENT0,
GR_GL_RENDERBUFFER,
cbID));
SK_GL(*this, GenRenderbuffers(1, &dsID));
SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, dsID));
if (fGL->supportsES2()) {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_STENCIL_INDEX8,
width, height));
} else {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_DEPTH_STENCIL,
width, height));
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_DEPTH_ATTACHMENT,
GR_GL_RENDERBUFFER,
dsID));
}
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_STENCIL_ATTACHMENT,
GR_GL_RENDERBUFFER,
dsID));
SK_GL(*this, Viewport(0, 0, width, height));
SK_GL(*this, ClearStencil(0));
SK_GL(*this, Clear(GR_GL_STENCIL_BUFFER_BIT));
error = SK_GL(*this, GetError());
GrGLenum status =
SK_GL(*this, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
if (GR_GL_FRAMEBUFFER_COMPLETE != status ||
GR_GL_NO_ERROR != error) {
fFBO = 0;
fGL->unref();
fGL = NULL;
this->destroyGLContext();
return false;
} else {
return true;
}
}
return false;
}
| 3,271
| 981
|
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "../../unittests.h"
#include "../../../../uidescription/uiviewfactory.h"
#include "../../../../uidescription/uiattributes.h"
#include "../../../../uidescription/detail/uiviewcreatorattributes.h"
#include "../../../../uidescription/uiviewswitchcontainer.h"
#include "../../../../lib/cstring.h"
#include "helpers.h"
namespace VSTGUI {
using namespace UIViewCreator;
TESTCASE(UIViewSwitchContainerCreatorTest,
TEST(templateNames,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrTemplateNames, "temp1,temp2", &uidesc, [] (UIViewSwitchContainer* v) {
auto controller = dynamic_cast<UIDescriptionViewSwitchController*> (v->getController ());
EXPECT(controller);
std::string str;
controller->getTemplateNames(str);
return str == "temp1,temp2";
});
);
TEST(templateSwitchControl,
DummyUIDescription uidesc;
uidesc.tag = 12345;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrTemplateSwitchControl, kTagName, &uidesc, [&] (UIViewSwitchContainer* v) {
auto controller = dynamic_cast<UIDescriptionViewSwitchController*> (v->getController ());
EXPECT(controller);
return controller->getSwitchControlTag() == uidesc.tag;
}, true);
);
TEST(animationStyle,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "fade", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kFadeInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "move", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kMoveInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "push", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kPushInOut;
});
);
TEST(animationTime,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTime, 1234, &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationTime() == 1234;
});
);
TEST(animationStyleValues,
DummyUIDescription uidesc;
testPossibleValues (kUIViewSwitchContainer, kAttrAnimationStyle, &uidesc, {"fade", "move", "push"});
);
TEST(animationTimingFunction,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "linear", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kLinear;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-in", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyIn;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-out", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-in-out", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasy;
});
);
TEST(animationTimingFunctionValues,
DummyUIDescription uidesc;
testPossibleValues (kUIViewSwitchContainer, kAttrAnimationTimingFunction, &uidesc, {"linear", "easy-in", "easy-out", "easy-in-out", "easy"});
);
);
} // VSTGUI
| 3,924
| 1,278
|
// File: Text.hpp
// Author: Bob Rubbens - Knights of the Compiler
// Creation date: 2014-07-21
// Contact: http://plusminos.nl - @broervanlisa - gmail (bobrubbens)
#ifndef NNB_TEXT_HPP
#define NNB_TEXT_HPP
// Public
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <string>
#include <memory>
// Private
#include "nnb/graphics/TextureContainer.hpp"
#include "nnb/graphics/Color.hpp"
#include "nnb/resources/CustomDeleters.hpp"
namespace nnb {
enum class HAlign {
LEFT,
CENTER,
RIGHT
} ;
enum class VAlign {
TOP,
CENTER,
BOTTOM
} ;
class Text {
public:
Text();
Text(SDL_Renderer* tgt_, bool autoCommit_ = true);
Text(const Text& other);
Text& operator=(const Text& rhs);
void setText(std::string text_);
void setFont(TTF_Font *font_);
void setPosition(int x_, int y_);
void setX(int x_);
void setY(int y_);
void setHAlign(HAlign align_);
void setVAlign(VAlign align_);
void setColor(SDL_Color clr_);
void setColor(int r, int g, int b);
void setColor(nnb::Color clr_);
void setAlpha(Uint8 alpha_);
void setAutoCommit(bool autoCommit_);
void calculateBounds();
void commit();
void render() const;
int getWidth() const;
int getHeight() const;
int getX() const;
int getY() const;
SDL_Rect getBounds() const;
private:
bool autoCommit;
int x = 0, y = 0;
TTF_Font *font = NULL;
std::string text = "";
HAlign halign;
VAlign valign;
nnb::TextureContainer txt;
SDL_Renderer *tgt;
SDL_Rect dst;
SDL_Color clr;
bool dirty = false;
std::unique_ptr<SDL_Texture, nnb::SDLDeleter> txtTexture;
} ;
}
#endif
| 1,695
| 736
|
#pragma once
#include <fstream>
#include <string>
#include "simeng/version.hh"
#include "yaml-cpp/yaml.h"
namespace simeng {
class SpecialFileDirGen {
public:
/** Construct a SpecialFileDirGen class by reading in the YAML file and
* running it through checks and formatting. */
SpecialFileDirGen(YAML::Node config);
/** Removes all files inside the '/src.lib/kernel/specialFiles' directory. */
void RemoveExistingSFDir();
/** Creates necessary file structure to support needed special files inside
* the '/src.lib/kernel/specialFiles' directory. */
void GenerateSFDir();
private:
/** Path to the root of the SimEng special files directory. */
const std::string specialFilesDir_ =
SIMENG_SOURCE_DIR "/src/lib/kernel/specialFiles";
/** Values declared in YAML config file needed to create the Special Files
* Directory tree. */
uint64_t core_count;
uint64_t smt;
uint64_t socket_count;
float bogoMIPS;
std::string features;
std::string cpu_implementer;
uint64_t cpu_architecture;
std::string cpu_variant;
std::string cpu_part;
uint64_t cpu_revision;
uint64_t package_count;
}; // namespace SpecialFilesDirGen
} // namespace simeng
| 1,196
| 380
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/common.h>
#include <ode/matrix.h>
#include "config.h"
#include "util.h"
// misc defines
#define ALLOCA dALLOCA16
void _dSetZero (dReal *a, int n)
{
dAASSERT (a && n >= 0);
dReal *acurr = a;
int ncurr = n;
while (ncurr > 0) {
*(acurr++) = 0;
--ncurr;
}
}
void _dSetValue (dReal *a, int n, dReal value)
{
dAASSERT (a && n >= 0);
dReal *acurr = a;
int ncurr = n;
while (ncurr > 0) {
*(acurr++) = value;
--ncurr;
}
}
void _dMultiply0 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int qskip = dPAD(q);
const int rskip = dPAD(r);
dReal *aa = A;
const dReal *bb = B;
for (int i=p; i; aa+=rskip, bb+=qskip, --i) {
dReal *a = aa;
const dReal *cc = C, *ccend = C + r;
for (; cc != ccend; ++a, ++cc) {
dReal sum = REAL(0.0);
const dReal *c = cc;
const dReal *b = bb, *bend = bb + q;
for (; b != bend; c+=rskip, ++b) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
void _dMultiply1 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int pskip = dPAD(p);
const int rskip = dPAD(r);
dReal *aa = A;
const dReal *bb = B, *bbend = B + p;
for (; bb != bbend; aa += rskip, ++bb) {
dReal *a = aa;
const dReal *cc = C, *ccend = C + r;
for (; cc != ccend; ++a, ++cc) {
dReal sum = REAL(0.0);
const dReal *b = bb, *c = cc;
for (int k=q; k; b+=pskip, c+=rskip, --k) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
void _dMultiply2 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int rskip = dPAD(r);
const int qskip = dPAD(q);
dReal *aa = A;
const dReal *bb = B;
for (int i=p; i; aa+=rskip, bb+=qskip, --i) {
dReal *a = aa, *aend = aa + r;
const dReal *cc = C;
for (; a != aend; cc+=qskip, ++a) {
dReal sum = REAL(0.0);
const dReal *b = bb, *c = cc, *cend = cc + q;
for (; c != cend; ++b, ++c) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
int _dFactorCholesky (dReal *A, int n, void *tmpbuf/*[n]*/)
{
dAASSERT (n > 0 && A);
bool failure = false;
const int nskip = dPAD (n);
dReal *recip = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (n * sizeof(dReal));
dReal *aa = A;
for (int i=0; i<n; aa+=nskip, ++i) {
dReal *cc = aa;
{
const dReal *bb = A;
for (int j=0; j<i; bb+=nskip, ++cc, ++j) {
dReal sum = *cc;
const dReal *a = aa, *b = bb, *bend = bb + j;
for (; b != bend; ++a, ++b) {
sum -= (*a)*(*b);
}
*cc = sum * recip[j];
}
}
{
dReal sum = *cc;
dReal *a = aa, *aend = aa + i;
for (; a != aend; ++a) {
sum -= (*a)*(*a);
}
if (sum <= REAL(0.0)) {
failure = true;
break;
}
dReal sumsqrt = dSqrt(sum);
*cc = sumsqrt;
recip[i] = dRecip (sumsqrt);
}
}
return failure ? 0 : 1;
}
void _dSolveCholesky (const dReal *L, dReal *b, int n, void *tmpbuf/*[n]*/)
{
dAASSERT (n > 0 && L && b);
const int nskip = dPAD (n);
dReal *y = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (n*sizeof(dReal));
{
const dReal *ll = L;
for (int i=0; i<n; ll+=nskip, ++i) {
dReal sum = REAL(0.0);
for (int k=0; k < i; ++k) {
sum += ll[k]*y[k];
}
dIASSERT(ll[i] != dReal(0.0));
y[i] = (b[i]-sum)/ll[i];
}
}
{
const dReal *ll = L + (n - 1) * (nskip + 1);
for (int i=n-1; i>=0; ll-=nskip+1, --i) {
dReal sum = REAL(0.0);
const dReal *l = ll + nskip;
for (int k=i+1; k<n; l+=nskip, ++k) {
sum += (*l)*b[k];
}
dIASSERT(*ll != dReal(0.0));
b[i] = (y[i]-sum)/(*ll);
}
}
}
int _dInvertPDMatrix (const dReal *A, dReal *Ainv, int n, void *tmpbuf/*[nskip*(n+2)]*/)
{
dAASSERT (n > 0 && A && Ainv);
bool success = false;
size_t FactorCholesky_size = _dEstimateFactorCholeskyTmpbufSize(n);
size_t SolveCholesky_size = _dEstimateSolveCholeskyTmpbufSize(n);
size_t MaxCholesky_size = FactorCholesky_size > SolveCholesky_size ? FactorCholesky_size : SolveCholesky_size;
dIASSERT(MaxCholesky_size % sizeof(dReal) == 0);
const int nskip = dPAD (n);
const int nskip_mul_n = nskip*n;
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (MaxCholesky_size + (nskip + nskip_mul_n)*sizeof(dReal));
dReal *X = (dReal *)((char *)tmp + MaxCholesky_size);
dReal *L = X + nskip;
memcpy (L, A, nskip_mul_n*sizeof(dReal));
if (dFactorCholesky (L,n,tmp)) {
dSetZero (Ainv,nskip_mul_n); // make sure all padding elements set to 0
dReal *aa = Ainv, *xi = X, *xiend = X + n;
for (; xi != xiend; ++aa, ++xi) {
dSetZero(X, n);
*xi = REAL(1.0);
dSolveCholesky (L,X,n,tmp);
dReal *a = aa;
const dReal *x = X, *xend = X + n;
for (; x!=xend; a+=nskip, ++x) {
*a = *x;
}
}
success = true;
}
return success ? 1 : 0;
}
int _dIsPositiveDefinite (const dReal *A, int n, void *tmpbuf/*[nskip*(n+1)]*/)
{
dAASSERT (n > 0 && A);
size_t FactorCholesky_size = _dEstimateFactorCholeskyTmpbufSize(n);
dIASSERT(FactorCholesky_size % sizeof(dReal) == 0);
const int nskip = dPAD (n);
const int nskip_mul_n = nskip*n;
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (FactorCholesky_size + nskip_mul_n*sizeof(dReal));
dReal *Acopy = (dReal *)((char *)tmp + FactorCholesky_size);
memcpy (Acopy, A, nskip_mul_n * sizeof(dReal));
return dFactorCholesky (Acopy, n, tmp);
}
void _dVectorScale (dReal *a, const dReal *d, int n)
{
dAASSERT (a && d && n >= 0);
for (int i=0; i<n; i++) {
a[i] *= d[i];
}
}
void _dSolveLDLT (const dReal *L, const dReal *d, dReal *b, int n, int nskip)
{
dAASSERT (L && d && b && n > 0 && nskip >= n);
dSolveL1 (L,b,n,nskip);
dVectorScale (b,d,n);
dSolveL1T (L,b,n,nskip);
}
void _dLDLTAddTL (dReal *L, dReal *d, const dReal *a, int n, int nskip, void *tmpbuf/*[2*nskip]*/)
{
dAASSERT (L && d && a && n > 0 && nskip >= n);
if (n < 2) return;
dReal *W1 = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA ((2*nskip)*sizeof(dReal));
dReal *W2 = W1 + nskip;
W1[0] = REAL(0.0);
W2[0] = REAL(0.0);
for (int j=1; j<n; ++j) {
W1[j] = W2[j] = (dReal) (a[j] * M_SQRT1_2);
}
dReal W11 = (dReal) ((REAL(0.5)*a[0]+1)*M_SQRT1_2);
dReal W21 = (dReal) ((REAL(0.5)*a[0]-1)*M_SQRT1_2);
dReal alpha1 = REAL(1.0);
dReal alpha2 = REAL(1.0);
{
dReal dee = d[0];
dReal alphanew = alpha1 + (W11*W11)*dee;
dIASSERT(alphanew != dReal(0.0));
dee /= alphanew;
dReal gamma1 = W11 * dee;
dee *= alpha1;
alpha1 = alphanew;
alphanew = alpha2 - (W21*W21)*dee;
dee /= alphanew;
//dReal gamma2 = W21 * dee;
alpha2 = alphanew;
dReal k1 = REAL(1.0) - W21*gamma1;
dReal k2 = W21*gamma1*W11 - W21;
dReal *ll = L + nskip;
for (int p=1; p<n; ll+=nskip, ++p) {
dReal Wp = W1[p];
dReal ell = *ll;
W1[p] = Wp - W11*ell;
W2[p] = k1*Wp + k2*ell;
}
}
dReal *ll = L + (nskip + 1);
for (int j=1; j<n; ll+=nskip+1, ++j) {
dReal k1 = W1[j];
dReal k2 = W2[j];
dReal dee = d[j];
dReal alphanew = alpha1 + (k1*k1)*dee;
dIASSERT(alphanew != dReal(0.0));
dee /= alphanew;
dReal gamma1 = k1 * dee;
dee *= alpha1;
alpha1 = alphanew;
alphanew = alpha2 - (k2*k2)*dee;
dee /= alphanew;
dReal gamma2 = k2 * dee;
dee *= alpha2;
d[j] = dee;
alpha2 = alphanew;
dReal *l = ll + nskip;
for (int p=j+1; p<n; l+=nskip, ++p) {
dReal ell = *l;
dReal Wp = W1[p] - k1 * ell;
ell += gamma1 * Wp;
W1[p] = Wp;
Wp = W2[p] - k2 * ell;
ell -= gamma2 * Wp;
W2[p] = Wp;
*l = ell;
}
}
}
// macros for dLDLTRemove() for accessing A - either access the matrix
// directly or access it via row pointers. we are only supposed to reference
// the lower triangle of A (it is symmetric), but indexes i and j come from
// permutation vectors so they are not predictable. so do a test on the
// indexes - this should not slow things down too much, as we don't do this
// in an inner loop.
#define _GETA(i,j) (A[i][j])
//#define _GETA(i,j) (A[(i)*nskip+(j)])
#define GETA(i,j) ((i > j) ? _GETA(i,j) : _GETA(j,i))
void _dLDLTRemove (dReal **A, const int *p, dReal *L, dReal *d,
int /*n1*/, int n2, int r, int nskip, void *tmpbuf/*n2 + 2*nskip*/)
{
//dAASSERT(A && p && L && d && n1 > 0 && n2 > 0 && r >= 0 && r < n2 &&
//n1 >= n2 && nskip >= n1);
#ifndef dNODEBUG
for (int i=0; i<n2; ++i) dIASSERT(p[i] >= 0 && p[i] < n1);
#endif
if (r==n2-1) {
return; // deleting last row/col is easy
}
else {
size_t LDLTAddTL_size = _dEstimateLDLTAddTLTmpbufSize(nskip);
dIASSERT(LDLTAddTL_size % sizeof(dReal) == 0);
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (LDLTAddTL_size + n2 * sizeof(dReal));
if (r==0) {
dReal *a = (dReal *)((char *)tmp + LDLTAddTL_size);
const int p_0 = p[0];
for (int i=0; i<n2; ++i) {
a[i] = -GETA(p[i],p_0);
}
a[0] += REAL(1.0);
dLDLTAddTL (L,d,a,n2,nskip,tmp);
}
else {
dReal *t = (dReal *)((char *)tmp + LDLTAddTL_size);
{
dReal *Lcurr = L + r*nskip;
for (int i=0; i<r; ++Lcurr, ++i) {
dIASSERT(d[i] != dReal(0.0));
t[i] = *Lcurr / d[i];
}
}
dReal *a = t + r;
{
dReal *Lcurr = L + r*nskip;
const int *pp_r = p + r, p_r = *pp_r;
const int n2_minus_r = n2-r;
for (int i=0; i<n2_minus_r; Lcurr+=nskip,++i) {
a[i] = dDot(Lcurr,t,r) - GETA(pp_r[i],p_r);
}
}
a[0] += REAL(1.0);
dLDLTAddTL (L + r*nskip+r, d+r, a, n2-r, nskip, tmp);
}
}
// snip out row/column r from L and d
dRemoveRowCol (L,n2,nskip,r);
if (r < (n2-1)) memmove (d+r,d+r+1,(n2-r-1)*sizeof(dReal));
}
void _dRemoveRowCol (dReal *A, int n, int nskip, int r)
{
dAASSERT(A && n > 0 && nskip >= n && r >= 0 && r < n);
if (r >= n-1) return;
if (r > 0) {
{
const size_t move_size = (n-r-1)*sizeof(dReal);
dReal *Adst = A + r;
for (int i=0; i<r; Adst+=nskip,++i) {
dReal *Asrc = Adst + 1;
memmove (Adst,Asrc,move_size);
}
}
{
const size_t cpy_size = r*sizeof(dReal);
dReal *Adst = A + r * nskip;
for (int i=r; i<(n-1); ++i) {
dReal *Asrc = Adst + nskip;
memcpy (Adst,Asrc,cpy_size);
Adst = Asrc;
}
}
}
{
const size_t cpy_size = (n-r-1)*sizeof(dReal);
dReal *Adst = A + r * (nskip + 1);
for (int i=r; i<(n-1); ++i) {
dReal *Asrc = Adst + (nskip + 1);
memcpy (Adst,Asrc,cpy_size);
Adst = Asrc - 1;
}
}
}
#undef dSetZero
#undef dSetValue
//#undef dDot
#undef dMultiply0
#undef dMultiply1
#undef dMultiply2
#undef dFactorCholesky
#undef dSolveCholesky
#undef dInvertPDMatrix
#undef dIsPositiveDefinite
//#undef dFactorLDLT
//#undef dSolveL1
//#undef dSolveL1T
#undef dVectorScale
#undef dSolveLDLT
#undef dLDLTAddTL
#undef dLDLTRemove
#undef dRemoveRowCol
void dSetZero (dReal *a, int n)
{
_dSetZero (a, n);
}
void dSetValue (dReal *a, int n, dReal value)
{
_dSetValue (a, n, value);
}
// dReal dDot (const dReal *a, const dReal *b, int n);
void dMultiply0 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply0 (A, B, C, p, q, r);
}
void dMultiply1 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply1 (A, B, C, p, q, r);
}
void dMultiply2 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply2 (A, B, C, p, q, r);
}
int dFactorCholesky (dReal *A, int n)
{
return _dFactorCholesky (A, n, NULL);
}
void dSolveCholesky (const dReal *L, dReal *b, int n)
{
_dSolveCholesky (L, b, n, NULL);
}
int dInvertPDMatrix (const dReal *A, dReal *Ainv, int n)
{
return _dInvertPDMatrix (A, Ainv, n, NULL);
}
int dIsPositiveDefinite (const dReal *A, int n)
{
return _dIsPositiveDefinite (A, n, NULL);
}
// void dFactorLDLT (dReal *A, dReal *d, int n, int nskip);
// void dSolveL1 (const dReal *L, dReal *b, int n, int nskip);
// void dSolveL1T (const dReal *L, dReal *b, int n, int nskip);
void dVectorScale (dReal *a, const dReal *d, int n)
{
_dVectorScale (a, d, n);
}
void dSolveLDLT (const dReal *L, const dReal *d, dReal *b, int n, int nskip)
{
_dSolveLDLT (L, d, b, n, nskip);
}
void dLDLTAddTL (dReal *L, dReal *d, const dReal *a, int n, int nskip)
{
_dLDLTAddTL (L, d, a, n, nskip, NULL);
}
void dLDLTRemove (dReal **A, const int *p, dReal *L, dReal *d, int n1, int n2, int r, int nskip)
{
_dLDLTRemove (A, p, L, d, n1, n2, r, nskip, NULL);
}
void dRemoveRowCol (dReal *A, int n, int nskip, int r)
{
_dRemoveRowCol (A, n, nskip, r);
}
| 14,493
| 6,456
|
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 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 "cocostudio/CCTween.h"
#include "cocostudio/CCArmatureAnimation.h"
#include "cocostudio/CCBone.h"
#include "cocostudio/CCArmature.h"
#include "cocostudio/CCUtilMath.h"
#include "cocostudio/CCTransformHelp.h"
namespace cocostudio {
using cocos2d::tweenfunc::Linear;
Tween *Tween::create(Bone *bone)
{
Tween *pTween = new (std::nothrow) Tween();
if (pTween && pTween->init(bone))
{
pTween->autorelease();
return pTween;
}
CC_SAFE_DELETE(pTween);
return nullptr;
}
Tween::Tween()
: _movementBoneData(nullptr)
, _tweenData(nullptr)
, _from(nullptr)
, _to(nullptr)
, _between(nullptr)
, _bone(nullptr)
, _frameTweenEasing(Linear)
, _fromIndex(0)
, _toIndex(0)
, _animation(nullptr)
, _passLastFrame(false)
{
}
Tween::~Tween(void)
{
CC_SAFE_DELETE( _from );
CC_SAFE_DELETE( _between );
}
bool Tween::init(Bone *bone)
{
bool bRet = false;
do
{
_from = new (std::nothrow) FrameData();
_between = new (std::nothrow) FrameData();
_bone = bone;
_tweenData = _bone->getTweenData();
_tweenData->displayIndex = -1;
_animation = _bone->getArmature() != nullptr ? _bone->getArmature()->getAnimation() : nullptr;
bRet = true;
}
while (0);
return bRet;
}
void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing)
{
ProcessBase::play(durationTo, durationTween, loop, tweenEasing);
if (loop)
{
_loopType = ANIMATION_TO_LOOP_FRONT;
}
else
{
_loopType = ANIMATION_NO_LOOP;
}
_totalDuration = 0;
_betweenDuration = 0;
_fromIndex = _toIndex = 0;
bool difMovement = movementBoneData != _movementBoneData;
setMovementBoneData(movementBoneData);
_rawDuration = _movementBoneData->duration;
FrameData *nextKeyFrame = _movementBoneData->getFrameData(0);
_tweenData->displayIndex = nextKeyFrame->displayIndex;
if (_bone->getArmature()->getArmatureData()->dataVersion >= VERSION_COMBINED)
{
TransformHelp::nodeSub(*_tweenData, *_bone->getBoneData());
_tweenData->scaleX += 1;
_tweenData->scaleY += 1;
}
if (_rawDuration == 0 )
{
_loopType = SINGLE_FRAME;
if(durationTo == 0)
{
setBetween(nextKeyFrame, nextKeyFrame);
}
else
{
setBetween(_tweenData, nextKeyFrame);
}
_frameTweenEasing = Linear;
}
else if (_movementBoneData->frameList.size() > 1)
{
_durationTween = durationTween * _movementBoneData->scale;
if (loop && _movementBoneData->delay != 0)
{
setBetween(_tweenData, tweenNodeTo(updateFrameData(1 - _movementBoneData->delay), _between));
}
else
{
if (!difMovement || durationTo == 0)
{
setBetween(nextKeyFrame, nextKeyFrame);
}
else
{
setBetween(_tweenData, nextKeyFrame);
}
}
}
tweenNodeTo(0);
}
void Tween::gotoAndPlay(int frameIndex)
{
ProcessBase::gotoFrame(frameIndex);
_totalDuration = 0;
_betweenDuration = 0;
_fromIndex = _toIndex = 0;
_isPlaying = true;
_isComplete = _isPause = false;
_currentPercent = (float)_curFrameIndex / ((float)_rawDuration-1);
_currentFrame = _nextFrameIndex * _currentPercent;
}
void Tween::gotoAndPause(int frameIndex)
{
gotoAndPlay(frameIndex);
pause();
}
void Tween::updateHandler()
{
if (_currentPercent >= 1)
{
switch(_loopType)
{
case SINGLE_FRAME:
{
_currentPercent = 1;
_isComplete = true;
_isPlaying = false;
}
break;
case ANIMATION_NO_LOOP:
{
_loopType = ANIMATION_MAX;
if (_durationTween <= 0)
{
_currentPercent = 1;
}
else
{
_currentPercent = (_currentPercent - 1) * _nextFrameIndex / _durationTween;
}
if (_currentPercent >= 1)
{
_currentPercent = 1;
_isComplete = true;
_isPlaying = false;
break;
}
else
{
_nextFrameIndex = _durationTween;
_currentFrame = _currentPercent * _nextFrameIndex;
_totalDuration = 0;
_betweenDuration = 0;
_fromIndex = _toIndex = 0;
break;
}
}
break;
case ANIMATION_TO_LOOP_FRONT:
{
_loopType = ANIMATION_LOOP_FRONT;
_nextFrameIndex = _durationTween > 0 ? _durationTween : 1;
if (_movementBoneData->delay != 0)
{
//
_currentFrame = (1 - _movementBoneData->delay) * (float)_nextFrameIndex;
_currentPercent = _currentFrame / _nextFrameIndex;
}
else
{
_currentPercent = 0;
_currentFrame = 0;
}
_totalDuration = 0;
_betweenDuration = 0;
_fromIndex = _toIndex = 0;
}
break;
case ANIMATION_MAX:
{
_currentPercent = 1;
_isComplete = true;
_isPlaying = false;
}
break;
default:
{
_currentFrame = fmodf(_currentFrame, _nextFrameIndex);
}
break;
}
}
if (_currentPercent < 1 && _loopType <= ANIMATION_TO_LOOP_BACK)
{
_currentPercent = sin(_currentPercent * CC_HALF_PI);
}
float percent = _currentPercent;
if (_loopType > ANIMATION_TO_LOOP_BACK)
{
percent = updateFrameData(percent);
}
if(_frameTweenEasing != ::cocos2d::tweenfunc::TWEEN_EASING_MAX)
{
tweenNodeTo(percent);
}
}
void Tween::setBetween(FrameData *from, FrameData *to, bool limit)
{
do
{
if(from->displayIndex < 0 && to->displayIndex >= 0)
{
_from->copy(to);
_between->subtract(to, to, limit);
break;
}
else if(to->displayIndex < 0 && from->displayIndex >= 0)
{
_from->copy(from);
_between->subtract(to, to, limit);
break;
}
_from->copy(from);
_between->subtract(from, to, limit);
}
while (0);
if (!from->isTween)
{
_tweenData->copy(from);
_tweenData->isTween = true;
}
arriveKeyFrame(from);
}
void Tween::arriveKeyFrame(FrameData *keyFrameData)
{
if(keyFrameData)
{
DisplayManager *displayManager = _bone->getDisplayManager();
//! Change bone's display
int displayIndex = keyFrameData->displayIndex;
if (!displayManager->isForceChangeDisplay())
{
displayManager->changeDisplayWithIndex(displayIndex, false);
}
//! Update bone zorder, bone's zorder is determined by frame zorder and bone zorder
_tweenData->zOrder = keyFrameData->zOrder;
_bone->updateZOrder();
//! Update blend type
_bone->setBlendFunc(keyFrameData->blendFunc);
//! Update child armature's movement
Armature *childAramture = _bone->getChildArmature();
if(childAramture)
{
if(!keyFrameData->strMovement.empty())
{
childAramture->getAnimation()->play(keyFrameData->strMovement);
}
}
}
}
FrameData *Tween::tweenNodeTo(float percent, FrameData *node)
{
node = node == nullptr ? _tweenData : node;
if (!_from->isTween)
{
percent = 0;
}
node->x = _from->x + percent * _between->x;
node->y = _from->y + percent * _between->y;
node->scaleX = _from->scaleX + percent * _between->scaleX;
node->scaleY = _from->scaleY + percent * _between->scaleY;
node->skewX = _from->skewX + percent * _between->skewX;
node->skewY = _from->skewY + percent * _between->skewY;
_bone->setTransformDirty(true);
if (node && _between->isUseColorInfo)
{
tweenColorTo(percent, node);
}
return node;
}
void Tween::tweenColorTo(float percent, FrameData *node)
{
node->a = _from->a + percent * _between->a;
node->r = _from->r + percent * _between->r;
node->g = _from->g + percent * _between->g;
node->b = _from->b + percent * _between->b;
_bone->updateColor();
}
float Tween::updateFrameData(float currentPercent)
{
if (currentPercent > 1 && _movementBoneData->delay != 0)
{
currentPercent = fmodf(currentPercent, 1);
}
float playedTime = ((float)_rawDuration-1) * currentPercent;
//! If play to current frame's front or back, then find current frame again
if (playedTime < _totalDuration || playedTime >= _totalDuration + _betweenDuration)
{
/*
* Get frame length, if _toIndex >= _length, then set _toIndex to 0, start anew.
* _toIndex is next index will play
*/
long length = _movementBoneData->frameList.size();
cocos2d::Vector<FrameData *> &frames = _movementBoneData->frameList;
FrameData *from = nullptr;
FrameData *to = nullptr;
if (playedTime < frames.at(0)->frameID)
{
from = to = frames.at(0);
setBetween(from, to);
return _currentPercent;
}
if(playedTime >= frames.at(length - 1)->frameID)
{
// If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on.
if (_passLastFrame)
{
from = to = frames.at(length - 1);
setBetween(from, to);
return _currentPercent;
}
_passLastFrame = true;
}
else
{
_passLastFrame = false;
}
do
{
_fromIndex = _toIndex;
from = frames.at(_fromIndex);
_totalDuration = from->frameID;
_toIndex = _fromIndex + 1;
if (_toIndex >= length)
{
_toIndex = 0;
}
to = frames.at(_toIndex);
//! Guaranteed to trigger frame event
if(!from->strEvent.empty() && !_animation->isIgnoreFrameEvent())
{
_animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime);
}
if (playedTime == from->frameID || (_passLastFrame && _fromIndex == length-1))
{
break;
}
}
while (playedTime < from->frameID || playedTime >= to->frameID);
_betweenDuration = to->frameID - from->frameID;
_frameTweenEasing = from->tweenEasing;
setBetween(from, to, false);
}
currentPercent = _betweenDuration == 0 ? 0 : (playedTime - _totalDuration) / (float)_betweenDuration;
/*
* If frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween.
*/
TweenType tweenType = (_frameTweenEasing != Linear) ? _frameTweenEasing : _tweenEasing;
if (tweenType != cocos2d::tweenfunc::TWEEN_EASING_MAX && tweenType != Linear && !_passLastFrame)
{
currentPercent = cocos2d::tweenfunc::tweenTo(currentPercent, tweenType, _from->easingParams);
}
return currentPercent;
}
}
| 12,838
| 4,147
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// <chrono>
// class weekday;
// weekday() = default;
// explicit constexpr weekday(unsigned wd) noexcept;
// constexpr weekday(const sys_days& dp) noexcept;
// explicit constexpr weekday(const local_days& dp) noexcept;
//
// explicit constexpr operator unsigned() const noexcept;
// Effects: Constructs an object of type weekday by initializing m_ with m.
// The value held is unspecified if d is not in the range [0, 255].
#include <chrono>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
int main()
{
using weekday = std::chrono::weekday;
ASSERT_NOEXCEPT(weekday{});
ASSERT_NOEXCEPT(weekday(1));
ASSERT_NOEXCEPT(static_cast<unsigned>(weekday(1)));
constexpr weekday m0{};
static_assert(static_cast<unsigned>(m0) == 0, "");
constexpr weekday m1{1};
static_assert(static_cast<unsigned>(m1) == 1, "");
for (unsigned i = 0; i <= 255; ++i)
{
weekday m(i);
assert(static_cast<unsigned>(m) == i);
}
// TODO - sys_days and local_days ctor tests
}
| 1,466
| 492
|
#include "menuItem.hpp"
#include "../common.hpp"
#include "../gfx.hpp"
void MenuItem::draw(Common& common, int x, int y, bool selected, bool disabled, bool centered, int valueOffsetX)
{
int wid = common.font.getDims(string);
int valueWid = common.font.getDims(value);
if(centered)
x -= (wid >> 1);
if(selected)
{
drawRoundedBox(gfx.screenBmp, x, y, 0, 7, wid);
if(hasValue)
drawRoundedBox(gfx.screenBmp, x + valueOffsetX - (valueWid >> 1), y, 0, 7, valueWid);
}
else
{
common.font.drawText(gfx.screenBmp, string, x + 3, y + 2, 0);
if(hasValue)
common.font.drawText(gfx.screenBmp, value, x + valueOffsetX - (valueWid >> 1) + 3, y + 2, 0);
}
PalIdx c;
if(disabled)
c = disColour;
else if(selected)
c = disabled ? 7 : 168;
else
c = color;
common.font.drawText(gfx.screenBmp, string, x + 2, y + 1, c);
if(hasValue)
common.font.drawText(gfx.screenBmp, value, x + valueOffsetX - (valueWid >> 1) + 2, y + 1, c);
}
| 997
| 454
|
//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <vector>
#include <string>
#include "module_traits.hpp"
#include "writer_fwd.hpp"
#include "date.hpp"
namespace budget {
struct retirement_module {
void load();
void handle(std::vector<std::string>& args);
};
template<>
struct module_traits<retirement_module> {
static constexpr const bool is_default = false;
static constexpr const char* command = "retirement";
};
float fi_ratio(budget::date d);
void retirement_status(budget::writer& w);
} //end of namespace budget
| 844
| 249
|
// Copyright 2016 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/android/webapk/webapk_metrics.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "chrome/browser/android/webapk/chrome_webapk_host.h"
namespace webapk {
const char kInstallDurationHistogram[] = "WebApk.Install.InstallDuration";
const char kInstallEventHistogram[] = "WebApk.Install.InstallEvent";
const char kInstallSourceHistogram[] = "WebApk.Install.InstallSource";
const char kInfoBarShownHistogram[] = "WebApk.Install.InfoBarShown";
const char kUserActionHistogram[] = "WebApk.Install.UserAction";
void TrackRequestTokenDuration(base::TimeDelta delta) {
UMA_HISTOGRAM_TIMES("WebApk.Install.RequestTokenDuration", delta);
}
void TrackInstallDuration(base::TimeDelta delta) {
UMA_HISTOGRAM_MEDIUM_TIMES(kInstallDurationHistogram, delta);
}
void TrackInstallEvent(InstallEvent event) {
UMA_HISTOGRAM_ENUMERATION(kInstallEventHistogram, event, INSTALL_EVENT_MAX);
}
void TrackInstallSource(InstallSource event) {
UMA_HISTOGRAM_ENUMERATION(kInstallSourceHistogram, event, INSTALL_SOURCE_MAX);
}
void TrackInstallInfoBarShown(InfoBarShown event) {
UMA_HISTOGRAM_ENUMERATION(kInfoBarShownHistogram, event,
WEBAPK_INFOBAR_SHOWN_MAX);
}
void TrackUserAction(UserAction event) {
UMA_HISTOGRAM_ENUMERATION(kUserActionHistogram, event, USER_ACTION_MAX);
}
} // namespace webapk
| 1,544
| 543
|
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/inference/api/analysis_predictor.h"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <thread> // NOLINT
#include "paddle/fluid/framework/ir/pass.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/inference/api/helper.h"
#include "paddle/fluid/inference/api/paddle_inference_api.h"
#include "paddle/fluid/inference/tests/api/tester_helper.h"
#include "paddle/fluid/platform/cpu_info.h"
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/inference/api/mkldnn_quantizer.h"
#endif
DEFINE_string(dirname, "", "dirname to tests.");
namespace paddle {
TEST(AnalysisPredictor, analysis_off) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(false);
auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());
// Without analysis, the scope_ and sub_scope_ are created by predictor
// itself.
ASSERT_TRUE(predictor->scope_);
ASSERT_TRUE(predictor->sub_scope_);
ASSERT_EQ(predictor->scope_->parent(), nullptr);
ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
// ir is turned off, so program shouldn't be optimized.
LOG(INFO) << "scope parameters " << predictor->scope_->LocalVarNames().size();
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(inputs, &outputs));
}
TEST(AnalysisPredictor, analysis_on) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(true);
#ifdef PADDLE_WITH_CUDA
config.EnableUseGpu(100, 0);
#else
config.DisableGpu();
#endif
auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());
ASSERT_TRUE(predictor->scope_);
ASSERT_TRUE(predictor->sub_scope_);
ASSERT_EQ(predictor->scope_->parent(), nullptr);
ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(inputs, &outputs));
for (auto& output : outputs) {
LOG(INFO) << inference::DescribeTensor(output);
}
// compare with NativePredictor
auto naive_predictor =
CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
std::vector<PaddleTensor> naive_outputs;
ASSERT_TRUE(naive_predictor->Run(inputs, &naive_outputs));
ASSERT_EQ(naive_outputs.size(), 1UL);
inference::CompareTensor(outputs.front(), naive_outputs.front());
}
TEST(AnalysisPredictor, ZeroCopy) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchUseFeedFetchOps(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto w0 = predictor->GetInputTensor("firstw");
auto w1 = predictor->GetInputTensor("secondw");
auto w2 = predictor->GetInputTensor("thirdw");
auto w3 = predictor->GetInputTensor("forthw");
w0->Reshape({4, 1});
w1->Reshape({4, 1});
w2->Reshape({4, 1});
w3->Reshape({4, 1});
auto* w0_data = w0->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w1_data = w1->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w2_data = w2->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w3_data = w3->mutable_data<int64_t>(PaddlePlace::kCPU);
for (int i = 0; i < 4; i++) {
w0_data[i] = i;
w1_data[i] = i;
w2_data[i] = i;
w3_data[i] = i;
}
predictor->ZeroCopyRun();
auto out = predictor->GetOutputTensor("fc_1.tmp_2");
PaddlePlace place;
int size = 0;
auto* out_data = out->data<float>(&place, &size);
LOG(INFO) << "output size: " << size / sizeof(float);
LOG(INFO) << "output_data: " << out_data;
predictor->TryShrinkMemory();
}
TEST(AnalysisPredictor, Clone) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchUseFeedFetchOps(true);
config.SwitchIrOptim(true);
std::vector<std::unique_ptr<PaddlePredictor>> predictors;
predictors.emplace_back(CreatePaddlePredictor(config));
LOG(INFO) << "************** to clone ************************";
const int num_threads = 3;
for (int i = 1; i < num_threads; i++) {
predictors.emplace_back(predictors.front()->Clone());
}
auto* root_scope =
static_cast<AnalysisPredictor*>(predictors[0].get())->scope();
ASSERT_FALSE(root_scope->kids().empty());
LOG(INFO) << "***** scope ******\n"
<< framework::GenScopeTreeDebugInfo(root_scope);
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
predictors[0]->Run(inputs, &outputs);
LOG(INFO) << "Run with single thread";
for (int i = 0; i < num_threads; i++) {
LOG(INFO) << "run predictor " << i;
ASSERT_TRUE(predictors[i]->Run(inputs, &outputs));
}
LOG(INFO) << "Run with multiple threads";
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; i++) {
threads.emplace_back([&predictors, &inputs, i] {
LOG(INFO) << "thread #" << i << " running";
std::vector<PaddleTensor> outputs;
auto predictor = predictors.front()->Clone();
for (int j = 0; j < 10; j++) {
ASSERT_TRUE(predictor->Run(inputs, &outputs));
}
});
}
for (auto& t : threads) {
t.join();
}
}
// This function is not released yet, will fail on some machine.
// TODO(Superjomn) Turn on it latter.
/*
TEST(AnalysisPredictor, memory_optim) {
AnalysisConfig config(FLAGS_dirname);
config.DisableGpu();
config.EnableMemoryOptim(true);
config.SwitchIrDebug();
auto native_predictor =
CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> output, output1;
{
// The first predictor help to cache the memory optimize strategy.
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
LOG(INFO) << "serialized program: " << predictor->GetSerializedProgram();
ASSERT_FALSE(predictor->GetSerializedProgram().empty());
// Run several times to check the parameters are not reused by mistake.
for (int i = 0; i < 5; i++) {
ASSERT_TRUE(predictor->Run(inputs, &output));
}
}
{
output.clear();
// The second predictor to perform memory optimization.
config.EnableMemoryOptim(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
// Run with memory optimization
ASSERT_TRUE(predictor->Run(inputs, &output));
}
// Run native
ASSERT_TRUE(native_predictor->Run(inputs, &output1));
LOG(INFO) << "the output " << inference::DescribeTensor(output.front());
LOG(INFO) << "the native output "
<< inference::DescribeTensor(output1.front());
inference::CompareResult(output, output1);
}
*/
#ifdef PADDLE_WITH_MKLDNN
class MkldnnQuantizerTest : public testing::Test {
public:
MkldnnQuantizerTest() {
AnalysisConfig config(FLAGS_dirname);
predictor = std::move(CreatePaddlePredictor(config));
auto* predictor_p = static_cast<AnalysisPredictor*>(predictor.get());
auto qconfig = new MkldnnQuantizerConfig();
mkldnn_quantizer.reset(
new AnalysisPredictor::MkldnnQuantizer(*predictor_p, qconfig));
}
std::pair<std::vector<int>, float> Histogram(
const framework::LoDTensor& var_tensor, float min_val, float max_val,
int num_bins) const {
return mkldnn_quantizer->Histogram(var_tensor, min_val, max_val, num_bins);
}
std::pair<bool, framework::LoDTensor> GetMaxScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetMaxScalingFactor(var_tensor, is_unsigned);
}
std::pair<bool, framework::LoDTensor> GetMaxChScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetMaxChScalingFactor(var_tensor, is_unsigned, 0);
}
std::pair<bool, framework::LoDTensor> GetKLScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetKLScalingFactor(var_tensor, is_unsigned);
}
protected:
std::unique_ptr<PaddlePredictor> predictor;
std::unique_ptr<AnalysisPredictor::MkldnnQuantizer> mkldnn_quantizer;
float abs_error = 1e-6;
static const std::array<float, 10> non_negative_values;
static const std::array<float, 10> positive_and_negative_values;
};
const std::array<float, 10> MkldnnQuantizerTest::non_negative_values = {
0.0158671, 0.026459, 0.0280772, 0.00962479, 0.0131628,
0.016704, 0.00118407, 0.00765726, 0.0123213, 0.00944741};
const std::array<float, 10> MkldnnQuantizerTest::positive_and_negative_values =
{-0.0482659, -0.0102493, -0.00794221, -0.00387115, -0.00674586,
-0.0495346, 0.0629528, -0.00531285, -0.0230353, 0.0269089};
TEST_F(MkldnnQuantizerTest, histogram_inverted_min_max) {
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
ASSERT_THROW(Histogram(var_tensor, max_val, min_val, 3),
platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, histogram_non_negative_to_3) {
// all non-negative values
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
std::vector<int> histogram;
float bin_width;
std::tie(histogram, bin_width) = Histogram(var_tensor, min_val, max_val, 3);
ASSERT_NEAR(bin_width, std::abs(max_val - min_val) / 3.f, abs_error)
<< "Improperly calculated bin_width.";
ASSERT_EQ(histogram[0], 4);
ASSERT_EQ(histogram[1], 4);
ASSERT_EQ(histogram[2], 2);
}
TEST_F(MkldnnQuantizerTest, histogram_positive_and_negative_to_3) {
const auto& values = positive_and_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
std::vector<int> histogram;
float bin_width;
std::tie(histogram, bin_width) = Histogram(var_tensor, min_val, max_val, 3);
ASSERT_NEAR(bin_width, std::abs(max_val - min_val) / 3.0f, abs_error)
<< "Improperly calculated bin_width.";
ASSERT_EQ(histogram[0], 3);
ASSERT_EQ(histogram[1], 5);
ASSERT_EQ(histogram[2], 2);
}
TEST_F(MkldnnQuantizerTest, histogram_zero_bins) {
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
ASSERT_THROW(Histogram(var_tensor, min_val, max_val, 0),
platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, histogram_empty) {
// empty tensor
ASSERT_THROW(Histogram({}, -1, 1, 1), platform::EnforceNotMet);
// zero tensor
framework::LoDTensor var_tensor;
var_tensor.Resize({0});
var_tensor.mutable_data<double>(platform::CPUPlace());
ASSERT_THROW(Histogram(var_tensor, -1, 1, 1), platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, kl_scaling_factor_signed) {
const auto& values = positive_and_negative_values;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetKLScalingFactor(var_tensor, false);
ASSERT_EQ(is_unsigned, false);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / 0.0899106152344, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_signed) {
const auto& values = positive_and_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxScalingFactor(var_tensor, false);
ASSERT_EQ(is_unsigned, false);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / max_val, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_unsigned) {
const auto& values = non_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / max_val, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_chwise_unsigned) {
const auto& values = non_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
int channels = 3;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(channels, 1, 1, values.size()));
for (int i = 0; i < channels; i++)
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()) +
i * values.size());
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxChScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), channels);
for (int i = 0; i < channels; i++) {
ASSERT_NEAR(lod_tensor.data<double>()[i], 1.0 / max_val, abs_error);
}
}
TEST_F(MkldnnQuantizerTest, kl_scaling_factor_unsigned) {
const auto& values = non_negative_values;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetKLScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / 0.0252845321362, abs_error);
}
#endif
#ifdef PADDLE_WITH_CUDA
TEST(AnalysisPredictor, bf16_gpu_pass_strategy) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(true);
config.EnableUseGpu(100, 0);
config.EnableMkldnnBfloat16();
#ifdef PADDLE_WITH_MKLDNN
if (platform::MayIUse(platform::cpu_isa_t::avx512_core))
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), true);
else
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
#else
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
#endif
}
#endif
TEST(AnalysisPredictor, bf16_pass_strategy) {
std::vector<std::string> passes;
PassStrategy passStrategy(passes);
passStrategy.EnableMkldnnBfloat16();
}
} // namespace paddle
namespace paddle_infer {
TEST(Predictor, Run) {
Config config;
config.SetModel(FLAGS_dirname);
auto predictor = CreatePredictor(config);
auto w0 = predictor->GetInputHandle("firstw");
auto w1 = predictor->GetInputHandle("secondw");
auto w2 = predictor->GetInputHandle("thirdw");
auto w3 = predictor->GetInputHandle("forthw");
w0->Reshape({4, 1});
w1->Reshape({4, 1});
w2->Reshape({4, 1});
w3->Reshape({4, 1});
auto* w0_data = w0->mutable_data<int64_t>(PlaceType::kCPU);
auto* w1_data = w1->mutable_data<int64_t>(PlaceType::kCPU);
auto* w2_data = w2->mutable_data<int64_t>(PlaceType::kCPU);
auto* w3_data = w3->mutable_data<int64_t>(PlaceType::kCPU);
for (int i = 0; i < 4; i++) {
w0_data[i] = i;
w1_data[i] = i;
w2_data[i] = i;
w3_data[i] = i;
}
predictor->Run();
auto out = predictor->GetOutputHandle("fc_1.tmp_2");
PlaceType place;
int size = 0;
out->data<float>(&place, &size);
LOG(INFO) << "output size: " << size / sizeof(float);
predictor->TryShrinkMemory();
}
} // namespace paddle_infer
| 18,259
| 6,977
|
/*
* 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 <limits>
#include "velox/buffer/Buffer.h"
#include "velox/common/memory/Memory.h"
#include "velox/expression/ControlExpr.h"
#include "velox/expression/VectorFunction.h"
#include "velox/functions/prestosql/tests/FunctionBaseTest.h"
#include "velox/type/Type.h"
#include "velox/vector/BaseVector.h"
#include "velox/vector/TypeAliases.h"
using namespace facebook::velox;
using namespace facebook::velox::test;
namespace {
/// Wraps input in a dictionary that reverses the order of rows.
class TestingDictionaryFunction : public exec::VectorFunction {
public:
bool isDefaultNullBehavior() const override {
return false;
}
void apply(
const SelectivityVector& rows,
std::vector<VectorPtr>& args,
const TypePtr& /* outputType */,
exec::EvalCtx* context,
VectorPtr* result) const override {
VELOX_CHECK(rows.isAllSelected());
const auto size = rows.size();
auto indices = makeIndicesInReverse(size, context->pool());
*result = BaseVector::wrapInDictionary(
BufferPtr(nullptr), indices, size, args[0]);
}
static std::vector<std::shared_ptr<exec::FunctionSignature>> signatures() {
// T, integer -> T
return {exec::FunctionSignatureBuilder()
.typeVariable("T")
.returnType("T")
.argumentType("T")
.build()};
}
};
} // namespace
class CastExprTest : public functions::test::FunctionBaseTest {
protected:
CastExprTest() {
exec::registerVectorFunction(
"testing_dictionary",
TestingDictionaryFunction::signatures(),
std::make_unique<TestingDictionaryFunction>());
}
void setCastIntByTruncate(bool value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kCastIntByTruncate, std::to_string(value)},
});
}
void setCastMatchStructByName(bool value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kCastMatchStructByName, std::to_string(value)},
});
}
void setTimezone(const std::string& value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kSessionTimezone, value},
{core::QueryConfig::kAdjustTimestampToTimezone, "true"},
});
}
std::shared_ptr<core::CastTypedExpr> makeCastExpr(
const std::shared_ptr<const core::ITypedExpr>& input,
const TypePtr& toType,
bool nullOnFailure) {
std::vector<std::shared_ptr<const core::ITypedExpr>> inputs = {input};
return std::make_shared<core::CastTypedExpr>(toType, inputs, nullOnFailure);
}
void testComplexCast(
const std::string& fromExpression,
const VectorPtr& data,
const VectorPtr& expected,
bool nullOnFailure = false) {
auto rowVector = makeRowVector({data});
auto rowType = std::dynamic_pointer_cast<const RowType>(rowVector->type());
auto castExpr = makeCastExpr(
makeTypedExpr(fromExpression, rowType),
expected->type(),
nullOnFailure);
exec::ExprSet exprSet({castExpr}, &execCtx_);
const auto size = data->size();
SelectivityVector rows(size);
std::vector<VectorPtr> result(1);
{
exec::EvalCtx evalCtx(&execCtx_, &exprSet, rowVector.get());
exprSet.eval(rows, &evalCtx, &result);
assertEqualVectors(expected, result[0]);
}
// Test constant input.
{
// Use last element for constant.
const auto index = size - 1;
auto constantData = BaseVector::wrapInConstant(size, index, data);
auto constantRow = makeRowVector({constantData});
exec::EvalCtx evalCtx(&execCtx_, &exprSet, constantRow.get());
exprSet.eval(rows, &evalCtx, &result);
assertEqualVectors(
BaseVector::wrapInConstant(size, index, expected), result[0]);
}
// Test dictionary input. It is not sufficient to wrap input in a dictionary
// as it will be peeled off before calling "cast". Apply
// testing_dictionary function to input to ensure that "cast" receives
// dictionary input.
{
auto dictionaryCastExpr = makeCastExpr(
makeTypedExpr(
fmt::format("testing_dictionary({})", fromExpression), rowType),
expected->type(),
nullOnFailure);
exec::ExprSet dictionaryExprSet({dictionaryCastExpr}, &execCtx_);
exec::EvalCtx evalCtx(&execCtx_, &dictionaryExprSet, rowVector.get());
dictionaryExprSet.eval(rows, &evalCtx, &result);
auto indices = ::makeIndicesInReverse(size, pool());
assertEqualVectors(wrapInDictionary(indices, size, expected), result[0]);
}
}
/**
* @tparam From Source type for cast
* @tparam To Destination type for cast
* @param typeString Cast type in string
* @param input Input vector of type From
* @param expectedResult Expected output vector of type To
* @param inputNulls Input null indexes
* @param expectedNulls Expected output null indexes
*/
template <typename TFrom, typename TTo>
void testCast(
const std::string& typeString,
std::vector<std::optional<TFrom>> input,
std::vector<std::optional<TTo>> expectedResult,
bool expectFailure = false,
bool tryCast = false) {
std::vector<TFrom> rawInput(input.size());
for (auto index = 0; index < input.size(); index++) {
if (input[index].has_value()) {
rawInput[index] = input[index].value();
}
}
// Create input vector using values and nulls
auto inputVector = makeFlatVector(rawInput);
for (auto index = 0; index < input.size(); index++) {
if (!input[index].has_value()) {
inputVector->setNull(index, true);
}
}
auto rowVector = makeRowVector({inputVector});
std::string castFunction = tryCast ? "try_cast" : "cast";
if (expectFailure) {
EXPECT_THROW(
evaluate<FlatVector<typename CppToType<TTo>::NativeType>>(
castFunction + "(c0 as " + typeString + ")", rowVector),
std::invalid_argument);
return;
}
// run try cast and get the result vector
auto result = evaluate<FlatVector<typename CppToType<TTo>::NativeType>>(
castFunction + "(c0 as " + typeString + ")", rowVector);
std::string msg;
// Compare the values and nulls in the output with expected
for (int index = 0; index < input.size(); index++) {
if (expectedResult[index].has_value()) {
EXPECT_TRUE(
compareValues(result->valueAt(index), expectedResult[index], msg))
<< "values at index " << index << " do not match!" << msg;
} else {
EXPECT_TRUE(result->isNullAt(index)) << " at index " << index;
}
}
}
};
TEST_F(CastExprTest, basics) {
// Testing non-null or error cases
const std::vector<std::optional<int32_t>> ii = {1, 2, 3, 100, -100};
const std::vector<std::optional<double>> oo = {1.0, 2.0, 3.0, 100.0, -100.0};
testCast<int32_t, double>(
"double", {1, 2, 3, 100, -100}, {1.0, 2.0, 3.0, 100.0, -100.0});
testCast<int32_t, std::string>(
"string", {1, 2, 3, 100, -100}, {"1", "2", "3", "100", "-100"});
testCast<std::string, int8_t>(
"tinyint", {"1", "2", "3", "100", "-100"}, {1, 2, 3, 100, -100});
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<double, double>(
"double",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<double, std::string>(
"string",
{1.888, 2.5, 3.6, 100.44, -100.101},
{"1.888", "2.5", "3.6", "100.44", "-100.101"});
testCast<double, double>(
"double",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<double, float>(
"float",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<bool, std::string>("string", {true, false}, {"true", "false"});
}
TEST_F(CastExprTest, timestamp) {
testCast<std::string, Timestamp>(
"timestamp",
{
"1970-01-01",
"2000-01-01",
"1970-01-01 00:00:00",
"2000-01-01 12:21:56",
"1970-01-01 00:00:00-02:00",
std::nullopt,
},
{
Timestamp(0, 0),
Timestamp(946684800, 0),
Timestamp(0, 0),
Timestamp(946729316, 0),
Timestamp(7200, 0),
std::nullopt,
});
}
TEST_F(CastExprTest, timestampInvalid) {
testCast<int8_t, Timestamp>("timestamp", {12}, {Timestamp(0, 0)}, true);
testCast<int16_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<int32_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<int64_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<float, Timestamp>("timestamp", {12.99}, {Timestamp(0, 0)}, true);
testCast<double, Timestamp>("timestamp", {12.99}, {Timestamp(0, 0)}, true);
}
TEST_F(CastExprTest, timestampAdjustToTimezone) {
setTimezone("America/Los_Angeles");
// Expect unix epochs to be converted to LA timezone (8h offset).
testCast<std::string, Timestamp>(
"timestamp",
{
"1970-01-01",
"2000-01-01",
"1969-12-31 16:00:00",
"2000-01-01 12:21:56",
"1970-01-01 00:00:00+14:00",
std::nullopt,
"2000-05-01", // daylight savings - 7h offset.
},
{
Timestamp(28800, 0),
Timestamp(946713600, 0),
Timestamp(0, 0),
Timestamp(946758116, 0),
Timestamp(-21600, 0),
std::nullopt,
Timestamp(957164400, 0),
});
// Empty timezone is assumed to be GMT.
setTimezone("");
testCast<std::string, Timestamp>(
"timestamp", {"1970-01-01"}, {Timestamp(0, 0)});
}
TEST_F(CastExprTest, timestampAdjustToTimezoneInvalid) {
auto testFunc = [&]() {
testCast<std::string, Timestamp>(
"timestamp", {"1970-01-01"}, {Timestamp(1, 0)});
};
setTimezone("bla");
EXPECT_THROW(testFunc(), std::runtime_error);
}
TEST_F(CastExprTest, date) {
testCast<std::string, Date>(
"date",
{
"1970-01-01",
"2020-01-01",
"2135-11-09",
"1969-12-27",
"1812-04-15",
"1920-01-02",
std::nullopt,
},
{
Date(0),
Date(18262),
Date(60577),
Date(-5),
Date(-57604),
Date(-18262),
std::nullopt,
});
}
TEST_F(CastExprTest, invalidDate) {
testCast<int8_t, Date>("date", {12}, {Date(0)}, true);
testCast<int16_t, Date>("date", {1234}, {Date(0)}, true);
testCast<int32_t, Date>("date", {1234}, {Date(0)}, true);
testCast<int64_t, Date>("date", {1234}, {Date(0)}, true);
testCast<float, Date>("date", {12.99}, {Date(0)}, true);
testCast<double, Date>("date", {12.99}, {Date(0)}, true);
// Parsing an ill-formated date.
testCast<std::string, Date>("date", {"2012-Oct-23"}, {Date(0)}, true);
}
TEST_F(CastExprTest, truncateVsRound) {
// Testing truncate vs round cast from double to int.
setCastIntByTruncate(true);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {1, 2, 3, 100, -100});
testCast<double, int8_t>(
"tinyint",
{1,
256,
257,
2147483646,
2147483647,
2147483648,
-2147483646,
-2147483647,
-2147483648,
-2147483649},
{1, 0, 1, -2, -1, -1, 2, 1, 0, 0});
setCastIntByTruncate(false);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<int8_t, int32_t>("int", {111, 2, 3, 10, -10}, {111, 2, 3, 10, -10});
setCastIntByTruncate(true);
testCast<int32_t, int8_t>(
"tinyint", {1111111, 2, 3, 1000, -100101}, {71, 2, 3, -24, -5});
setCastIntByTruncate(false);
EXPECT_THROW(
(testCast<int32_t, int8_t>(
"tinyint", {1111111, 2, 3, 1000, -100101}, {71, 2, 3, -24, -5})),
std::invalid_argument);
}
TEST_F(CastExprTest, nullInputs) {
// Testing null inputs
testCast<double, double>(
"double",
{std::nullopt, std::nullopt, 3.6, 100.44, std::nullopt},
{std::nullopt, std::nullopt, 3.6, 100.44, std::nullopt});
testCast<double, float>(
"float",
{std::nullopt, 2.5, 3.6, 100.44, std::nullopt},
{std::nullopt, 2.5, 3.6, 100.44, std::nullopt});
testCast<double, std::string>(
"string",
{1.888, std::nullopt, std::nullopt, std::nullopt, -100.101},
{"1.888", std::nullopt, std::nullopt, std::nullopt, "-100.101"});
}
TEST_F(CastExprTest, errorHandling) {
// Making sure error cases lead to null outputs
testCast<std::string, int8_t>(
"tinyint",
{"1abc", "2", "3", "100", std::nullopt},
{std::nullopt, 2, 3, 100, std::nullopt},
false,
true);
setCastIntByTruncate(true);
testCast<std::string, int8_t>(
"tinyint",
{"-",
"-0",
" @w 123",
"123 ",
" 122",
"",
"-12-3",
"125.5",
"1234",
"-129",
"127",
"-128"},
{std::nullopt,
0,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
127,
-128},
false,
true);
testCast<double, int>(
"integer",
{1e12, 2.5, 3.6, 100.44, -100.101},
{std::numeric_limits<int32_t>::max(), 2, 3, 100, -100},
false,
true);
setCastIntByTruncate(false);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<std::string, int8_t>(
"tinyint", {"1abc", "2", "3", "100", "-100"}, {1, 2, 3, 100, -100}, true);
testCast<std::string, int8_t>(
"tinyint", {"1", "2", "3", "100", "-100.5"}, {1, 2, 3, 100, -100}, true);
}
constexpr vector_size_t kVectorSize = 1'000;
TEST_F(CastExprTest, mapCast) {
auto sizeAt = [](vector_size_t row) { return row % 5; };
auto keyAt = [](vector_size_t row) { return row % 11; };
auto valueAt = [](vector_size_t row) { return row % 13; };
auto inputMap = makeMapVector<int64_t, int64_t>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3));
// Cast map<bigint, bigint> -> map<integer, double>.
{
auto expectedMap = makeMapVector<int32_t, double>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// Cast map<bigint, bigint> -> map<bigint, varchar>.
{
auto valueAtString = [valueAt](vector_size_t row) {
return StringView(folly::to<std::string>(valueAt(row)));
};
auto expectedMap = makeMapVector<int64_t, StringView>(
kVectorSize, sizeAt, keyAt, valueAtString, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// Cast map<bigint, bigint> -> map<varchar, bigint>.
{
auto keyAtString = [&](vector_size_t row) {
return StringView(folly::to<std::string>(keyAt(row)));
};
auto expectedMap = makeMapVector<StringView, int64_t>(
kVectorSize, sizeAt, keyAtString, valueAt, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// null values
{
auto inputWithNullValues = makeMapVector<int64_t, int64_t>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3), nullEvery(7));
auto expectedMap = makeMapVector<int32_t, double>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3), nullEvery(7));
testComplexCast("c0", inputWithNullValues, expectedMap);
}
}
TEST_F(CastExprTest, arrayCast) {
auto sizeAt = [](vector_size_t /* row */) { return 7; };
auto valueAt = [](vector_size_t /* row */, vector_size_t idx) {
return 1 + idx;
};
auto arrayVector =
makeArrayVector<double>(kVectorSize, sizeAt, valueAt, nullEvery(3));
// Cast array<double> -> array<bigint>.
{
auto expected =
makeArrayVector<int64_t>(kVectorSize, sizeAt, valueAt, nullEvery(3));
testComplexCast("c0", arrayVector, expected);
}
// Cast array<double> -> array<varchar>.
{
auto valueAtString = [valueAt](vector_size_t row, vector_size_t idx) {
return StringView(folly::to<std::string>(valueAt(row, idx)));
};
auto expected = makeArrayVector<StringView>(
kVectorSize, sizeAt, valueAtString, nullEvery(3));
testComplexCast("c0", arrayVector, expected);
}
}
TEST_F(CastExprTest, rowCast) {
auto valueAt = [](vector_size_t row) { return double(1 + row); };
auto valueAtInt = [](vector_size_t row) { return int64_t(1 + row); };
auto doubleVectorNullEvery3 =
makeFlatVector<double>(kVectorSize, valueAt, nullEvery(3));
auto intVectorNullEvery11 =
makeFlatVector<int64_t>(kVectorSize, valueAtInt, nullEvery(11));
auto doubleVectorNullEvery11 =
makeFlatVector<double>(kVectorSize, valueAt, nullEvery(11));
auto intVectorNullEvery3 =
makeFlatVector<int64_t>(kVectorSize, valueAtInt, nullEvery(3));
auto rowVector = makeRowVector(
{intVectorNullEvery11, doubleVectorNullEvery3}, nullEvery(5));
setCastMatchStructByName(false);
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double, c1:
// bigint)
{
auto expectedRowVector = makeRowVector(
{doubleVectorNullEvery11, intVectorNullEvery3}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(a: double, b:
// bigint)
{
auto expectedRowVector = makeRowVector(
{"a", "b"},
{doubleVectorNullEvery11, intVectorNullEvery3},
nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double)
{
auto expectedRowVector =
makeRowVector({doubleVectorNullEvery11}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Name-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double) dropping
// b
setCastMatchStructByName(true);
{
auto intVectorNullAll = makeFlatVector<int64_t>(
kVectorSize, valueAtInt, [](vector_size_t /* row */) { return true; });
auto expectedRowVector = makeRowVector(
{"c0", "b"}, {doubleVectorNullEvery11, intVectorNullAll}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
}
TEST_F(CastExprTest, nulls) {
auto input =
makeFlatVector<int32_t>(kVectorSize, [](auto row) { return row; });
auto allNulls = makeFlatVector<int32_t>(
kVectorSize, [](auto row) { return row; }, nullEvery(1));
auto result = evaluate<FlatVector<int16_t>>(
"cast(if(c0 % 2 = 0, c1, c0) as smallint)",
makeRowVector({input, allNulls}));
auto expectedResult = makeFlatVector<int16_t>(
kVectorSize, [](auto row) { return row; }, nullEvery(2));
assertEqualVectors(expectedResult, result);
}
TEST_F(CastExprTest, testNullOnFailure) {
auto input =
makeNullableFlatVector<std::string>({"1", "2", "", "3.4", std::nullopt});
auto expected = makeNullableFlatVector<int32_t>(
{1, 2, std::nullopt, std::nullopt, std::nullopt});
// nullOnFailure is true, so we should return null instead of throwing.
testComplexCast("c0", input, expected, true);
// nullOnFailure is false, so we should throw.
EXPECT_THROW(
testComplexCast("c0", input, expected, false), std::invalid_argument);
}
TEST_F(CastExprTest, toString) {
auto input = std::make_shared<core::FieldAccessTypedExpr>(VARCHAR(), "a");
exec::ExprSet exprSet(
{makeCastExpr(input, BIGINT(), false),
makeCastExpr(input, ARRAY(VARCHAR()), false)},
&execCtx_);
ASSERT_EQ("cast((a) as BIGINT)", exprSet.exprs()[0]->toString());
ASSERT_EQ("cast((a) as ARRAY<VARCHAR>)", exprSet.exprs()[1]->toString());
}
| 20,338
| 7,851
|
/*
** EPITECH PROJECT, 2020
** B-CPP-300-LYN-3-1-CPPD13-
** File description:
** Woody.hpp
*/
#ifndef WOODY_HPP_
#define WOODY_HPP_
#include "Toy.hpp"
class Woody : public Toy {
public:
Woody(std::string const &, std::string const &);
Woody(Woody const &);
virtual ~Woody();
virtual void display(std::string const);
};
#endif /* !WOODY_HPP_ */
| 417
| 168
|
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/core/frames/quic_new_connection_id_frame.h"
#include "net/third_party/quiche/src/quic/core/quic_constants.h"
namespace quic {
QuicNewConnectionIdFrame::QuicNewConnectionIdFrame()
: control_frame_id(kInvalidControlFrameId),
connection_id(EmptyQuicConnectionId()),
sequence_number(0) {}
QuicNewConnectionIdFrame::QuicNewConnectionIdFrame(
QuicControlFrameId control_frame_id,
QuicConnectionId connection_id,
QuicConnectionIdSequenceNumber sequence_number,
const QuicUint128 stateless_reset_token,
uint64_t retire_prior_to)
: control_frame_id(control_frame_id),
connection_id(connection_id),
sequence_number(sequence_number),
stateless_reset_token(stateless_reset_token),
retire_prior_to(retire_prior_to) {
DCHECK(retire_prior_to <= sequence_number);
}
std::ostream& operator<<(std::ostream& os,
const QuicNewConnectionIdFrame& frame) {
os << "{ control_frame_id: " << frame.control_frame_id
<< ", connection_id: " << frame.connection_id
<< ", sequence_number: " << frame.sequence_number
<< ", retire_prior_to: " << frame.retire_prior_to << " }\n";
return os;
}
} // namespace quic
| 1,407
| 472
|
//===========================================================================
#include "Assets.h"
//===========================================================================
const unsigned char PROGMEM titleSprite_plus_mask[] = {
// width, height,
88, 49,
// FRAME 00
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0xe0, 0x80, 0xf0, 0xc0, 0xf8, 0xe0, 0xfc, 0x70, 0xfe, 0x38, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x0c, 0xff, 0x0c, 0xff, 0x0e, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x46, 0xff, 0x46, 0xff, 0x86, 0xff, 0x8e, 0xff, 0x0c, 0xff, 0x3c, 0xff, 0x38, 0xfe, 0xf0, 0xfe, 0xe0, 0xfc, 0x80, 0xf8, 0x00, 0xf0, 0x80, 0xf0, 0xc0, 0xf0, 0xc0, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0xc0, 0xf8, 0xc0, 0xf0, 0x80, 0xf0,
0x00, 0xe0, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0xc0, 0x00, 0xc0, 0x00, 0xe0, 0x80, 0xe0, 0x80, 0xf0, 0xc0, 0xf0, 0xc0, 0xf0, 0xc0, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xfc, 0x70, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x60, 0xfc, 0x60, 0xf8, 0xe0, 0xf8, 0xc0, 0xf8, 0xc0, 0xf0, 0x80, 0xf0, 0x00, 0xe0, 0x00, 0xc0, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfc, 0x00, 0xff, 0xf8, 0xff, 0xfe, 0xff, 0x0f, 0xff, 0x03, 0xff, 0xe0, 0xff, 0xf8, 0xff, 0xfc, 0xff, 0x06, 0xff, 0x02, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0xe0, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x03, 0xff, 0x1c, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xc1, 0xff, 0x80, 0xff, 0x06, 0xff, 0x06, 0xff, 0x00, 0xff, 0x40, 0xff, 0x60, 0xff, 0xb0, 0xff, 0xc1, 0xff, 0xff, 0xff,
0x7e, 0xff, 0x60, 0xff, 0x60, 0xff, 0x60, 0xf8, 0xc0, 0xf8, 0xe0, 0xf8, 0x60, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfe, 0x38, 0xff, 0x7c, 0xff, 0xdc, 0xff, 0x8f, 0xff, 0x07, 0xff, 0x13, 0xff, 0x19, 0xff, 0x05, 0xff, 0x04, 0xff, 0x02, 0xff, 0x82, 0xff, 0xc2, 0xff, 0xc1, 0xff, 0x61, 0xff, 0x41, 0xff, 0x40, 0xff, 0xc0, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x84, 0xff, 0xf8, 0xff, 0xe0, 0xff, 0x01, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xfc, 0xff, 0x00, 0xff, 0x00, 0xfe, 0x00, 0x00,
0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x0c, 0xff, 0x9e, 0xff, 0x3f, 0xff, 0x3b, 0xff, 0x70, 0xff, 0x71, 0xff, 0xff, 0xff, 0x9f, 0xff, 0x27, 0xff, 0x73, 0xff, 0x33, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff,
0x03, 0xff, 0x86, 0xff, 0x1c, 0xff, 0xf0, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x18, 0xff, 0xf0, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0x03, 0xff, 0x1f, 0xff, 0x3e, 0xff, 0x78, 0xff, 0x01, 0xff, 0x07, 0xff, 0xfc, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x07, 0xff, 0x0f, 0xff, 0x0c, 0xff, 0x18, 0xff, 0x18, 0xff, 0x38, 0xff, 0x38, 0xff, 0x77, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0x31, 0xff, 0x31, 0xff, 0x38, 0xff, 0x18, 0xff, 0x1e, 0x7f, 0x0f, 0x7f, 0x03, 0x3f, 0x00, 0x1f, 0x00, 0x0f, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x1f, 0x03, 0x7f, 0x0f, 0xff, 0x3c, 0xff, 0xf0, 0xff, 0xc0, 0xff, 0x01, 0xff, 0x07, 0xff, 0x0e, 0xff, 0x18, 0xff, 0x20, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x08, 0xff, 0x38, 0xff, 0xf0, 0xff, 0xf2, 0xff, 0xe2, 0xff, 0x84, 0xff, 0x18, 0xff, 0x60, 0xff, 0x80, 0xff, 0x80, 0xff, 0x00, 0xff, 0x01, 0xff, 0x03, 0xff, 0x06, 0xff, 0x1e, 0xff, 0x3c, 0xff, 0x3c, 0xff, 0x38, 0xff, 0x01, 0xff, 0x01, 0xff, 0x86, 0xff, 0xfc, 0xff, 0xe0, 0xff, 0x80, 0xff, 0xb8, 0xff,
0x9c, 0xff, 0xc7, 0xff, 0xe0, 0xff, 0xbc, 0xff, 0x87, 0xff, 0x80, 0xff, 0xc0, 0xff, 0xf8, 0xff, 0xcf, 0xff, 0xc0, 0xff, 0x80, 0xff, 0x9c, 0xff, 0x98, 0xff, 0x90, 0xff, 0x90, 0xff, 0xc8, 0xff, 0x60, 0xff, 0x30, 0xff, 0x98, 0xff, 0x0f, 0xff, 0x0c, 0xff, 0x04, 0xff, 0x02, 0xff, 0x02, 0xff, 0x02, 0xff, 0x82, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x80, 0xff, 0xc0, 0xff, 0xe1, 0xff, 0x3f, 0xff, 0x0f, 0xff, 0x00, 0x7f, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0f, 0x01, 0x1f, 0x07, 0x3f, 0x0e, 0x3f, 0x0c, 0x7f, 0x18, 0xff, 0x30, 0xff, 0x30, 0xff, 0x60, 0xff, 0x60, 0xff, 0x60, 0xff, 0xe0, 0xff, 0xc0, 0xff, 0xc0, 0xff, 0xc0, 0xff, 0xc1, 0xff, 0xc3, 0xff, 0x61, 0xff, 0x60, 0xff, 0x38, 0xff, 0x3f, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0x43, 0xff, 0xc6, 0xff, 0x46, 0xff, 0x4c, 0xff, 0x0c, 0xff, 0x4c, 0xff, 0xcc, 0xff, 0x46, 0xff, 0x46, 0xff, 0xc1, 0xff, 0x01, 0xff, 0xc1, 0xff, 0xc1, 0xff, 0x01, 0xff,
0x41, 0xff, 0x00, 0xff, 0xc0, 0xff, 0x41, 0xff, 0x41, 0xff, 0x81, 0xff, 0x01, 0xff, 0x80, 0xff, 0x40, 0xff, 0xc0, 0xff, 0x01, 0xff, 0xc1, 0xff, 0x01, 0xff, 0x01, 0xff, 0x1f, 0xff, 0x7f, 0xff, 0x70, 0xff, 0xe7, 0xff, 0xcf, 0xff, 0xcf, 0xff, 0xc6, 0xff, 0xe6, 0xff, 0x62, 0xff, 0x71, 0xff, 0x39, 0xff, 0x1c, 0xff, 0x0c, 0x7f, 0x06, 0x3f, 0x06, 0x1f, 0x03, 0x1f, 0x01, 0x0f, 0x01, 0x07, 0x00, 0x07, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x07, 0x00, 0x0f, 0x03, 0xff, 0x00, 0xff, 0xfb, 0xff, 0x5b, 0xff, 0x78, 0xff, 0x03, 0xff, 0x79, 0xff, 0xc3, 0xff, 0xf9, 0xff, 0x00, 0xff, 0xcb, 0xff, 0xab, 0xff, 0x98, 0xff,
0x03, 0xff, 0xc8, 0xff, 0xab, 0xff, 0x9a, 0xff, 0x02, 0xff, 0xf9, 0xff, 0xc0, 0xff, 0x03, 0xff, 0xf9, 0xff, 0xab, 0xff, 0x88, 0xff, 0x03, 0xff, 0x02, 0xff, 0x03, 0x0f, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
//===========================================================================
const unsigned char PROGMEM githubLogoSprite_plus_mask[] = {
// width, height,
16, 16,
// FRAME 00
0xe0, 0xe0, 0xf8, 0xf8, 0xfc, 0xfc, 0x3e, 0xfe, 0x0e, 0xfe, 0x07, 0xff, 0x0f, 0xff, 0x1f, 0xff,
0x1f, 0xff, 0x0f, 0xff, 0x07, 0xff, 0x0e, 0xfe, 0x3e, 0xfe, 0xfc, 0xfc, 0xf8, 0xf8, 0xe0, 0xe0,
0x07, 0x07, 0x1f, 0x1f, 0x37, 0x3f, 0x64, 0x7f, 0x48, 0x7f, 0xd8, 0xff, 0x08, 0xff, 0x00, 0xff,
0x00, 0xff, 0x08, 0xff, 0xf8, 0xff, 0x78, 0x7f, 0x7c, 0x7f, 0x3f, 0x3f, 0x1f, 0x1f, 0x07, 0x07,
};
//===========================================================================
const unsigned char PROGMEM tilesSprite_plus_mask[] = {
// width, height,
16, 16,
// FRAME 00
0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0xfc, 0x70, 0xfc, 0xf0, 0xfc, 0xf0, 0xfc, 0xe0, 0xfc,
0xd0, 0xfe, 0xb8, 0xff, 0x7c, 0xff, 0x3c, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0e, 0x00, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f,
0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 01
0x00, 0x1f, 0x00, 0xbf, 0x0f, 0xff, 0x1f, 0xff, 0xbf, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff,
0xe8, 0xff, 0xdc, 0xff, 0xbf, 0xff, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x07, 0x0f, 0x02, 0x0f, 0x01, 0x0f,
0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 02
0x01, 0x8f, 0x03, 0xdf, 0x07, 0xff, 0x8f, 0xff, 0xdf, 0xff, 0xbe, 0xff, 0x7c, 0xff, 0xf8, 0xff,
0xf4, 0xff, 0xee, 0xff, 0xde, 0xff, 0x8d, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0f, 0x00, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f,
0x01, 0x0f, 0x03, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 03
0x00, 0x0f, 0x00, 0x1f, 0x03, 0xff, 0x07, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff,
0xbe, 0xff, 0xdf, 0xff, 0xef, 0xff, 0xc7, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03,
0x00, 0x07, 0x01, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 04
0x1c, 0xff, 0x1c, 0xff, 0x3c, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfe,
0xb8, 0xff, 0x7c, 0xff, 0x3e, 0xff, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x06, 0x0f, 0x08, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 05
0x0f, 0xff, 0x01, 0xff, 0x01, 0xff, 0x81, 0xff, 0xc0, 0xff, 0xe0, 0xff, 0xf0, 0xff, 0xf8, 0xff,
0x7c, 0xff, 0x3e, 0xff, 0x1f, 0xff, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0c, 0x0f, 0x0b, 0x0f, 0x07, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f,
0x00, 0x0f, 0x08, 0x0f, 0x04, 0x0f, 0x0a, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 06
0x03, 0xff, 0x07, 0xff, 0x0f, 0xff, 0x1f, 0xff, 0x3e, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff,
0xe0, 0xff, 0xc1, 0xff, 0x83, 0xff, 0x07, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x01, 0x0f,
0x03, 0x0f, 0x0b, 0x0f, 0x0d, 0x0f, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 07
0x83, 0xff, 0x83, 0xff, 0xc7, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff,
0xdf, 0xff, 0xef, 0xff, 0xc7, 0xff, 0x83, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x07,
0x01, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 08
0x1f, 0xff, 0x3e, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfe, 0xb8, 0xff,
0x7c, 0xff, 0x3c, 0xff, 0x1c, 0xff, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x0c, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 09
0x07, 0xff, 0x1b, 0xff, 0x3d, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0xe0, 0xff, 0xc0, 0xff,
0x81, 0xff, 0x01, 0xff, 0x01, 0xff, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0c, 0x0f, 0x08, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x01, 0x0f, 0x03, 0x0f, 0x07, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 10
0x07, 0xff, 0x83, 0xff, 0xc1, 0xff, 0xe0, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0x3e, 0xff,
0x1e, 0xff, 0x0d, 0xff, 0x03, 0xff, 0x07, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x0f, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f,
0x08, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 11
0x81, 0xff, 0xc6, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff,
0xef, 0xff, 0xc7, 0xff, 0x83, 0xff, 0x83, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x07, 0x01, 0x0f,
0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 12
0x3c, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfc, 0xb0, 0xfc, 0x70, 0xfc,
0x00, 0xfc, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
0x0e, 0x0f, 0x0c, 0x0f, 0x00, 0x0f, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 13
0x1f, 0xff, 0xbf, 0xff, 0xdc, 0xff, 0xe8, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0xbf, 0xff,
0x1f, 0xff, 0x0f, 0xff, 0x00, 0xbf, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0b, 0x0f, 0x07, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x02, 0x0f, 0x07, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x08, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 14
0x8f, 0xff, 0xdf, 0xff, 0xee, 0xff, 0xf4, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff,
0x8f, 0xff, 0x07, 0xff, 0x03, 0xdf, 0x01, 0x8f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x0f, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f, 0x01, 0x0f, 0x03, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 15
0xc7, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff, 0xef, 0xff,
0x07, 0xff, 0x03, 0xff, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03,
0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
| 14,900
| 13,549
|
#include "SimpleBrush3D.hpp"
#include "Color.hpp"
#include <cstring>
#include "Vulkan.hpp"
namespace lw
{
void SimpleBrush3D::setColor(const Color& color)
{
m_mainColor = color;
}
void SimpleBrush3D::setColor(f32 r, f32 g, f32 b, f32 a /*= 1.f*/)
{
m_mainColor = { r, g, b, a };
}
void SimpleBrush3D::drawVertexArray(Vertex2DArray & va)
{
/*switch (va.m_primitive)
{
case Triangles:
drawVertexArrayTriangleFill(va);
break;
case Quads:
drawVertexArrayQuadFill(va);
break;
default:
throw std::logic_error("not available");
}*/
}
void SimpleBrush3D::drawLine(const Vertex2D& start, const Vertex2D& end)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
m_lineVertexArray.push(start);
m_lineVertexArray.push(end);
}
void SimpleBrush3D::drawLine(f32 x1, f32 y1, f32 x2, f32 y2)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
m_lineVertexArray.push(Vertex2D({ x1, y1 }, m_mainColor));
m_lineVertexArray.push(Vertex2D({ x2, y2 }, m_mainColor));
}
void SimpleBrush3D::drawPoint(const Vertex2D & pos)
{
m_pointVertexArray.push(pos);
}
void SimpleBrush3D::drawPoint(f32 x, f32 y)
{
m_pointVertexArray.push(Vertex2D({ x, y }, m_mainColor));
}
void SimpleBrush3D::create(VK::Vulkan* pVulkan, u32 screenWidth, u32 screenHeight)
{
m_pVK = pVulkan;
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
m_vertexShader.create(&m_pVK->m_mainDevice, "D:/Dev/C++/My Projects/lwirth-lib/res/shaders/2Dshadervert.spv");
m_fragmentShader.create(&m_pVK->m_mainDevice, "D:/Dev/C++/My Projects/lwirth-lib/res/shaders/2Dshaderfrag.spv");
SimpleBrush3D::createPipeline();
//prepare index buffers
{
lw::List<u16> indexArrayVec = { 0, 1, 1, 2, 2, 0 };
VK::StagingBuffer stagingBuffer;
size_t dataSize = indexArrayVec.size() * sizeof(u16);
stagingBuffer.allocate(&m_pVK->m_mainDevice, dataSize);
void* dataPtr = stagingBuffer.map();
std::memcpy(dataPtr, indexArrayVec.raw(), dataSize);
stagingBuffer.unmap();
m_triangleMeshIndexBuffer.allocate(&m_pVK->m_mainDevice, &m_pVK->m_commandPool, m_pVK->m_mainDevice.getGraphicsQueue(), &stagingBuffer, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE);
stagingBuffer.destroy();
}
{
lw::List<u16> indexArrayVec = { 0, 1, 2, 2, 3, 0 };
VK::StagingBuffer stagingBuffer;
size_t dataSize = indexArrayVec.size() * sizeof(u16);
stagingBuffer.allocate(&m_pVK->m_mainDevice, dataSize);
void* dataPtr = stagingBuffer.map();
std::memcpy(dataPtr, indexArrayVec.raw(), dataSize);
stagingBuffer.unmap();
m_quadFillIndexBuffer.allocate(&m_pVK->m_mainDevice, &m_pVK->m_commandPool, m_pVK->m_mainDevice.getGraphicsQueue(), &stagingBuffer, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE);
stagingBuffer.destroy();
}
//Triangle::s_init(&m_pVK->m_device, &m_pVK->m_commandPool);
}
void SimpleBrush3D::destroy()
{
//Triangle::s_deinit();
SimpleBrush3D::destroyPipeline();
m_fragmentShader.destroy();
m_vertexShader.destroy();
}
void SimpleBrush3D::createPipeline()
{
}
void SimpleBrush3D::destroyPipeline()
{
m_pipelineTriangleFill.destroy();
m_pipelineLine.destroy();
m_pipelinePoint.destroy();
}
void SimpleBrush3D::prepare(const VK::CommandBuffer* cmd)
{
m_pCmdBuffer = cmd;
m_lineVertexArray.clear();
m_pointVertexArray.clear();
m_ready = true;
}
void SimpleBrush3D::disperse()
{
drawAllLines();
drawAllPoints();
m_pCmdBuffer = nullptr;
m_ready = false;
}
void SimpleBrush3D::resize(u32 screenWidth, u32 screenHeight)
{
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
destroyPipeline();
createPipeline();
}
void SimpleBrush3D::drawAllLines()
{
if (m_lineVertexArray.isEmpty())return;
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLine.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
//m_lineVertexArray.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, m_lineVertexArray.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), m_lineVertexArray.size(), 1, 0, 0);
}
void SimpleBrush3D::drawAllPoints()
{
if (m_pointVertexArray.isEmpty())return;
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelinePoint.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
//m_pointVertexArray.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, m_pointVertexArray.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), m_pointVertexArray.size(), 1, 0, 0);
}
void SimpleBrush3D::preparePipeline(VK::Pipeline & pipeline)
{
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
}
void SimpleBrush3D::drawVertexArrayTriangleFill(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineTriangleFill);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), va.size(), 1, 0, 0);
}
void SimpleBrush3D::drawVertexArrayTriangleMesh(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineLine);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdBindIndexBuffer(m_pCmdBuffer->raw(), m_triangleMeshIndexBuffer.raw(), 0, VK_INDEX_TYPE_UINT16);
vkCmdDrawIndexed(m_pCmdBuffer->raw(), 6, 1, 0, 0, 0);
}
void SimpleBrush3D::drawVertexArrayQuadFill(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineTriangleFill);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdBindIndexBuffer(m_pCmdBuffer->raw(), m_quadFillIndexBuffer.raw(), 0, VK_INDEX_TYPE_UINT16);
for (size_t i = 0; i < va.size(); i += 4)
{
//#TODO optimize
vkCmdDrawIndexed(m_pCmdBuffer->raw(), 6, 1, 0, i, 0);
}
}
void SimpleBrush3D::drawVertexArrayQuadMesh(Vertex2DArray & va)
{
}
}
| 7,859
| 3,523
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/oauth2/google_application_default_credentials_file.h"
#include "google/cloud/internal/getenv.h"
#include <cstdlib>
namespace {
std::string const& GoogleWellKnownAdcFilePathSuffix() {
#ifdef _WIN32
static std::string const kSuffix =
"/gcloud/application_default_credentials.json";
#else
static std::string const kSuffix =
"/.config/gcloud/application_default_credentials.json";
#endif
return kSuffix;
}
} // anonymous namespace
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace oauth2 {
std::string GoogleAdcFilePathFromEnvVarOrEmpty() {
auto override_value = google::cloud::internal::GetEnv(GoogleAdcEnvVar());
if (override_value.has_value()) {
return *override_value;
}
return "";
}
std::string GoogleAdcFilePathFromWellKnownPathOrEmpty() {
// Allow mocking out this value for testing.
auto override_path =
google::cloud::internal::GetEnv(GoogleGcloudAdcFileEnvVar());
if (override_path.has_value()) {
return *override_path;
}
// Search well known gcloud ADC path.
auto adc_path_root = google::cloud::internal::GetEnv(GoogleAdcHomeEnvVar());
if (adc_path_root.has_value()) {
return *adc_path_root + GoogleWellKnownAdcFilePathSuffix();
}
return "";
}
} // namespace oauth2
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 2,021
| 639
|
// ObserverPattern.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class IDisplayObserver
{
public:
virtual void update(int t, int p, int h) {}
};
class CWeatherData
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
vector<IDisplayObserver*> obsV;
void notifyObservers()
{
for (IDisplayObserver* ob : obsV)
ob->update(nTemp, nPressure, nHumidity);
}
public:
void addObserver(IDisplayObserver* o)
{
obsV.push_back(o);
}
void removeObserver(IDisplayObserver* o)
{
for (auto it = obsV.cbegin(); it != obsV.cend(); ++it)
{
if (*it == o)
{
obsV.erase(it);
break;
}
}
}
void setWeather(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
notifyObservers();
}
};
class CDisp1 : IDisplayObserver
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
CWeatherData* data;
void display()
{
cout << "Displaying from CDisp1 obj: ";
cout << "Temperature :" << nTemp << "\t Pressure :" << nPressure << "\t Humidty :" << nHumidity << endl;
}
public:
CDisp1(CWeatherData* data)
{
cout << "Disp1 obj created!" << endl;
this->data = data;
data->addObserver(this);
}
~CDisp1()
{
cout << "Disp1 obj destroyed!" << endl;
data->removeObserver(this);
}
void update(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
display();
}
};
class CDisp2 : IDisplayObserver
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
CWeatherData* data;
void display()
{
cout << "Displaying from CDisp2 obj: ";
cout << "Temperature :" << nTemp << "\t Pressure :" << nPressure << "\t Humidty :" << nHumidity << endl;
}
public:
CDisp2(CWeatherData* data)
{
cout << "Disp2 obj created!" << endl;
this->data = data;
data->addObserver(this);
}
~CDisp2()
{
cout << "Disp2 obj destroyed!" << endl;
data->removeObserver(this);
}
void update(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
display();
}
};
int main()
{
CWeatherData* data = new CWeatherData();
CDisp1* d1 = new CDisp1(data);
data->setWeather(10, 15, 19);
CDisp2* d2 = new CDisp2(data);
data->setWeather(50, 55, 59);
delete d1;
data->setWeather(60, 65, 69);
getchar();
return 0;
}
| 2,324
| 1,077
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "inc/Viewport.hpp"
using namespace Microsoft::Console::Types;
Viewport::Viewport(const SMALL_RECT sr) noexcept :
_sr(sr)
{
}
Viewport::Viewport(const Viewport& other) noexcept :
_sr(other._sr)
{
}
Viewport Viewport::Empty() noexcept
{
return Viewport();
}
Viewport Viewport::FromInclusive(const SMALL_RECT sr) noexcept
{
return Viewport(sr);
}
Viewport Viewport::FromExclusive(const SMALL_RECT sr) noexcept
{
SMALL_RECT _sr = sr;
_sr.Bottom -= 1;
_sr.Right -= 1;
return Viewport::FromInclusive(_sr);
}
// Function Description:
// - Creates a new Viewport at the given origin, with the given dimensions.
// Arguments:
// - origin: The origin of the new Viewport. Becomes the Viewport's Left, Top
// - width: The width of the new viewport
// - height: The height of the new viewport
// Return Value:
// - a new Viewport at the given origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD origin,
const short width,
const short height) noexcept
{
return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + width, origin.Y + height });
}
// Function Description:
// - Creates a new Viewport at the given origin, with the given dimensions.
// Arguments:
// - origin: The origin of the new Viewport. Becomes the Viewport's Left, Top
// - dimensions: A coordinate containing the width and height of the new viewport
// in the x and y coordinates respectively.
// Return Value:
// - a new Viewport at the given origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD origin,
const COORD dimensions) noexcept
{
return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + dimensions.X, origin.Y + dimensions.Y });
}
// Function Description:
// - Creates a new Viewport at the origin, with the given dimensions.
// Arguments:
// - dimensions: A coordinate containing the width and height of the new viewport
// in the x and y coordinates respectively.
// Return Value:
// - a new Viewport at the origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD dimensions) noexcept
{
return Viewport::FromDimensions({ 0 }, dimensions);
}
// Method Description:
// - Creates a Viewport equivalent to a 1x1 rectangle at the given coordinate.
// Arguments:
// - origin: origin of the rectangle to create.
// Return Value:
// - a 1x1 Viewport at the given coordinate
Viewport Viewport::FromCoord(const COORD origin) noexcept
{
return Viewport::FromInclusive({ origin.X, origin.Y, origin.X, origin.Y });
}
SHORT Viewport::Left() const noexcept
{
return _sr.Left;
}
SHORT Viewport::RightInclusive() const noexcept
{
return _sr.Right;
}
SHORT Viewport::RightExclusive() const noexcept
{
return _sr.Right + 1;
}
SHORT Viewport::Top() const noexcept
{
return _sr.Top;
}
SHORT Viewport::BottomInclusive() const noexcept
{
return _sr.Bottom;
}
SHORT Viewport::BottomExclusive() const noexcept
{
return _sr.Bottom + 1;
}
SHORT Viewport::Height() const noexcept
{
return BottomExclusive() - Top();
}
SHORT Viewport::Width() const noexcept
{
return RightExclusive() - Left();
}
// Method Description:
// - Get a coord representing the origin of this viewport.
// Arguments:
// - <none>
// Return Value:
// - the coordinates of this viewport's origin.
COORD Viewport::Origin() const noexcept
{
return { Left(), Top() };
}
// Method Description:
// - For Accessibility, get a COORD representing the end of this viewport in exclusive terms.
// - This is needed to represent an exclusive endpoint in UiaTextRange that includes the last
// COORD's text in the buffer at (RightInclusive(), BottomInclusive())
// Arguments:
// - <none>
// Return Value:
// - the coordinates of this viewport's end.
COORD Viewport::EndExclusive() const noexcept
{
return { Left(), BottomExclusive() };
}
// Method Description:
// - Get a coord representing the dimensions of this viewport.
// Arguments:
// - <none>
// Return Value:
// - the dimensions of this viewport.
COORD Viewport::Dimensions() const noexcept
{
return { Width(), Height() };
}
// Method Description:
// - Determines if the given viewport fits within this viewport.
// Arguments:
// - other - The viewport to fit inside this one
// Return Value:
// - True if it fits. False otherwise.
bool Viewport::IsInBounds(const Viewport& other) const noexcept
{
return other.Left() >= Left() && other.Left() <= RightInclusive() &&
other.RightInclusive() >= Left() && other.RightInclusive() <= RightInclusive() &&
other.Top() >= Top() && other.Top() <= other.BottomInclusive() &&
other.BottomInclusive() >= Top() && other.BottomInclusive() <= BottomInclusive();
}
// Method Description:
// - Determines if the given coordinate position lies within this viewport.
// Arguments:
// - pos - Coordinate position
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it lies inside the viewport. False otherwise.
bool Viewport::IsInBounds(const COORD& pos, bool allowEndExclusive) const noexcept
{
if (allowEndExclusive && pos == EndExclusive())
{
return true;
}
return pos.X >= Left() && pos.X < RightExclusive() &&
pos.Y >= Top() && pos.Y < BottomExclusive();
}
// Method Description:
// - Clamps a coordinate position into the inside of this viewport.
// Arguments:
// - pos - coordinate to update/clamp
// Return Value:
// - <none>
void Viewport::Clamp(COORD& pos) const
{
THROW_HR_IF(E_NOT_VALID_STATE, !IsValid()); // we can't clamp to an invalid viewport.
pos.X = std::clamp(pos.X, Left(), RightInclusive());
pos.Y = std::clamp(pos.Y, Top(), BottomInclusive());
}
// Method Description:
// - Clamps a viewport into the inside of this viewport.
// Arguments:
// - other - Viewport to clamp to the inside of this viewport
// Return Value:
// - Clamped viewport
Viewport Viewport::Clamp(const Viewport& other) const noexcept
{
auto clampMe = other.ToInclusive();
clampMe.Left = std::clamp(clampMe.Left, Left(), RightInclusive());
clampMe.Right = std::clamp(clampMe.Right, Left(), RightInclusive());
clampMe.Top = std::clamp(clampMe.Top, Top(), BottomInclusive());
clampMe.Bottom = std::clamp(clampMe.Bottom, Top(), BottomInclusive());
return Viewport::FromInclusive(clampMe);
}
// Method Description:
// - Moves the coordinate given by the number of positions and
// in the direction given (repeated increment or decrement)
// Arguments:
// - move - Magnitude and direction of the move
// - pos - The coordinate position to adjust
// Return Value:
// - True if we successfully moved the requested distance. False if we had to stop early.
// - If False, we will restore the original position to the given coordinate.
bool Viewport::MoveInBounds(const ptrdiff_t move, COORD& pos) const noexcept
{
const auto backup = pos;
bool success = true; // If nothing happens, we're still successful (e.g. add = 0)
for (int i = 0; i < move; i++)
{
success = IncrementInBounds(pos);
// If an operation fails, break.
if (!success)
{
break;
}
}
for (int i = 0; i > move; i--)
{
success = DecrementInBounds(pos);
// If an operation fails, break.
if (!success)
{
break;
}
}
// If any operation failed, revert to backed up state.
if (!success)
{
pos = backup;
}
return success;
}
// Method Description:
// - Increments the given coordinate within the bounds of this viewport.
// Arguments:
// - pos - Coordinate position that will be incremented, if it can be.
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be incremented. False if it would move outside.
bool Viewport::IncrementInBounds(COORD& pos, bool allowEndExclusive) const noexcept
{
return WalkInBounds(pos, { XWalk::LeftToRight, YWalk::TopToBottom }, allowEndExclusive);
}
// Method Description:
// - Increments the given coordinate within the bounds of this viewport
// rotating around to the top when reaching the bottom right corner.
// Arguments:
// - pos - Coordinate position that will be incremented.
// Return Value:
// - True if it could be incremented inside the viewport.
// - False if it rolled over from the bottom right corner back to the top.
bool Viewport::IncrementInBoundsCircular(COORD& pos) const noexcept
{
return WalkInBoundsCircular(pos, { XWalk::LeftToRight, YWalk::TopToBottom });
}
// Method Description:
// - Decrements the given coordinate within the bounds of this viewport.
// Arguments:
// - pos - Coordinate position that will be incremented, if it can be.
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be incremented. False if it would move outside.
bool Viewport::DecrementInBounds(COORD& pos, bool allowEndExclusive) const noexcept
{
return WalkInBounds(pos, { XWalk::RightToLeft, YWalk::BottomToTop }, allowEndExclusive);
}
// Method Description:
// - Decrements the given coordinate within the bounds of this viewport
// rotating around to the bottom right when reaching the top left corner.
// Arguments:
// - pos - Coordinate position that will be decremented.
// Return Value:
// - True if it could be decremented inside the viewport.
// - False if it rolled over from the top left corner back to the bottom right.
bool Viewport::DecrementInBoundsCircular(COORD& pos) const noexcept
{
return WalkInBoundsCircular(pos, { XWalk::RightToLeft, YWalk::BottomToTop });
}
// Routine Description:
// - Compares two coordinate positions to determine whether they're the same, left, or right within the given buffer size
// Arguments:
// - first- The first coordinate position
// - second - The second coordinate position
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - Negative if First is to the left of the Second.
// - 0 if First and Second are the same coordinate.
// - Positive if First is to the right of the Second.
// - This is so you can do s_CompareCoords(first, second) <= 0 for "first is left or the same as second".
// (the < looks like a left arrow :D)
// - The magnitude of the result is the distance between the two coordinates when typing characters into the buffer (left to right, top to bottom)
int Viewport::CompareInBounds(const COORD& first, const COORD& second, bool allowEndExclusive) const noexcept
{
// Assert that our coordinates are within the expected boundaries
FAIL_FAST_IF(!IsInBounds(first, allowEndExclusive));
FAIL_FAST_IF(!IsInBounds(second, allowEndExclusive));
// First set the distance vertically
// If first is on row 4 and second is on row 6, first will be -2 rows behind second * an 80 character row would be -160.
// For the same row, it'll be 0 rows * 80 character width = 0 difference.
int retVal = (first.Y - second.Y) * Width();
// Now adjust for horizontal differences
// If first is in position 15 and second is in position 30, first is -15 left in relation to 30.
retVal += (first.X - second.X);
// Further notes:
// If we already moved behind one row, this will help correct for when first is right of second.
// For example, with row 4, col 79 and row 5, col 0 as first and second respectively, the distance is -1.
// Assume the row width is 80.
// Step one will set the retVal as -80 as first is one row behind the second.
// Step two will then see that first is 79 - 0 = +79 right of second and add 79
// The total is -80 + 79 = -1.
return retVal;
}
// Method Description:
// - Walks the given coordinate within the bounds of this viewport in the specified
// X and Y directions.
// Arguments:
// - pos - Coordinate position that will be adjusted, if it can be.
// - dir - Walking direction specifying which direction to go when reaching the end of a row/column
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be adjusted as specified and remain in bounds. False if it would move outside.
bool Viewport::WalkInBounds(COORD& pos, const WalkDir dir, bool allowEndExclusive) const noexcept
{
auto copy = pos;
if (WalkInBoundsCircular(copy, dir, allowEndExclusive))
{
pos = copy;
return true;
}
else
{
return false;
}
}
// Method Description:
// - Walks the given coordinate within the bounds of this viewport
// rotating around to the opposite corner when reaching the final corner
// in the specified direction.
// Arguments:
// - pos - Coordinate position that will be adjusted.
// - dir - Walking direction specifying which direction to go when reaching the end of a row/column
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be adjusted inside the viewport.
// - False if it rolled over from the final corner back to the initial corner
// for the specified walk direction.
bool Viewport::WalkInBoundsCircular(COORD& pos, const WalkDir dir, bool allowEndExclusive) const noexcept
{
// Assert that the position given fits inside this viewport.
FAIL_FAST_IF(!IsInBounds(pos, allowEndExclusive));
if (dir.x == XWalk::LeftToRight)
{
if (allowEndExclusive && pos.X == Left() && pos.Y == BottomExclusive())
{
pos.Y = Top();
return false;
}
else if (pos.X == RightInclusive())
{
pos.X = Left();
if (dir.y == YWalk::TopToBottom)
{
pos.Y++;
if (allowEndExclusive && pos.Y == BottomExclusive())
{
return true;
}
else if (pos.Y > BottomInclusive())
{
pos.Y = Top();
return false;
}
}
else
{
pos.Y--;
if (pos.Y < Top())
{
pos.Y = BottomInclusive();
return false;
}
}
}
else
{
pos.X++;
}
}
else
{
if (pos.X == Left())
{
pos.X = RightInclusive();
if (dir.y == YWalk::TopToBottom)
{
pos.Y++;
if (pos.Y > BottomInclusive())
{
pos.Y = Top();
return false;
}
}
else
{
pos.Y--;
if (pos.Y < Top())
{
pos.Y = BottomInclusive();
return false;
}
}
}
else
{
pos.X--;
}
}
return true;
}
// Routine Description:
// - If walking through a viewport, one might want to know the origin
// for the direction walking.
// - For example, for walking up and to the left (bottom right corner
// to top left corner), the origin would start at the bottom right.
// Arguments:
// - dir - The direction one intends to walk through the viewport
// Return Value:
// - The origin for the walk to reach every position without circling
// if using this same viewport with the `WalkInBounds` methods.
COORD Viewport::GetWalkOrigin(const WalkDir dir) const noexcept
{
COORD origin{ 0 };
origin.X = dir.x == XWalk::LeftToRight ? Left() : RightInclusive();
origin.Y = dir.y == YWalk::TopToBottom ? Top() : BottomInclusive();
return origin;
}
// Routine Description:
// - Given two viewports that will be used for copying data from one to the other (source, target),
// determine which direction you will have to walk through them to ensure that an overlapped copy
// won't erase data in the source that hasn't yet been read and copied into the target at the same
// coordinate offset position from their respective origins.
// - Note: See elaborate ASCII-art comment inside the body of this function for more details on how/why this works.
// Arguments:
// - source - The viewport representing the region that will be copied from
// - target - The viewport representing the region that will be copied to
// Return Value:
// - The direction to walk through both viewports from the walk origins to touch every cell and not
// accidentally overwrite something that hasn't been read yet. (use with GetWalkOrigin and WalkInBounds)
Viewport::WalkDir Viewport::DetermineWalkDirection(const Viewport& source, const Viewport& target) noexcept
{
// We can determine which direction we need to walk based on solely the origins of the two rectangles.
// I'll use a few examples to prove the situation.
//
// For the cardinal directions, let's start with this sample:
//
// source target
// origin 0,0 origin 4,0
// | |
// v V
// +--source-----+--target--------- +--source-----+--target---------
// | A B C D | E | 1 2 3 4 | becomes | A B C D | A | B C D E |
// | F G H I | J | 5 6 7 8 | =========> | F G H I | F | G H I J |
// | K L M N | O | 9 $ % @ | | K L M N | K | L M N O |
// -------------------------------- --------------------------------
//
// The source and target overlap in the 5th column (X=4).
// To ensure that we don't accidentally write over the source
// data before we copy it into the target, we want to start by
// reading that column (a.k.a. writing to the farthest away column
// of the target).
//
// This means we want to copy from right to left.
// Top to bottom and bottom to top don't really matter for this since it's
// a cardinal direction shift.
//
// If we do the right most column first as so...
//
// +--source-----+--target--------- +--source-----+--target---------
// | A B C D | E | 1 2 3 4 | step 1 | A B C D | E | 1 2 3 E |
// | F G H I | J | 5 6 7 8 | =========> | F G H I | J | 5 6 7 J |
// | K L M N | O | 9 $ % @ | | K L M N | O | 9 $ % O |
// -------------------------------- --------------------------------
//
// ... then we can see that the EJO column is safely copied first out of the way and
// can be overwritten on subsequent steps without losing anything.
// The rest of the columns aren't overlapping, so they'll be fine.
//
// But we extrapolate this logic to follow for rectangles that overlap more columns, up
// to and including only leaving one column not overlapped...
//
// source target
// origin origin
// 0,0 / 1,0
// | /
// v v
// +----+------target- +----+------target-
// | A | B C D | E | becomes | A | A B C | D |
// | F | G H I | J | =========> | F | F G H | I |
// | K | L M N | O | | K | K L M | N |
// ---source---------- ---source----------
//
// ... will still be OK following the same Right-To-Left rule as the first move.
//
// +----+------target- +----+------target-
// | A | B C D | E | step 1 | A | B C D | D |
// | F | G H I | J | =========> | F | G H I | I |
// | K | L M N | O | | K | L M N | N |
// ---source---------- ---source----------
//
// The DIN column from the source was moved to the target as the right most column
// of both rectangles. Now it is safe to iterate to the second column from the right
// and proceed with moving CHM on top of the source DIN as it was already moved.
//
// +----+------target- +----+------target-
// | A | B C D | E | step 2 | A | B C C | D |
// | F | G H I | J | =========> | F | G H H | I |
// | K | L M N | O | | K | L M M | N |
// ---source---------- ---source----------
//
// Continue walking right to left (an exercise left to the reader,) and we never lose
// any source data before it reaches the target with the Right To Left pattern.
//
// We notice that the target origin was Right of the source origin in this circumstance,
// (target origin X is > source origin X)
// so it is asserted that targets right of sources means that we should "walk" right to left.
//
// Reviewing the above, it doesn't appear to matter if we go Top to Bottom or Bottom to Top,
// so the conclusion is drawn that it doesn't matter as long as the source and target origin
// Y values are the same.
//
// Also, extrapolating this cardinal direction move to the other 3 cardinal directions,
// it should follow that they would follow the same rules.
// That is, a target left of a source, or a Westbound move, opposite of the above Eastbound move,
// should be "walked" left to right.
// (target origin X is < source origin X)
//
// We haven't given the sample yet that Northbound and Southbound moves are the same, but we
// could reason that the same logic applies and the conclusion would be a Northbound move
// would walk from the target toward the source again... a.k.a. Top to Bottom.
// (target origin Y is < source origin Y)
// Then the Southbound move would be the opposite, Bottom to Top.
// (target origin Y is > source origin Y)
//
// To confirm, let's try one more example but moving both at once in an ordinal direction Northeast.
//
// target
// origin 1, 0
// |
// v
// +----target-- +----target--
// source A | B C | A | D E |
// origin-->+------------ | becomes +------------ |
// 0, 1 | D | E | F | =========> | D | G | H |
// | ------------- | -------------
// | G H | I | G H | I
// --source----- --source-----
//
// Following our supposed rules from above, we have...
// Source Origin X = 0, Y = 1
// Target Origin X = 1, Y = 0
//
// Source Origin X < Target Origin X which means Right to Left
// Source Origin Y > Target Origin Y which means Top to Bottom
//
// So the first thing we should copy is the Top and Right most
// value from source to target.
//
// +----target-- +----target--
// A | B C | A | B E |
// +------------ | step 1 +------------ |
// | D | E | F | =========> | D | E | F |
// | ------------- | -------------
// | G H | I | G H | I
// --source----- --source-----
//
// And look. The E which was in the overlapping part of the source
// is the first thing copied out of the way and we're safe to copy the rest.
//
// We assume that this pattern then applies to all ordinal directions as well
// and it appears our rules hold.
//
// We've covered all cardinal and ordinal directions... all that is left is two
// rectangles of the same size and origin... and in that case, it doesn't matter
// as nothing is moving and therefore can't be covered up or lost.
//
// Therefore, we will codify our inequalities below as determining the walk direction
// for a given source and target viewport and use the helper `GetWalkOrigin`
// to return the place that we should start walking from when the copy commences.
const auto sourceOrigin = source.Origin();
const auto targetOrigin = target.Origin();
return Viewport::WalkDir{ targetOrigin.X < sourceOrigin.X ? Viewport::XWalk::LeftToRight : Viewport::XWalk::RightToLeft,
targetOrigin.Y < sourceOrigin.Y ? Viewport::YWalk::TopToBottom : Viewport::YWalk::BottomToTop };
}
// Method Description:
// - Clips the input rectangle to our bounds. Assumes that the input rectangle
//is an exclusive rectangle.
// Arguments:
// - psr: a pointer to an exclusive rect to clip.
// Return Value:
// - true iff the clipped rectangle is valid (with a width and height both >0)
bool Viewport::TrimToViewport(_Inout_ SMALL_RECT* const psr) const noexcept
{
psr->Left = std::max(psr->Left, Left());
psr->Right = std::min(psr->Right, RightExclusive());
psr->Top = std::max(psr->Top, Top());
psr->Bottom = std::min(psr->Bottom, BottomExclusive());
return psr->Left < psr->Right && psr->Top < psr->Bottom;
}
// Method Description:
// - Translates the input SMALL_RECT out of our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - psr: a pointer to a SMALL_RECT the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertToOrigin(_Inout_ SMALL_RECT* const psr) const noexcept
{
const short dx = Left();
const short dy = Top();
psr->Left -= dx;
psr->Right -= dx;
psr->Top -= dy;
psr->Bottom -= dy;
}
// Method Description:
// - Translates the input coordinate out of our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - pcoord: a pointer to a coordinate the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertToOrigin(_Inout_ COORD* const pcoord) const noexcept
{
pcoord->X -= Left();
pcoord->Y -= Top();
}
// Method Description:
// - Translates the input SMALL_RECT to our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - psr: a pointer to a SMALL_RECT the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertFromOrigin(_Inout_ SMALL_RECT* const psr) const noexcept
{
const short dx = Left();
const short dy = Top();
psr->Left += dx;
psr->Right += dx;
psr->Top += dy;
psr->Bottom += dy;
}
// Method Description:
// - Translates the input coordinate to our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - pcoord: a pointer to a coordinate the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertFromOrigin(_Inout_ COORD* const pcoord) const noexcept
{
pcoord->X += Left();
pcoord->Y += Top();
}
// Method Description:
// - Returns an exclusive SMALL_RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an exclusive SMALL_RECT equivalent to this viewport.
SMALL_RECT Viewport::ToExclusive() const noexcept
{
return { Left(), Top(), RightExclusive(), BottomExclusive() };
}
// Method Description:
// - Returns an exclusive RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an exclusive RECT equivalent to this viewport.
RECT Viewport::ToRect() const noexcept
{
RECT r{ 0 };
r.left = Left();
r.top = Top();
r.right = RightExclusive();
r.bottom = BottomExclusive();
return r;
}
// Method Description:
// - Returns an inclusive SMALL_RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an inclusive SMALL_RECT equivalent to this viewport.
SMALL_RECT Viewport::ToInclusive() const noexcept
{
return { Left(), Top(), RightInclusive(), BottomInclusive() };
}
// Method Description:
// - Returns a new viewport representing this viewport at the origin.
// For example:
// this = {6, 5, 11, 11} (w, h = 5, 6)
// result = {0, 0, 5, 6} (w, h = 5, 6)
// Arguments:
// - <none>
// Return Value:
// - a new viewport with the same dimensions as this viewport with top, left = 0, 0
Viewport Viewport::ToOrigin() const noexcept
{
Viewport returnVal = *this;
ConvertToOrigin(&returnVal._sr);
return returnVal;
}
// Method Description:
// - Translates another viewport to this viewport's coordinate space.
// For example:
// this = {5, 6, 7, 8} (w,h = 1, 1)
// other = {6, 5, 11, 11} (w, h = 5, 6)
// result = {1, -1, 6, 5} (w, h = 5, 6)
// Arguments:
// - other: the viewport to convert to this coordinate space
// Return Value:
// - the input viewport in a the coordinate space with origin at (this.Top, this.Left)
[[nodiscard]] Viewport Viewport::ConvertToOrigin(const Viewport& other) const noexcept
{
Viewport returnVal = other;
ConvertToOrigin(&returnVal._sr);
return returnVal;
}
// Method Description:
// - Translates another viewport out of this viewport's coordinate space.
// For example:
// this = {5, 6, 7, 8} (w,h = 1, 1)
// other = {0, 0, 5, 6} (w, h = 5, 6)
// result = {5, 6, 10, 12} (w, h = 5, 6)
// Arguments:
// - other: the viewport to convert out of this coordinate space
// Return Value:
// - the input viewport in a the coordinate space with origin at (0, 0)
[[nodiscard]] Viewport Viewport::ConvertFromOrigin(const Viewport& other) const noexcept
{
Viewport returnVal = other;
ConvertFromOrigin(&returnVal._sr);
return returnVal;
}
// Function Description:
// - Translates a given Viewport by the specified coord amount. Does the
// addition with safemath.
// Arguments:
// - original: The initial viewport to translate. Is unmodified by this operation.
// - delta: The amount to translate the original rect by, in both the x and y coordinates.
// Return Value:
// - The offset viewport by the given delta.
// - NOTE: Throws on safe math failure.
[[nodiscard]] Viewport Viewport::Offset(const Viewport& original, const COORD delta)
{
// If there's no delta, do nothing.
if (delta.X == 0 && delta.Y == 0)
{
return original;
}
SHORT newTop = original._sr.Top;
SHORT newLeft = original._sr.Left;
SHORT newRight = original._sr.Right;
SHORT newBottom = original._sr.Bottom;
THROW_IF_FAILED(ShortAdd(newLeft, delta.X, &newLeft));
THROW_IF_FAILED(ShortAdd(newRight, delta.X, &newRight));
THROW_IF_FAILED(ShortAdd(newTop, delta.Y, &newTop));
THROW_IF_FAILED(ShortAdd(newBottom, delta.Y, &newBottom));
return Viewport({ newLeft, newTop, newRight, newBottom });
}
// Function Description:
// - Returns a viewport created from the union of both the parameter viewports.
// The result extends from the leftmost extent of either rect to the
// rightmost extent of either rect, and from the lowest top value to the
// highest bottom value, and everything in between.
// Arguments:
// - lhs: one of the viewports to or together
// - rhs: the other viewport to or together
// Return Value:
// - a Viewport representing the union of the other two viewports.
[[nodiscard]] Viewport Viewport::Union(const Viewport& lhs, const Viewport& rhs) noexcept
{
const auto leftValid = lhs.IsValid();
const auto rightValid = rhs.IsValid();
// If neither are valid, return empty.
if (!leftValid && !rightValid)
{
return Viewport::Empty();
}
// If left isn't valid, then return just the right.
else if (!leftValid)
{
return rhs;
}
// If right isn't valid, then return just the left.
else if (!rightValid)
{
return lhs;
}
// Otherwise, everything is valid. Find the actual union.
else
{
const auto left = std::min(lhs.Left(), rhs.Left());
const auto top = std::min(lhs.Top(), rhs.Top());
const auto right = std::max(lhs.RightInclusive(), rhs.RightInclusive());
const auto bottom = std::max(lhs.BottomInclusive(), rhs.BottomInclusive());
return Viewport({ left, top, right, bottom });
}
}
// Function Description:
// - Creates a viewport from the intersection fo both the parameter viewports.
// The result will be the smallest area that fits within both rectangles.
// Arguments:
// - lhs: one of the viewports to intersect
// - rhs: the other viewport to intersect
// Return Value:
// - a Viewport representing the intersection of the other two, or an empty viewport if there's no intersection.
[[nodiscard]] Viewport Viewport::Intersect(const Viewport& lhs, const Viewport& rhs) noexcept
{
const auto left = std::max(lhs.Left(), rhs.Left());
const auto top = std::max(lhs.Top(), rhs.Top());
const auto right = std::min(lhs.RightInclusive(), rhs.RightInclusive());
const auto bottom = std::min(lhs.BottomInclusive(), rhs.BottomInclusive());
const Viewport intersection({ left, top, right, bottom });
// What we calculated with min/max might not actually represent a valid viewport that has area.
// If we calculated something that is nonsense (invalid), then just return the empty viewport.
if (!intersection.IsValid())
{
return Viewport::Empty();
}
else
{
// If it was valid, give back whatever we created.
return intersection;
}
}
// Routine Description:
// - Returns a list of Viewports representing the area from the `original` Viewport that was NOT a part of
// the given `removeMe` Viewport. It can require multiple Viewports to represent the remaining
// area as a "region".
// Arguments:
// - original - The overall viewport to start from.
// - removeMe - The space that should be taken out of the main Viewport.
// Return Value:
// - Array of 4 Viewports representing non-overlapping segments of the remaining area
// that was covered by `main` before the regional area of `removeMe` was taken out.
// - You must check that each viewport .IsValid() before using it.
[[nodiscard]] SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& removeMe) noexcept
try
{
SomeViewports result;
// We could have up to four rectangles describing the area resulting when you take removeMe out of main.
// Find the intersection of the two so we know which bits of removeMe are actually applicable
// to the original rectangle for subtraction purposes.
const auto intersection = Viewport::Intersect(original, removeMe);
// If there's no intersection, there's nothing to remove.
if (!intersection.IsValid())
{
// Just put the original rectangle into the results and return early.
result.push_back(original);
}
// If the original rectangle matches the intersection, there is nothing to return.
else if (original != intersection)
{
// Generate our potential four viewports that represent the region of the original that falls outside of the remove area.
// We will bias toward generating wide rectangles over tall rectangles (if possible) so that optimizations that apply
// to manipulating an entire row at once can be realized by other parts of the console code. (i.e. Run Length Encoding)
// In the following examples, the found remaining regions are represented by:
// T = Top B = Bottom L = Left R = Right
//
// 4 Sides but Identical:
// |---------original---------| |---------original---------|
// | | | |
// | | | |
// | | | |
// | | ======> | intersect | ======> early return of nothing
// | | | |
// | | | |
// | | | |
// |---------removeMe---------| |--------------------------|
//
// 4 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |---------| | | |---------| | |LLLLLLLL|---------|RRRRRRR|
// | |removeMe | | ======> | |intersect| | ======> |LLLLLLLL| |RRRRRRR|
// | |---------| | | |---------| | |LLLLLLLL|---------|RRRRRRR|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// |--------------------------| |--------------------------| |--------------------------|
//
// 3 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | |removeMe | ======> | |intersect | ======> |LLLLLLLL| |
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// |--------------------------| |--------------------------| |--------------------------|
//
// 2 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | |removeMe | ======> | |intersect | ======> |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// |--------| | |--------------------------| |--------------------------|
// | |
// |--------------------|
//
// 1 Side:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// |-----------------------------| |--------------------------| |--------------------------|
// | removeMe | ======> | intersect | ======> | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | |--------------------------| |--------------------------|
// | |
// |-----------------------------|
//
// 0 Sides:
// |---------original---------| |---------original---------|
// | | | |
// | | | |
// | | | |
// | | ======> | | ======> early return of Original
// | | | |
// | | | |
// | | | |
// |--------------------------| |--------------------------|
//
//
// |---------------|
// | removeMe |
// |---------------|
// We generate these rectangles by the original and intersection points, but some of them might be empty when the intersection
// lines up with the edge of the original. That's OK. That just means that the subtraction didn't leave anything behind.
// We will filter those out below when adding them to the result.
const auto top = Viewport({ original.Left(), original.Top(), original.RightInclusive(), intersection.Top() - 1 });
const auto bottom = Viewport({ original.Left(), intersection.BottomExclusive(), original.RightInclusive(), original.BottomInclusive() });
const auto left = Viewport({ original.Left(), intersection.Top(), intersection.Left() - 1, intersection.BottomInclusive() });
const auto right = Viewport({ intersection.RightExclusive(), intersection.Top(), original.RightInclusive(), intersection.BottomInclusive() });
if (top.IsValid())
{
result.push_back(top);
}
if (bottom.IsValid())
{
result.push_back(bottom);
}
if (left.IsValid())
{
result.push_back(left);
}
if (right.IsValid())
{
result.push_back(right);
}
}
return result;
}
CATCH_FAIL_FAST()
// Method Description:
// - Returns true if the rectangle described by this Viewport has internal space
// - i.e. it has a positive, non-zero height and width.
bool Viewport::IsValid() const noexcept
{
return Height() > 0 && Width() > 0;
}
| 45,523
| 12,990
|
//
// detail/reactive_socket_service_base.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
#define ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_HAS_IOCP) \
&& !defined(ASIO_WINDOWS_RUNTIME)
#include "asio/detail/reactive_socket_service_base.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
reactive_socket_service_base::reactive_socket_service_base(
asio::io_service& io_service)
: reactor_(use_service<reactor>(io_service))
{
reactor_.init_task();
}
void reactive_socket_service_base::shutdown_service()
{
}
void reactive_socket_service_base::construct(
reactive_socket_service_base::base_implementation_type& impl)
{
impl.socket_ = invalid_socket;
impl.state_ = 0;
}
void reactive_socket_service_base::base_move_construct(
reactive_socket_service_base::base_implementation_type& impl,
reactive_socket_service_base::base_implementation_type& other_impl)
{
impl.socket_ = other_impl.socket_;
other_impl.socket_ = invalid_socket;
impl.state_ = other_impl.state_;
other_impl.state_ = 0;
reactor_.move_descriptor(impl.socket_,
impl.reactor_data_, other_impl.reactor_data_);
}
void reactive_socket_service_base::base_move_assign(
reactive_socket_service_base::base_implementation_type& impl,
reactive_socket_service_base& other_service,
reactive_socket_service_base::base_implementation_type& other_impl)
{
destroy(impl);
impl.socket_ = other_impl.socket_;
other_impl.socket_ = invalid_socket;
impl.state_ = other_impl.state_;
other_impl.state_ = 0;
other_service.reactor_.move_descriptor(impl.socket_,
impl.reactor_data_, other_impl.reactor_data_);
}
void reactive_socket_service_base::destroy(
reactive_socket_service_base::base_implementation_type& impl)
{
if (impl.socket_ != invalid_socket)
{
ASIO_HANDLER_OPERATION(("socket", &impl, "close"));
reactor_.deregister_descriptor(impl.socket_, impl.reactor_data_,
(impl.state_ & socket_ops::possible_dup) == 0);
asio::error_code ignored_ec;
socket_ops::close(impl.socket_, impl.state_, true, ignored_ec);
}
}
asio::error_code reactive_socket_service_base::close(
reactive_socket_service_base::base_implementation_type& impl,
asio::error_code& ec)
{
if (is_open(impl))
{
ASIO_HANDLER_OPERATION(("socket", &impl, "close"));
reactor_.deregister_descriptor(impl.socket_, impl.reactor_data_,
(impl.state_ & socket_ops::possible_dup) == 0);
}
socket_ops::close(impl.socket_, impl.state_, false, ec);
// The descriptor is closed by the OS even if close() returns an error.
//
// (Actually, POSIX says the state of the descriptor is unspecified. On
// Linux the descriptor is apparently closed anyway; e.g. see
// http://lkml.org/lkml/2005/9/10/129
// We'll just have to assume that other OSes follow the same behaviour. The
// known exception is when Windows's closesocket() function fails with
// WSAEWOULDBLOCK, but this case is handled inside socket_ops::close().
construct(impl);
return ec;
}
asio::error_code reactive_socket_service_base::cancel(
reactive_socket_service_base::base_implementation_type& impl,
asio::error_code& ec)
{
if (!is_open(impl))
{
ec = asio::error::bad_descriptor;
return ec;
}
ASIO_HANDLER_OPERATION(("socket", &impl, "cancel"));
reactor_.cancel_ops(impl.socket_, impl.reactor_data_);
ec = asio::error_code();
return ec;
}
asio::error_code reactive_socket_service_base::do_open(
reactive_socket_service_base::base_implementation_type& impl,
int af, int type, int protocol, asio::error_code& ec)
{
if (is_open(impl))
{
ec = asio::error::already_open;
return ec;
}
socket_holder sock(socket_ops::socket(af, type, protocol, ec));
if (sock.get() == invalid_socket)
return ec;
if (int err = reactor_.register_descriptor(sock.get(), impl.reactor_data_))
{
ec = asio::error_code(err,
asio::error::get_system_category());
return ec;
}
impl.socket_ = sock.release();
switch (type)
{
case SOCK_STREAM: impl.state_ = socket_ops::stream_oriented; break;
case SOCK_DGRAM: impl.state_ = socket_ops::datagram_oriented; break;
default: impl.state_ = 0; break;
}
ec = asio::error_code();
return ec;
}
asio::error_code reactive_socket_service_base::do_assign(
reactive_socket_service_base::base_implementation_type& impl, int type,
const reactive_socket_service_base::native_handle_type& native_socket,
asio::error_code& ec)
{
if (is_open(impl))
{
ec = asio::error::already_open;
return ec;
}
if (int err = reactor_.register_descriptor(
native_socket, impl.reactor_data_))
{
ec = asio::error_code(err,
asio::error::get_system_category());
return ec;
}
impl.socket_ = native_socket;
switch (type)
{
case SOCK_STREAM: impl.state_ = socket_ops::stream_oriented; break;
case SOCK_DGRAM: impl.state_ = socket_ops::datagram_oriented; break;
default: impl.state_ = 0; break;
}
impl.state_ |= socket_ops::possible_dup;
ec = asio::error_code();
return ec;
}
void reactive_socket_service_base::start_op(
reactive_socket_service_base::base_implementation_type& impl,
int op_type, reactor_op* op, bool is_continuation,
bool is_non_blocking, bool noop)
{
if (!noop)
{
if ((impl.state_ & socket_ops::non_blocking)
|| socket_ops::set_internal_non_blocking(
impl.socket_, impl.state_, true, op->ec_))
{
reactor_.start_op(op_type, impl.socket_,
impl.reactor_data_, op, is_continuation, is_non_blocking);
return;
}
}
reactor_.post_immediate_completion(op, is_continuation);
}
void reactive_socket_service_base::start_accept_op(
reactive_socket_service_base::base_implementation_type& impl,
reactor_op* op, bool is_continuation, bool peer_is_open)
{
if (!peer_is_open)
start_op(impl, reactor::read_op, op, true, is_continuation, false);
else
{
op->ec_ = asio::error::already_open;
reactor_.post_immediate_completion(op, is_continuation);
}
}
void reactive_socket_service_base::start_connect_op(
reactive_socket_service_base::base_implementation_type& impl,
reactor_op* op, bool is_continuation,
const socket_addr_type* addr, size_t addrlen)
{
if ((impl.state_ & socket_ops::non_blocking)
|| socket_ops::set_internal_non_blocking(
impl.socket_, impl.state_, true, op->ec_))
{
if (socket_ops::connect(impl.socket_, addr, addrlen, op->ec_) != 0)
{
if (op->ec_ == asio::error::in_progress
|| op->ec_ == asio::error::would_block)
{
op->ec_ = asio::error_code();
reactor_.start_op(reactor::connect_op, impl.socket_,
impl.reactor_data_, op, is_continuation, false);
return;
}
}
}
reactor_.post_immediate_completion(op, is_continuation);
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_HAS_IOCP)
// && !defined(ASIO_WINDOWS_RUNTIME)
#endif // ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
| 7,570
| 2,775
|
// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "VertexProcessor.hpp"
#include "Pipeline/VertexProgram.hpp"
#include "Pipeline/Constants.hpp"
#include "System/Math.hpp"
#include "Vulkan/VkDebug.hpp"
#include <cstring>
namespace sw
{
void VertexCache::clear()
{
for(uint32_t i = 0; i < SIZE; i++)
{
tag[i] = 0xFFFFFFFF;
}
}
uint32_t VertexProcessor::States::computeHash()
{
uint32_t *state = reinterpret_cast<uint32_t*>(this);
uint32_t hash = 0;
for(unsigned int i = 0; i < sizeof(States) / sizeof(uint32_t); i++)
{
hash ^= state[i];
}
return hash;
}
bool VertexProcessor::State::operator==(const State &state) const
{
if(hash != state.hash)
{
return false;
}
static_assert(is_memcmparable<State>::value, "Cannot memcmp States");
return memcmp(static_cast<const States*>(this), static_cast<const States*>(&state), sizeof(States)) == 0;
}
VertexProcessor::VertexProcessor()
{
routineCache = nullptr;
setRoutineCacheSize(1024);
}
VertexProcessor::~VertexProcessor()
{
delete routineCache;
routineCache = nullptr;
}
void VertexProcessor::setRoutineCacheSize(int cacheSize)
{
delete routineCache;
routineCache = new RoutineCache<State>(clamp(cacheSize, 1, 65536));
}
const VertexProcessor::State VertexProcessor::update(const sw::Context* context)
{
State state;
state.shaderID = context->vertexShader->getSerialID();
for(int i = 0; i < MAX_INTERFACE_COMPONENTS / 4; i++)
{
state.input[i].type = context->input[i].type;
state.input[i].count = context->input[i].count;
state.input[i].normalized = context->input[i].normalized;
// TODO: get rid of attribType -- just keep the VK format all the way through, this fully determines
// how to handle the attribute.
state.input[i].attribType = context->vertexShader->inputs[i*4].Type;
}
state.hash = state.computeHash();
return state;
}
Routine *VertexProcessor::routine(const State &state,
vk::PipelineLayout const *pipelineLayout,
SpirvShader const *vertexShader,
const vk::DescriptorSet::Bindings &descriptorSets)
{
Routine *routine = routineCache->query(state);
if(!routine) // Create one
{
VertexRoutine *generator = new VertexProgram(state, pipelineLayout, vertexShader, descriptorSets);
generator->generate();
routine = (*generator)("VertexRoutine_%0.8X", state.shaderID);
delete generator;
routineCache->add(state, routine);
}
return routine;
}
}
| 3,133
| 1,129
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/password_manager/chrome_password_manager_client.h"
#include "base/command_line.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/password_manager/content/browser/password_manager_internals_service_factory.h"
#include "components/password_manager/content/common/credential_manager_messages.h"
#include "components/password_manager/content/common/credential_manager_types.h"
#include "components/password_manager/core/browser/log_receiver.h"
#include "components/password_manager/core/browser/password_manager_internals_service.h"
#include "components/password_manager/core/common/password_manager_switches.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/mock_render_process_host.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserContext;
using content::WebContents;
namespace {
const char kTestText[] = "abcd1234";
const int kRequestId = 4;
class MockLogReceiver : public password_manager::LogReceiver {
public:
MOCK_METHOD1(LogSavePasswordProgress, void(const std::string&));
};
class TestChromePasswordManagerClient : public ChromePasswordManagerClient {
public:
explicit TestChromePasswordManagerClient(content::WebContents* web_contents)
: ChromePasswordManagerClient(web_contents, NULL),
is_sync_account_credential_(false) {}
virtual ~TestChromePasswordManagerClient() {}
virtual bool IsSyncAccountCredential(
const std::string& username,
const std::string& origin) const OVERRIDE {
return is_sync_account_credential_;
}
void set_is_sync_account_credential(bool is_sync_account_credential) {
is_sync_account_credential_ = is_sync_account_credential;
}
private:
bool is_sync_account_credential_;
DISALLOW_COPY_AND_ASSIGN(TestChromePasswordManagerClient);
};
} // namespace
class ChromePasswordManagerClientTest : public ChromeRenderViewHostTestHarness {
public:
ChromePasswordManagerClientTest();
virtual void SetUp() OVERRIDE;
protected:
ChromePasswordManagerClient* GetClient();
// If the test IPC sink contains an AutofillMsg_SetLoggingState message, then
// copies its argument into |activation_flag| and returns true. Otherwise
// returns false.
bool WasLoggingActivationMessageSent(bool* activation_flag);
password_manager::PasswordManagerInternalsService* service_;
testing::StrictMock<MockLogReceiver> receiver_;
};
ChromePasswordManagerClientTest::ChromePasswordManagerClientTest()
: service_(NULL) {
}
void ChromePasswordManagerClientTest::SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient(
web_contents(), NULL);
service_ = password_manager::PasswordManagerInternalsServiceFactory::
GetForBrowserContext(profile());
ASSERT_TRUE(service_);
}
ChromePasswordManagerClient* ChromePasswordManagerClientTest::GetClient() {
return ChromePasswordManagerClient::FromWebContents(web_contents());
}
bool ChromePasswordManagerClientTest::WasLoggingActivationMessageSent(
bool* activation_flag) {
const uint32 kMsgID = AutofillMsg_SetLoggingState::ID;
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(kMsgID);
if (!message)
return false;
Tuple1<bool> param;
AutofillMsg_SetLoggingState::Read(message, ¶m);
*activation_flag = param.a;
process()->sink().ClearMessages();
return true;
}
TEST_F(ChromePasswordManagerClientTest, LogSavePasswordProgressNoReceiver) {
ChromePasswordManagerClient* client = GetClient();
EXPECT_CALL(receiver_, LogSavePasswordProgress(kTestText)).Times(0);
// Before attaching the receiver, no text should be passed.
client->LogSavePasswordProgress(kTestText);
EXPECT_FALSE(client->IsLoggingActive());
}
TEST_F(ChromePasswordManagerClientTest, LogSavePasswordProgressAttachReceiver) {
ChromePasswordManagerClient* client = GetClient();
EXPECT_FALSE(client->IsLoggingActive());
// After attaching the logger, text should be passed.
service_->RegisterReceiver(&receiver_);
EXPECT_TRUE(client->IsLoggingActive());
EXPECT_CALL(receiver_, LogSavePasswordProgress(kTestText)).Times(1);
client->LogSavePasswordProgress(kTestText);
service_->UnregisterReceiver(&receiver_);
EXPECT_FALSE(client->IsLoggingActive());
}
TEST_F(ChromePasswordManagerClientTest, LogSavePasswordProgressDetachReceiver) {
ChromePasswordManagerClient* client = GetClient();
service_->RegisterReceiver(&receiver_);
EXPECT_TRUE(client->IsLoggingActive());
service_->UnregisterReceiver(&receiver_);
EXPECT_FALSE(client->IsLoggingActive());
// After detaching the logger, no text should be passed.
EXPECT_CALL(receiver_, LogSavePasswordProgress(kTestText)).Times(0);
client->LogSavePasswordProgress(kTestText);
}
TEST_F(ChromePasswordManagerClientTest, LogSavePasswordProgressNotifyRenderer) {
ChromePasswordManagerClient* client = GetClient();
bool logging_active = false;
// Initially, the logging should be off, so no IPC messages.
EXPECT_FALSE(WasLoggingActivationMessageSent(&logging_active));
service_->RegisterReceiver(&receiver_);
EXPECT_TRUE(client->IsLoggingActive());
EXPECT_TRUE(WasLoggingActivationMessageSent(&logging_active));
EXPECT_TRUE(logging_active);
service_->UnregisterReceiver(&receiver_);
EXPECT_FALSE(client->IsLoggingActive());
EXPECT_TRUE(WasLoggingActivationMessageSent(&logging_active));
EXPECT_FALSE(logging_active);
}
TEST_F(ChromePasswordManagerClientTest, AnswerToPingsAboutLoggingState_Active) {
service_->RegisterReceiver(&receiver_);
process()->sink().ClearMessages();
// Ping the client for logging activity update.
AutofillHostMsg_PasswordAutofillAgentConstructed msg(0);
static_cast<IPC::Listener*>(GetClient())->OnMessageReceived(msg);
bool logging_active = false;
EXPECT_TRUE(WasLoggingActivationMessageSent(&logging_active));
EXPECT_TRUE(logging_active);
service_->UnregisterReceiver(&receiver_);
}
TEST_F(ChromePasswordManagerClientTest,
AnswerToPingsAboutLoggingState_Inactive) {
process()->sink().ClearMessages();
// Ping the client for logging activity update.
AutofillHostMsg_PasswordAutofillAgentConstructed msg(0);
static_cast<IPC::Listener*>(GetClient())->OnMessageReceived(msg);
bool logging_active = true;
EXPECT_TRUE(WasLoggingActivationMessageSent(&logging_active));
EXPECT_FALSE(logging_active);
}
TEST_F(ChromePasswordManagerClientTest,
IsAutomaticPasswordSavingEnabledDefaultBehaviourTest) {
EXPECT_FALSE(GetClient()->IsAutomaticPasswordSavingEnabled());
}
TEST_F(ChromePasswordManagerClientTest,
IsAutomaticPasswordSavingEnabledWhenFlagIsSetTest) {
CommandLine::ForCurrentProcess()->AppendSwitch(
password_manager::switches::kEnableAutomaticPasswordSaving);
if (chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_UNKNOWN)
EXPECT_TRUE(GetClient()->IsAutomaticPasswordSavingEnabled());
else
EXPECT_FALSE(GetClient()->IsAutomaticPasswordSavingEnabled());
}
TEST_F(ChromePasswordManagerClientTest, LogToAReceiver) {
ChromePasswordManagerClient* client = GetClient();
service_->RegisterReceiver(&receiver_);
EXPECT_TRUE(client->IsLoggingActive());
EXPECT_CALL(receiver_, LogSavePasswordProgress(kTestText)).Times(1);
client->LogSavePasswordProgress(kTestText);
service_->UnregisterReceiver(&receiver_);
EXPECT_FALSE(client->IsLoggingActive());
}
TEST_F(ChromePasswordManagerClientTest, ShouldFilterAutofillResult_Reauth) {
// Make client disallow only reauth requests.
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(
password_manager::switches::kDisallowAutofillSyncCredentialForReauth);
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
autofill::PasswordForm form;
client->set_is_sync_account_credential(false);
NavigateAndCommit(
GURL("https://accounts.google.com/login?rart=123&continue=blah"));
EXPECT_FALSE(client->ShouldFilterAutofillResult(form));
client->set_is_sync_account_credential(true);
NavigateAndCommit(
GURL("https://accounts.google.com/login?rart=123&continue=blah"));
EXPECT_TRUE(client->ShouldFilterAutofillResult(form));
// This counts as a reauth url, though a valid URL should have a value for
// "rart"
NavigateAndCommit(GURL("https://accounts.google.com/addlogin?rart"));
EXPECT_TRUE(client->ShouldFilterAutofillResult(form));
NavigateAndCommit(GURL("https://accounts.google.com/login?param=123"));
EXPECT_FALSE(client->ShouldFilterAutofillResult(form));
NavigateAndCommit(GURL("https://site.com/login?rart=678"));
EXPECT_FALSE(client->ShouldFilterAutofillResult(form));
}
TEST_F(ChromePasswordManagerClientTest, ShouldFilterAutofillResult) {
// Normally the client should allow any credentials through, even if they
// are the sync credential.
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
autofill::PasswordForm form;
client->set_is_sync_account_credential(true);
NavigateAndCommit(GURL("https://accounts.google.com/Login"));
EXPECT_FALSE(client->ShouldFilterAutofillResult(form));
// Adding disallow switch should cause sync credential to be filtered.
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(
password_manager::switches::kDisallowAutofillSyncCredential);
client.reset(new TestChromePasswordManagerClient(web_contents()));
client->set_is_sync_account_credential(true);
NavigateAndCommit(GURL("https://accounts.google.com/Login"));
EXPECT_TRUE(client->ShouldFilterAutofillResult(form));
}
TEST_F(ChromePasswordManagerClientTest,
IsPasswordManagerEnabledForCurrentPage) {
ChromePasswordManagerClient* client = GetClient();
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://passwords.google.com/settings&rart=123"));
EXPECT_FALSE(client->IsPasswordManagerEnabledForCurrentPage());
// Password site is inaccesible via HTTP, but because of HSTS the following
// link should still continue to https://passwords.google.com.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"http://passwords.google.com/settings&rart=123"));
EXPECT_FALSE(client->IsPasswordManagerEnabledForCurrentPage());
// Specifying default port still passes.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://passwords.google.com:443/settings&rart=123"));
EXPECT_FALSE(client->IsPasswordManagerEnabledForCurrentPage());
// Encoded URL is considered the same.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://passwords.%67oogle.com/settings&rart=123"));
EXPECT_FALSE(client->IsPasswordManagerEnabledForCurrentPage());
// Make sure testing sites are disabled as well.
NavigateAndCommit(
GURL("https://accounts.google.com/Login?continue="
"https://passwords-ac-testing.corp.google.com/settings&rart=456"));
EXPECT_FALSE(client->IsPasswordManagerEnabledForCurrentPage());
// Fully qualified domain name is considered a different hostname by GURL.
// Ideally this would not be the case, but this quirk can be avoided by
// verification on the server. This test is simply documentation of this
// behavior.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://passwords.google.com./settings&rart=123"));
EXPECT_TRUE(client->IsPasswordManagerEnabledForCurrentPage());
// Not a transactional reauth page.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://passwords.google.com/settings"));
EXPECT_TRUE(client->IsPasswordManagerEnabledForCurrentPage());
// Should be enabled for other transactional reauth pages.
NavigateAndCommit(
GURL("https://accounts.google.com/ServiceLogin?continue="
"https://mail.google.com&rart=234"));
EXPECT_TRUE(client->IsPasswordManagerEnabledForCurrentPage());
// Reauth pages are only on accounts.google.com
NavigateAndCommit(
GURL("https://other.site.com/ServiceLogin?continue="
"https://passwords.google.com&rart=234"));
EXPECT_TRUE(client->IsPasswordManagerEnabledForCurrentPage());
}
TEST_F(ChromePasswordManagerClientTest, CredentialManagerOnNotifyFailedSignIn) {
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
password_manager::CredentialInfo info(base::ASCIIToUTF16("id"),
base::ASCIIToUTF16("name"),
GURL("https://example.com/image.png"));
client->OnNotifyFailedSignIn(kRequestId, info);
const uint32 kMsgID = CredentialManagerMsg_AcknowledgeFailedSignIn::ID;
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(kMsgID);
EXPECT_TRUE(message);
process()->sink().ClearMessages();
}
TEST_F(ChromePasswordManagerClientTest, CredentialManagerOnNotifySignedIn) {
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
password_manager::CredentialInfo info(base::ASCIIToUTF16("id"),
base::ASCIIToUTF16("name"),
GURL("https://example.com/image.png"));
client->OnNotifySignedIn(kRequestId, info);
const uint32 kMsgID = CredentialManagerMsg_AcknowledgeSignedIn::ID;
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(kMsgID);
EXPECT_TRUE(message);
process()->sink().ClearMessages();
}
TEST_F(ChromePasswordManagerClientTest, CredentialManagerOnNotifySignedOut) {
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
client->OnNotifySignedOut(kRequestId);
const uint32 kMsgID = CredentialManagerMsg_AcknowledgeSignedOut::ID;
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(kMsgID);
EXPECT_TRUE(message);
process()->sink().ClearMessages();
}
TEST_F(ChromePasswordManagerClientTest, CredentialManagerOnRequestCredential) {
scoped_ptr<TestChromePasswordManagerClient> client(
new TestChromePasswordManagerClient(web_contents()));
std::vector<GURL> federations;
client->OnRequestCredential(kRequestId, false, federations);
const uint32 kMsgID = CredentialManagerMsg_SendCredential::ID;
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(kMsgID);
EXPECT_TRUE(message);
process()->sink().ClearMessages();
}
| 15,304
| 4,666
|
#include <nan.h> // pulls in Nan and v8 namespaces
#include <cmath> // std::ceil
#include <algorithm> // std::max
#include <cstdlib> // std::malloc std::realloc
#include "fastlz.h" // fastlz_*
NAN_METHOD(CompressSync) {
if (info.Length() == 2 && node::Buffer::HasInstance(info[0]) && info[1]->IsUint32()) {
v8::Local<v8::Object> sourceObject = info[0]->ToObject();
void* source = static_cast<void*>(node::Buffer::Data(sourceObject));
uint32_t dataLength = info[1]->Uint32Value();
// Ensure the new buffer is at least big enough to hold the compressed data
// per the requirements by fastlz
int destinationSize = std::max(66, static_cast<int>(std::ceil(dataLength * 1.05)));
void* destination = std::malloc(destinationSize);
int compressedSize = fastlz_compress(source, dataLength, destination);
// Reallocate the buffer so it is strictly big enough.
char* compressedData = static_cast<char*>(realloc(destination, compressedSize));
// Turn it into a node::Buffer which takes ownership of the memory and will
// call free() on the internal buffer we allocated when it is garbage
// collected.
v8::Local<v8::Object> compressedBuffer = Nan::NewBuffer(compressedData, compressedSize).ToLocalChecked();
info.GetReturnValue().Set(compressedBuffer);
} else {
Nan::ThrowTypeError("usage: source buffer, source data length, destination buffer");
}
return;
}
NAN_MODULE_INIT(InitAll) {
Nan::Set(target, Nan::New("compressSync").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(CompressSync)).ToLocalChecked());
}
NODE_MODULE(FastLZ, InitAll)
| 1,641
| 523
|
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "main/Config.h"
#include "StellarCoreVersion.h"
#include "crypto/Hex.h"
#include "crypto/KeyUtils.h"
#include "history/HistoryArchive.h"
#include "ledger/LedgerManager.h"
#include "main/ExternalQueue.h"
#include "scp/LocalNode.h"
#include "util/Logging.h"
#include "util/types.h"
#include <functional>
#include <lib/util/format.h>
#include <sstream>
namespace stellar
{
using xdr::operator<;
const uint32 Config::CURRENT_LEDGER_PROTOCOL_VERSION = 9;
Config::Config() : NODE_SEED(SecretKey::random())
{
// fill in defaults
// non configurable
FORCE_SCP = false;
LEDGER_PROTOCOL_VERSION = CURRENT_LEDGER_PROTOCOL_VERSION;
OVERLAY_PROTOCOL_MIN_VERSION = 5;
OVERLAY_PROTOCOL_VERSION = 6;
VERSION_STR = STELLAR_CORE_VERSION;
// configurable
RUN_STANDALONE = false;
MANUAL_CLOSE = false;
CATCHUP_COMPLETE = false;
CATCHUP_RECENT = 0;
AUTOMATIC_MAINTENANCE_PERIOD = std::chrono::seconds{3600};
AUTOMATIC_MAINTENANCE_COUNT = 50000;
ARTIFICIALLY_GENERATE_LOAD_FOR_TESTING = false;
ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = false;
ARTIFICIALLY_SET_CLOSE_TIME_FOR_TESTING = 0;
ARTIFICIALLY_PESSIMIZE_MERGES_FOR_TESTING = false;
ALLOW_LOCALHOST_FOR_TESTING = false;
USE_CONFIG_FOR_GENESIS = false;
FAILURE_SAFETY = -1;
UNSAFE_QUORUM = false;
LOG_FILE_PATH = "/var/log/digitalbits-core.%datetime{%Y.%M.%d-%H:%m:%s}.log";
BUCKET_DIR_PATH = "/var/lib/digitalbits/buckets";
TESTING_UPGRADE_DESIRED_FEE = LedgerManager::GENESIS_LEDGER_BASE_FEE;
TESTING_UPGRADE_RESERVE = LedgerManager::GENESIS_LEDGER_BASE_RESERVE;
TESTING_UPGRADE_MAX_TX_PER_LEDGER = 50;
HTTP_PORT = DEFAULT_PEER_PORT + 1;
PUBLIC_HTTP_PORT = false;
HTTP_MAX_CLIENT = 128;
PEER_PORT = DEFAULT_PEER_PORT;
TARGET_PEER_CONNECTIONS = 8;
MAX_ADDITIONAL_PEER_CONNECTIONS = -1;
MAX_PEER_CONNECTIONS = 12;
MAX_PENDING_CONNECTIONS = 5000;
PEER_AUTHENTICATION_TIMEOUT = 2;
PEER_TIMEOUT = 30;
PREFERRED_PEERS_ONLY = false;
MINIMUM_IDLE_PERCENT = 0;
MAX_CONCURRENT_SUBPROCESSES = 16;
NODE_IS_VALIDATOR = false;
DATABASE = SecretValue{"sqlite3://:memory:"};
NTP_SERVER = "pool.ntp.org";
}
namespace
{
using ConfigItem = std::pair<std::string, std::shared_ptr<cpptoml::toml_base>>;
bool
readBool(ConfigItem const& item)
{
if (!item.second->as<bool>())
{
throw std::invalid_argument(fmt::format("invalid {}", item.first));
}
return item.second->as<bool>()->value();
}
std::string
readString(ConfigItem const& item)
{
if (!item.second->as<std::string>())
{
throw std::invalid_argument(fmt::format("invalid {}", item.first));
}
return item.second->as<std::string>()->value();
}
std::vector<std::string>
readStringArray(ConfigItem const& item)
{
auto result = std::vector<std::string>{};
if (!item.second->is_array())
{
throw std::invalid_argument(
fmt::format("{} must be an array", item.first));
}
for (auto v : item.second->as_array()->array())
{
if (!v->as<std::string>())
{
throw std::invalid_argument(
fmt::format("invalid element of {}", item.first));
}
result.push_back(v->as<std::string>()->value());
}
return result;
}
template <typename T>
T
readInt(ConfigItem const& item, T min = std::numeric_limits<T>::min(),
T max = std::numeric_limits<T>::max())
{
if (!item.second->as<int64_t>())
{
throw std::invalid_argument(fmt::format("invalid {}", item.first));
}
int64_t v = item.second->as<int64_t>()->value();
if (v < min || v > max)
{
throw std::invalid_argument(fmt::format("bad {}", item.first));
}
return static_cast<T>(v);
}
}
void
Config::loadQset(std::shared_ptr<cpptoml::toml_group> group, SCPQuorumSet& qset,
int level)
{
if (!group)
{
throw std::invalid_argument("invalid entry in quorum set definition");
}
if (level > 2)
{
throw std::invalid_argument("too many levels in quorum set");
}
int thresholdPercent = 67;
qset.threshold = 0;
for (auto& item : *group)
{
if (item.first == "THRESHOLD_PERCENT")
{
if (!item.second->as<int64_t>())
{
throw std::invalid_argument("invalid THRESHOLD_PERCENT");
}
int64_t f = item.second->as<int64_t>()->value();
if (f <= 0 || f > 100)
{
throw std::invalid_argument("invalid THRESHOLD_PERCENT");
}
thresholdPercent = (uint32_t)f;
}
else if (item.first == "VALIDATORS")
{
auto values = readStringArray(item);
for (auto v : values)
{
PublicKey nodeID;
parseNodeID(v, nodeID);
qset.validators.emplace_back(nodeID);
}
}
else
{ // must be a subset
try
{
if (!item.second->is_group())
{
throw std::invalid_argument(
"invalid quorum set, should be a group");
}
qset.innerSets.resize((uint32_t)qset.innerSets.size() + 1);
loadQset(item.second->as_group(),
qset.innerSets[qset.innerSets.size() - 1], level + 1);
}
catch (std::exception& e)
{
std::string s;
s = e.what();
s += " while parsing '" + item.first + "'";
throw std::invalid_argument(s);
}
}
}
// round up: n*percent/100
qset.threshold = uint32(
1 +
(((qset.validators.size() + qset.innerSets.size()) * thresholdPercent -
1) /
100));
if (qset.threshold == 0 ||
(qset.validators.empty() && qset.innerSets.empty()))
{
throw std::invalid_argument("invalid quorum set definition");
}
}
void
Config::load(std::string const& filename)
{
LOG(DEBUG) << "Loading config from: " << filename;
try
{
cpptoml::toml_group g;
if (filename == "-")
{
cpptoml::parser p(std::cin);
g = p.parse();
}
else
{
g = cpptoml::parse_file(filename);
}
// cpptoml returns the items in non-deterministic order
// so we need to process items that are potential dependencies first
for (auto& item : g)
{
LOG(DEBUG) << "Config item: " << item.first;
if (item.first == "PEER_PORT")
{
PEER_PORT = readInt<unsigned short>(item, 1, UINT16_MAX);
}
else if (item.first == "HTTP_PORT")
{
HTTP_PORT = readInt<unsigned short>(item, 1, UINT16_MAX);
}
else if (item.first == "HTTP_MAX_CLIENT")
{
HTTP_MAX_CLIENT = readInt<unsigned short>(item, 0, UINT16_MAX);
}
else if (item.first == "PUBLIC_HTTP_PORT")
{
PUBLIC_HTTP_PORT = readBool(item);
}
else if (item.first == "FAILURE_SAFETY")
{
FAILURE_SAFETY = readInt<int32_t>(item, -1, INT32_MAX - 1);
}
else if (item.first == "UNSAFE_QUORUM")
{
UNSAFE_QUORUM = readBool(item);
}
else if (item.first == "KNOWN_CURSORS")
{
KNOWN_CURSORS = readStringArray(item);
for (auto const& c : KNOWN_CURSORS)
{
if (!ExternalQueue::validateResourceID(c))
{
throw std::invalid_argument(
fmt::format("invalid cursor: \"{}\"", c));
}
}
}
else if (item.first == "RUN_STANDALONE")
{
RUN_STANDALONE = readBool(item);
}
else if (item.first == "CATCHUP_COMPLETE")
{
CATCHUP_COMPLETE = readBool(item);
}
else if (item.first == "CATCHUP_RECENT")
{
CATCHUP_RECENT = readInt<uint32_t>(item, 0, UINT32_MAX - 1);
}
else if (item.first == "ARTIFICIALLY_GENERATE_LOAD_FOR_TESTING")
{
ARTIFICIALLY_GENERATE_LOAD_FOR_TESTING = readBool(item);
}
else if (item.first == "ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING")
{
ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = readBool(item);
}
else if (item.first == "ARTIFICIALLY_SET_CLOSE_TIME_FOR_TESTING")
{
ARTIFICIALLY_SET_CLOSE_TIME_FOR_TESTING =
readInt<uint32_t>(item, 0, UINT32_MAX - 1);
}
else if (item.first == "ALLOW_LOCALHOST_FOR_TESTING")
{
ALLOW_LOCALHOST_FOR_TESTING = readBool(item);
}
else if (item.first == "AUTOMATIC_MAINTENANCE_PERIOD")
{
AUTOMATIC_MAINTENANCE_PERIOD =
std::chrono::seconds{readInt<uint32_t>(item)};
}
else if (item.first == "AUTOMATIC_MAINTENANCE_COUNT")
{
AUTOMATIC_MAINTENANCE_COUNT = readInt<uint32_t>(item);
}
else if (item.first == "MANUAL_CLOSE")
{
MANUAL_CLOSE = readBool(item);
}
else if (item.first == "LOG_FILE_PATH")
{
LOG_FILE_PATH = readString(item);
}
else if (item.first == "TMP_DIR_PATH")
{
throw std::invalid_argument("TMP_DIR_PATH is not supported "
"anymore - tmp data is now kept in "
"BUCKET_DIR_PATH/tmp");
}
else if (item.first == "BUCKET_DIR_PATH")
{
BUCKET_DIR_PATH = readString(item);
}
else if (item.first == "NODE_NAMES")
{
auto names = readStringArray(item);
for (auto v : names)
{
PublicKey nodeID;
parseNodeID(v, nodeID);
}
}
else if (item.first == "NODE_SEED")
{
PublicKey nodeID;
parseNodeID(readString(item), nodeID, NODE_SEED, true);
}
else if (item.first == "NODE_IS_VALIDATOR")
{
NODE_IS_VALIDATOR = readBool(item);
}
else if (item.first == "TARGET_PEER_CONNECTIONS")
{
TARGET_PEER_CONNECTIONS = readInt<unsigned short>(item, 1);
}
else if (item.first == "MAX_PEER_CONNECTIONS")
{
MAX_PEER_CONNECTIONS = readInt<unsigned short>(item, 1);
}
else if (item.first == "MAX_ADDITIONAL_PEER_CONNECTIONS")
{
MAX_ADDITIONAL_PEER_CONNECTIONS =
readInt<int>(item, -1, UINT16_MAX);
}
else if (item.first == "MAX_PENDING_CONNECTIONS")
{
MAX_PENDING_CONNECTIONS =
readInt<unsigned short>(item, 1, UINT16_MAX);
}
else if (item.first == "PEER_AUTHENTICATION_TIMEOUT")
{
PEER_AUTHENTICATION_TIMEOUT =
readInt<unsigned short>(item, 1, UINT16_MAX);
}
else if (item.first == "PEER_TIMEOUT")
{
PEER_TIMEOUT = readInt<unsigned short>(item, 1, UINT16_MAX);
}
else if (item.first == "PREFERRED_PEERS")
{
PREFERRED_PEERS = readStringArray(item);
}
else if (item.first == "PREFERRED_PEER_KEYS")
{
// handled below
}
else if (item.first == "PREFERRED_PEERS_ONLY")
{
PREFERRED_PEERS_ONLY = readBool(item);
}
else if (item.first == "KNOWN_PEERS")
{
KNOWN_PEERS = readStringArray(item);
}
else if (item.first == "QUORUM_SET")
{
// processing performed after this loop
}
else if (item.first == "COMMANDS")
{
COMMANDS = readStringArray(item);
}
else if (item.first == "MAX_CONCURRENT_SUBPROCESSES")
{
MAX_CONCURRENT_SUBPROCESSES =
static_cast<size_t>(readInt<int>(item, 1));
}
else if (item.first == "MINIMUM_IDLE_PERCENT")
{
MINIMUM_IDLE_PERCENT = readInt<uint32_t>(item, 0, 100);
}
else if (item.first == "HISTORY")
{
auto hist = item.second->as_group();
if (hist)
{
for (auto const& archive : *hist)
{
LOG(DEBUG) << "History archive: " << archive.first;
auto tab = archive.second->as_group();
if (!tab)
{
throw std::invalid_argument(
"malformed HISTORY config block");
}
std::string get, put, mkdir;
for (auto const& c : *tab)
{
if (c.first == "get")
{
get = c.second->as<std::string>()->value();
}
else if (c.first == "put")
{
put = c.second->as<std::string>()->value();
}
else if (c.first == "mkdir")
{
mkdir = c.second->as<std::string>()->value();
}
else
{
std::string err(
"Unknown HISTORY-table entry: '");
err += c.first;
err +=
"', within [HISTORY." + archive.first + "]";
throw std::invalid_argument(err);
}
}
HISTORY[archive.first] =
std::make_shared<HistoryArchive>(archive.first, get,
put, mkdir);
}
}
else
{
throw std::invalid_argument("incomplete HISTORY block");
}
}
else if (item.first == "DATABASE")
{
DATABASE = SecretValue{readString(item)};
}
else if (item.first == "NETWORK_PASSPHRASE")
{
NETWORK_PASSPHRASE = readString(item);
}
else if (item.first == "NTP_SERVER")
{
NTP_SERVER = readString(item);
}
else if (item.first == "INVARIANT_CHECKS")
{
INVARIANT_CHECKS = readStringArray(item);
}
else
{
std::string err("Unknown configuration entry: '");
err += item.first;
err += "'";
throw std::invalid_argument(err);
}
}
// process elements that potentially depend on others
if (g.contains("PREFERRED_PEER_KEYS"))
{
auto pkeys = g.get("PREFERRED_PEER_KEYS");
if (pkeys)
{
auto values =
readStringArray(ConfigItem{"PREFERRED_PEER_KEYS", pkeys});
for (auto v : values)
{
PublicKey nodeID;
parseNodeID(v, nodeID);
PREFERRED_PEER_KEYS.push_back(KeyUtils::toStrKey(nodeID));
}
}
}
if (g.contains("QUORUM_SET"))
{
auto qset = g.get("QUORUM_SET");
if (qset)
{
loadQset(qset->as_group(), QUORUM_SET, 0);
}
}
if (MAX_ADDITIONAL_PEER_CONNECTIONS < 0)
{
MAX_ADDITIONAL_PEER_CONNECTIONS = TARGET_PEER_CONNECTIONS;
}
if (MAX_ADDITIONAL_PEER_CONNECTIONS >
(UINT16_MAX - TARGET_PEER_CONNECTIONS))
{
throw std::invalid_argument(
"invalid MAX_ADDITIONAL_PEER_CONNECTIONS");
}
MAX_PEER_CONNECTIONS = std::max(
MAX_PEER_CONNECTIONS,
static_cast<unsigned short>(MAX_ADDITIONAL_PEER_CONNECTIONS +
TARGET_PEER_CONNECTIONS));
validateConfig();
}
catch (cpptoml::toml_parse_exception& ex)
{
std::string err("Failed to parse '");
err += filename;
err += "' :";
err += ex.what();
throw std::invalid_argument(err);
}
}
void
Config::validateConfig()
{
std::set<NodeID> nodes;
LocalNode::forAllNodes(QUORUM_SET,
[&](NodeID const& n) { nodes.insert(n); });
if (nodes.size() == 0)
{
throw std::invalid_argument("QUORUM_SET not configured");
}
// calculates nodes that would break quorum
auto selfID = NODE_SEED.getPublicKey();
auto r = LocalNode::findClosestVBlocking(QUORUM_SET, nodes, nullptr);
if (FAILURE_SAFETY == -1)
{
// calculates default value for safety giving the top level entities
// the same weight
// n = 3f+1 <=> f = (n-1)/3
auto topLevelCount =
QUORUM_SET.validators.size() + QUORUM_SET.innerSets.size();
FAILURE_SAFETY = (static_cast<uint32>(topLevelCount) - 1) / 3;
}
try
{
if (FAILURE_SAFETY >= r.size())
{
LOG(ERROR) << "Not enough nodes / thresholds too strict in your "
"Quorum set to ensure your desired level of "
"FAILURE_SAFETY. Reduce FAILURE_SAFETY or fix "
"quorum set";
throw std::invalid_argument(
"FAILURE_SAFETY incompatible with QUORUM_SET");
}
if (!UNSAFE_QUORUM)
{
if (FAILURE_SAFETY == 0)
{
LOG(ERROR)
<< "Can't have FAILURE_SAFETY=0 unless you also set "
"UNSAFE_QUORUM=true. Be sure you know what you are "
"doing!";
throw std::invalid_argument("SCP unsafe");
}
unsigned int topSize = (unsigned int)(QUORUM_SET.validators.size() +
QUORUM_SET.innerSets.size());
unsigned int minSize = 1 + (topSize * 2 - 1) / 3;
if (QUORUM_SET.threshold < minSize)
{
LOG(ERROR)
<< "Your THESHOLD_PERCENTAGE is too low. If you really "
"want "
"this set UNSAFE_QUORUM=true. Be sure you know what you "
"are doing!";
throw std::invalid_argument("SCP unsafe");
}
}
}
catch (...)
{
LOG(INFO) << " Current QUORUM_SET breaks with " << r.size()
<< " failures";
throw;
}
}
void
Config::parseNodeID(std::string configStr, PublicKey& retKey)
{
SecretKey k;
parseNodeID(configStr, retKey, k, false);
}
void
Config::parseNodeID(std::string configStr, PublicKey& retKey, SecretKey& sKey,
bool isSeed)
{
if (configStr.size() < 2)
{
throw std::invalid_argument("invalid key");
}
// check if configStr is a PublicKey or a common name
if (configStr[0] == '$')
{
if (isSeed)
{
throw std::invalid_argument("aliases only store public keys");
}
if (!resolveNodeID(configStr, retKey))
{
std::stringstream msg;
msg << "unknown key in config: " << configStr;
throw std::invalid_argument(msg.str());
}
}
else
{
std::istringstream iss(configStr);
std::string nodestr;
iss >> nodestr;
if (isSeed)
{
sKey = SecretKey::fromStrKeySeed(nodestr);
retKey = sKey.getPublicKey();
nodestr = sKey.getStrKeyPublic();
}
else
{
retKey = KeyUtils::fromStrKey<PublicKey>(nodestr);
}
if (iss)
{ // get any common name they have added
std::string commonName;
iss >> commonName;
if (commonName.size())
{
std::string cName = "$";
cName += commonName;
if (resolveNodeID(cName, retKey))
{
throw std::invalid_argument("name already used");
}
if (!VALIDATOR_NAMES
.emplace(std::make_pair(nodestr, commonName))
.second)
{
std::stringstream msg;
msg << "naming node twice: " << commonName;
throw std::invalid_argument(msg.str());
}
}
}
}
}
std::string
Config::toShortString(PublicKey const& pk) const
{
std::string ret = KeyUtils::toStrKey(pk);
auto it = VALIDATOR_NAMES.find(ret);
if (it == VALIDATOR_NAMES.end())
return ret.substr(0, 5);
else
return it->second;
}
std::string
Config::toStrKey(PublicKey const& pk, bool& isAlias) const
{
std::string ret = KeyUtils::toStrKey(pk);
auto it = VALIDATOR_NAMES.find(ret);
if (it == VALIDATOR_NAMES.end())
{
isAlias = false;
return ret;
}
else
{
isAlias = true;
return it->second;
}
}
std::string
Config::toStrKey(PublicKey const& pk) const
{
bool isAlias;
return toStrKey(pk, isAlias);
}
bool
Config::resolveNodeID(std::string const& s, PublicKey& retKey) const
{
auto expanded = expandNodeID(s);
if (expanded.empty())
{
return false;
}
try
{
retKey = KeyUtils::fromStrKey<PublicKey>(expanded);
}
catch (std::invalid_argument&)
{
return false;
}
return true;
}
std::string
Config::expandNodeID(const std::string& s) const
{
if (s.length() < 2)
{
return s;
}
if (s[0] != '$' && s[0] != '@')
{
return s;
}
using validatorMatcher_t =
std::function<bool(std::pair<std::string, std::string> const&)>;
auto arg = s.substr(1);
auto validatorMatcher =
s[0] == '$'
? validatorMatcher_t{[&](std::pair<std::string, std::string> const&
p) { return p.second == arg; }}
: validatorMatcher_t{
[&](std::pair<std::string, std::string> const& p) {
return p.first.compare(0, arg.size(), arg) == 0;
}};
auto it = std::find_if(VALIDATOR_NAMES.begin(), VALIDATOR_NAMES.end(),
validatorMatcher);
if (it != VALIDATOR_NAMES.end())
{
return it->first;
}
else
{
return {};
}
}
}
| 24,185
| 7,493
|
#include <stan/math/rev/mat.hpp> // FIX ME - more specific
#include <stan/math/torsten/PKModel/Pred/Pred1_mix2.hpp>
#include <stan/math/torsten/PKModel/functors/mix2_functor.hpp>
#include <gtest/gtest.h>
struct ODE_functor {
template <typename T0, typename T1, typename T2, typename T3>
inline
std::vector<typename boost::math::tools::promote_args<T0, T1, T2, T3>::type>
operator()(const T0& t,
const std::vector<T1>& y,
const std::vector<T2>& y_pk,
const std::vector<T3>& theta,
const std::vector<double>& x_r,
const std::vector<int>& x_i,
std::ostream* pstream_) const {
typedef typename boost::math::tools::promote_args<T0, T1, T2, T3>::type
scalar;
scalar VC = theta[2],
Mtt = theta[5],
circ0 = theta[6],
alpha = theta[7],
gamma = theta[8],
ktr = 4 / Mtt,
prol = y[0] + circ0,
transit = y[1] + circ0,
circ = y[2] + circ0,
conc = y_pk[1] / VC,
Edrug = alpha * conc;
std::vector<scalar> dxdt(3);
dxdt[0] = ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1);
dxdt[1] = ktr * (prol - transit);
dxdt[2] = ktr * (transit - circ);
return dxdt;
}
};
TEST(Torsten, pred1_mix) {
using Eigen::Matrix;
using Eigen::Dynamic;
double dt = 1.0;
int nParameters = 9;
std::vector<double> parameters(nParameters);
parameters[0] = 10; // CL
parameters[1] = 15; // Q
parameters[2] = 35; // VC
parameters[3] = 105; // VP
parameters[4] = 2.0; // ka
parameters[5] = 125; // Mtt
parameters[6] = 5; // Circ0
parameters[7] = 3e-4; // alpha
parameters[8] = 0.17; // gamma
std::vector<double> biovar_dummy(1, 0);
std::vector<double> tlag_dummy(1, 0);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> K(0, 0);
// initialize Model Parameters object
torsten::ModelParameters<double, double, double, double>
parms(dt, parameters, biovar_dummy, tlag_dummy);
int nOdes = 6;
Matrix<double, 1, Dynamic> init(nOdes);
init << 10000, 0, 0, 0, 0, 0; // initial dose in the gut
std::vector<double> rate(6, 0); // no rate
// Use default value of parameters
double rel_tol = 1e-6, abs_tol = 1e-6;
long int max_num_steps = 1e+6;
typedef torsten::mix2_functor<ODE_functor> F0;
torsten::Pred1_mix2<F0> Pred1(F0(ODE_functor()), rel_tol, abs_tol, max_num_steps, 0,
"rk45");
Matrix<double, 1, Dynamic> pred = Pred1(dt, parms, init, rate);
// Compare to results obtained with mrgsolve
Eigen::VectorXd mrgResults(6);
mrgResults << 1353.352829, 5597.489, 1787.0134,
-0.0060546255, -7.847821e-05, -7.039447e-07;
// PK compartments
EXPECT_FLOAT_EQ(mrgResults(0), pred(0));
EXPECT_FLOAT_EQ(mrgResults(1), pred(1));
EXPECT_FLOAT_EQ(mrgResults(2), pred(2));
// PD compartments
// (are estimated less accurately)
EXPECT_NEAR(mrgResults(3), pred(3), std::abs(mrgResults(3) * 1e-4));
EXPECT_NEAR(mrgResults(4), pred(4), std::abs(mrgResults(4) * 1e-4));
EXPECT_NEAR(mrgResults(5), pred(5), std::abs(mrgResults(5) * 1e-4));
}
| 3,115
| 1,348
|
#include <torch/extension.h>
#include <pybind11/pybind11.h>
#include <iostream>
#include <vector>
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
sample_adj(torch::Tensor indptr, torch::Tensor indices, torch::Tensor node_idx, int64_t num_neighbors, bool replace) {
auto indptr_data = indptr.data_ptr<int64_t>();
auto indices_data = indices.data_ptr<int64_t>();
auto node_idx_data = node_idx.data_ptr<int64_t>();
auto out_indptr = torch::empty(node_idx.numel() + 1, indptr.options());
auto out_indptr_data = out_indptr.data_ptr<int64_t>();
out_indptr_data[0] = 0;
auto num_input_nodes = node_idx.numel();
std::vector<int64_t> new_indices;
std::vector<int64_t> new_edges;
std::vector<int64_t> new_node_idx;
auto assoc = torch::full({indptr.size(0) - 1}, -1, node_idx.options());
assoc.index_copy_(0, node_idx, torch::arange(num_input_nodes, node_idx.options()));
auto assoc_data = assoc.data_ptr<int64_t>();
// std::unordered_map<int64_t, int64_t> node_id_map;
int64_t node = 0;
for(int64_t i = 0; i < node_idx.numel(); i++) {
node = node_idx_data[i];
// node_id_map[node] = i;
new_node_idx.push_back(node);
}
int64_t row_start, row_count, edge, src_node;
int64_t num_nodes = node_idx.numel();
if(num_neighbors < 0){
for(int64_t i = 0; i < num_input_nodes; i++) {
node = node_idx_data[i];
row_start = indptr_data[node];
row_count = indptr_data[node+1] - row_start;
for(int k = 0; k < row_count; k++) {
edge = row_start + k;
src_node = indices_data[edge];
if(assoc_data[src_node] == -1) {
assoc_data[src_node] = num_nodes;
new_node_idx.push_back(src_node);
num_nodes++;
}
new_indices.push_back(assoc_data[src_node]);
// if(node_id_map.count(src_node) == 0) {
// node_id_map[src_node] = num_nodes;
// new_node_idx.push_back(src_node);
// num_nodes++;
// }
// new_indices.push_back(node_id_map[src_node]);
new_edges.push_back(edge);
}
out_indptr_data[i+1] = row_count + out_indptr_data[i];
}
} else if(replace) {
for(int64_t i = 0; i < num_input_nodes; i++) {
node = node_idx_data[i];
row_start = indptr_data[node];
row_count = indptr_data[node+1] - row_start;
for(int64_t k = 0; k < num_neighbors; k++) {
edge = row_start + rand() % row_count;
src_node = indices_data[edge];
if(assoc_data[src_node] == -1) {
assoc_data[src_node] = num_nodes;
new_node_idx.push_back(src_node);
num_nodes++;
}
new_indices.push_back(assoc_data[src_node]);
// if(node_id_map.count(src_node) == 0) {
// node_id_map[src_node] = num_nodes;
// new_node_idx.push_back(src_node);
// num_nodes++;
// }
// new_indices.push_back(node_id_map[src_node]);
new_edges.push_back(edge);
}
out_indptr_data[i+1] = num_neighbors + out_indptr_data[i];
}
} else {
for(int64_t i = 0; i < num_input_nodes; i++) {
node = node_idx_data[i];
row_start = indptr_data[node];
row_count = indptr_data[node+1] - row_start;
std::unordered_set<int64_t> perm;
if (row_count <= num_neighbors) {
for (int64_t j = 0; j < row_count; j++)
perm.insert(j);
} else { // See: https://www.nowherenearithaca.com/2013/05/
// robert-floyds-tiny-and-beautiful.html
for (int64_t j = row_count - num_neighbors; j < row_count; j++) {
if (!perm.insert(rand() % j).second)
perm.insert(j);
}
}
for(const int64_t &p : perm) {
edge = row_start + p;
src_node = indices_data[edge];
if(assoc_data[src_node] == -1) {
assoc_data[src_node] = num_nodes;
new_node_idx.push_back(src_node);
num_nodes++;
}
new_indices.push_back(assoc_data[src_node]);
// if(node_id_map.count(src_node) == 0) {
// node_id_map[src_node] = num_nodes;
// new_node_idx.push_back(src_node);
// num_nodes++;
// }
// new_indices.push_back(node_id_map[src_node]);
new_edges.push_back(edge);
}
out_indptr_data[i+1] = perm.size() + out_indptr_data[i];
}
}
int64_t num_edges = out_indptr_data[num_input_nodes];
int64_t out_num_nodes = new_node_idx.size();
auto out_nodes = torch::from_blob(new_node_idx.data(), {out_num_nodes}, indices.options()).clone();
auto out_indices = torch::from_blob(new_indices.data(), {num_edges}, indices.options()).clone();
auto out_edges = torch::from_blob(new_edges.data(), {num_edges}, indices.options()).clone();
return std::make_tuple(out_indptr, out_indices, out_nodes, out_edges);
}
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
subgraph_cpu(torch::Tensor indptr, torch::Tensor indices, torch::Tensor node_idx) {
auto node_idx_data = node_idx.data_ptr<int64_t>();
auto indptr_data = indptr.data_ptr<int64_t>();
auto indices_data = indices.data_ptr<int64_t>();
int64_t num_nodes = node_idx.numel();
auto out_indptr = torch::empty(num_nodes + 1, indptr.options());
auto out_indptr_data = out_indptr.data_ptr<int64_t>();
out_indptr_data[0] = 0;
std::vector<int64_t> new_indices;
std::vector<int64_t> new_edges;
auto assoc = torch::full({indptr.size(0) - 1}, -1, node_idx.options());
assoc.index_copy_(0, node_idx, torch::arange(num_nodes, node_idx.options()));
auto assoc_data = assoc.data_ptr<int64_t>();
int64_t node, src, src_new;
int64_t row_start, row_end, num_edges = 0;
for(int64_t i = 0; i < num_nodes; i++) {
node = node_idx_data[i];
row_start = indptr_data[node];
row_end = indptr_data[node+1];
for(int64_t k = row_start; k < row_end; k++) {
src = indices_data[k];
src_new = assoc_data[src];
if(src_new > -1) {
new_indices.push_back(src_new);
new_edges.push_back(k);
num_edges++;
}
}
out_indptr_data[i+1] = num_edges;
}
auto out_indices = torch::from_blob(new_indices.data(), {num_edges}, indptr.options()).clone();
auto out_edges = torch::from_blob(new_edges.data(), {num_edges}, indptr.options()).clone();
auto out_nodes = torch::arange(0, num_nodes);
return std::make_tuple(out_indptr, out_indices, out_nodes, out_edges);
}
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor>
coo2csr_cpu(torch::Tensor row, torch::Tensor col, torch::Tensor val, int64_t num_nodes) {
auto nnz = row.size(0);
auto row_ptr = torch::zeros(num_nodes+1, row.options());
auto col_ind = torch::empty(nnz, col.options());
auto out_val = torch::empty(nnz, val.options());
auto row_ptr_data = row_ptr.data_ptr<int64_t>();
auto col_ind_data = col_ind.data_ptr<int64_t>();
auto out_val_data = out_val.data_ptr<float>();
auto row_data = row.data_ptr<int64_t>();
auto col_data = col.data_ptr<int64_t>();
auto val_data = val.data_ptr<float>();
for(int64_t i = 0; i < nnz; i++) {
row_ptr_data[row_data[i]]++;
}
int64_t temp, row_num, dest;
for(int64_t i = 0, cumsum = 0; i < num_nodes; i++) {
temp = row_ptr_data[i];
row_ptr_data[i] = cumsum;
cumsum += temp;
}
row_ptr_data[num_nodes] = nnz;
for(int64_t i = 0; i < nnz; i++) {
row_num = row_data[i];
dest = row_ptr_data[row_num];
col_ind_data[dest] = col_data[i];
out_val_data[dest] = val_data[i];
row_ptr_data[row_num]++;
}
for(int64_t i = 0, last = 0; i <= num_nodes; i++){
temp = row_ptr_data[i];
row_ptr_data[i] = last;
last = temp;
}
return std::make_tuple(row_ptr, col_ind, out_val);
}
std::tuple<torch::Tensor, torch::Tensor>
coo2csr_cpu_index(torch::Tensor row, torch::Tensor col, int64_t num_nodes) {
auto nnz = row.size(0);
auto row_ptr = torch::zeros(num_nodes+1, row.options());
auto col_ind = torch::empty(nnz, col.options());
auto row_ptr_data = row_ptr.data_ptr<int64_t>();
auto col_ind_data = col_ind.data_ptr<int64_t>();
auto row_data = row.data_ptr<int64_t>();
auto col_data = col.data_ptr<int64_t>();
for(int64_t i = 0; i < nnz; i++) {
row_ptr_data[row_data[i]]++;
}
int64_t temp, row_num, dest;
for(int64_t i = 0, cumsum = 0; i < num_nodes; i++) {
temp = row_ptr_data[i];
row_ptr_data[i] = cumsum;
cumsum += temp;
}
row_ptr_data[num_nodes] = nnz;
for(int64_t i = 0; i < nnz; i++) {
row_num = row_data[i];
dest = row_ptr_data[row_num];
col_ind_data[dest] = i;
row_ptr_data[row_num]++;
}
for(int64_t i = 0, last = 0; i <= num_nodes; i++){
temp = row_ptr_data[i];
row_ptr_data[i] = last;
last = temp;
}
return std::make_tuple(row_ptr, col_ind);
}
PYBIND11_MODULE(sampler, m) {
m.def("sample_adj", &sample_adj, "sample neighborhood");
m.def("subgraph", &subgraph_cpu, "subgraph");
m.def("coo2csr_cpu", &coo2csr_cpu, "coo2csr");
m.def("coo2csr_cpu_index", &coo2csr_cpu_index, "coo2csr with index");
}
| 9,997
| 3,838
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "common_test_utils/test_common.hpp"
#include <string>
#include <sstream>
#include <fstream>
#include <memory>
#include <queue>
#include <map>
#include <ngraph/function.hpp>
#include <ngraph/opsets/opset3.hpp>
#include <ngraph/pass/constant_folding.hpp>
#include <transformations/utils/utils.hpp>
#include <transformations/init_node_info.hpp>
#include <ngraph/pass/visualize_tree.hpp>
#include <transformations/common_optimizations/transpose_sinking.hpp>
#include <transformations/common_optimizations/transpose_to_reshape.hpp>
#include "common_test_utils/ngraph_test_utils.hpp"
using namespace testing;
using namespace ngraph;
using namespace std;
using InputShape = ngraph::PartialShape;
using TransposeOrder = std::vector<int64_t>;
struct ReferenceParams {
bool no_changes = false;
bool is_empty = false;
std::vector<int64_t> reshape_value;
ReferenceParams() = default;
explicit ReferenceParams(bool no_changes, bool is_empty) : no_changes(no_changes), is_empty(is_empty) {}
explicit ReferenceParams(const std::vector<int64_t> & reshape_value): reshape_value(reshape_value) {}
};
class TransposeToReshapeTests: public CommonTestUtils::TestsCommon,
public testing::WithParamInterface<std::tuple<InputShape, TransposeOrder, ReferenceParams> > {
public:
std::shared_ptr<ngraph::Function> f, f_ref;
void SetUp() override {
const auto& input_shape = std::get<0>(GetParam());
const auto& transpose_order = std::get<1>(GetParam());
const auto& reference_params = std::get<2>(GetParam());
f = get_initial_function(input_shape, transpose_order);
f_ref = get_reference_function(input_shape, transpose_order, reference_params);
}
private:
std::shared_ptr<ngraph::Function> get_initial_function(const ngraph::PartialShape & input_shape,
const std::vector<int64_t> & transpose_order) {
auto data = std::make_shared<ngraph::opset3::Parameter>(ngraph::element::f32, input_shape);
auto order_const = ngraph::opset3::Constant::create(ngraph::element::i64, ngraph::Shape{transpose_order.size()}, transpose_order);
auto transpose = std::make_shared<ngraph::opset3::Transpose>(data, order_const);
// WA to test cases with transpose elimination
auto relu = std::make_shared<ngraph::opset3::Relu>(transpose);
return std::make_shared<ngraph::Function>(ngraph::NodeVector{relu}, ngraph::ParameterVector{data});
}
std::shared_ptr<ngraph::Function> get_reference_function(const ngraph::PartialShape & input_shape,
const std::vector<int64_t> & transpose_order,
const ReferenceParams & params) {
if (params.no_changes) {
return get_initial_function(input_shape, transpose_order);
}
auto data = std::make_shared<ngraph::opset3::Parameter>(ngraph::element::f32, input_shape);
ngraph::Output<ngraph::Node> reshape_dims, last(data);
if (!params.reshape_value.empty()) {
reshape_dims = ngraph::opset3::Constant::create(ngraph::element::i64, ngraph::Shape{params.reshape_value.size()}, params.reshape_value);
} else {
auto shape_of = std::make_shared<ngraph::opset3::ShapeOf>(data);
reshape_dims = std::make_shared<ngraph::opset3::Gather>(shape_of,
ngraph::opset3::Constant::create(ngraph::element::i64, ngraph::Shape{transpose_order.size()}, transpose_order),
ngraph::opset3::Constant::create(ngraph::element::i64, ngraph::Shape{1}, {0}));
}
if (!params.is_empty) {
last = std::make_shared<ngraph::opset3::Reshape>(last, reshape_dims, true);
}
last = std::make_shared<ngraph::opset3::Relu>(last);
return std::make_shared<ngraph::Function>(ngraph::NodeVector{last.get_node_shared_ptr()}, ngraph::ParameterVector{data});
}
};
TEST_P(TransposeToReshapeTests, CompareFunctions) {
auto unh = std::make_shared<ngraph::pass::UniqueNamesHolder>();
pass::Manager m;
m.register_pass<pass::InitUniqueNames>(unh);
m.register_pass<ngraph::pass::InitNodeInfo>();
m.register_pass<ngraph::pass::TransposeToReshape>();
m.register_pass<ngraph::pass::CheckUniqueNames>(unh);
m.run_passes(f);
f->validate_nodes_and_infer_types();
ASSERT_NO_THROW(check_rt_info(f));
auto fc = FunctionsComparator::no_default().enable(FunctionsComparator::PRECISIONS);
auto res = fc.compare(f, f_ref);
ASSERT_TRUE(res.valid) << res.message;
}
#define SAME_FUNCTION ReferenceParams(true, false)
#define EMPTY_FUNCTION ReferenceParams(false, true)
#define SHAPE_OF_GATHER ReferenceParams()
INSTANTIATE_TEST_SUITE_P(KeepTranspose, TransposeToReshapeTests,
testing::Values(std::make_tuple(InputShape{1, 3, 64, 64}, TransposeOrder{0, 1, 3, 2}, SAME_FUNCTION),
std::make_tuple(InputShape{1, 3, 1, 64}, TransposeOrder{2, 0, 3, 1}, SAME_FUNCTION),
std::make_tuple(InputShape{1, 3, 1, 3}, TransposeOrder{3, 0, 2, 1}, SAME_FUNCTION),
std::make_tuple(InputShape{DYN, 2, 64, 1}, TransposeOrder{1, 0, 3, 2}, SAME_FUNCTION),
std::make_tuple(InputShape{DYN, 3}, TransposeOrder{1, 0}, SAME_FUNCTION),
std::make_tuple(InputShape{DYN, DYN, 1}, TransposeOrder{2, 1, 0}, SAME_FUNCTION),
std::make_tuple(InputShape{DYN, DYN}, TransposeOrder{1, 0}, SAME_FUNCTION)));
INSTANTIATE_TEST_SUITE_P(EliminateTranspose, TransposeToReshapeTests,
testing::Values(std::make_tuple(InputShape{1, 3, 64, 64}, TransposeOrder{0, 1, 2, 3}, EMPTY_FUNCTION),
std::make_tuple(InputShape{1, 1, 1}, TransposeOrder{2, 0, 1}, EMPTY_FUNCTION),
std::make_tuple(InputShape{DYN, DYN}, TransposeOrder{0, 1}, EMPTY_FUNCTION)));
INSTANTIATE_TEST_SUITE_P(ReshapeWithConstant, TransposeToReshapeTests,
testing::Values(std::make_tuple(InputShape{1, 3, 64, 1}, TransposeOrder{0, 1, 3, 2}, ReferenceParams({1, 3, 1, 64})),
std::make_tuple(InputShape{1, 3, 1, 64}, TransposeOrder{1, 0, 3, 2}, ReferenceParams({3, 1, 64, 1})),
std::make_tuple(InputShape{DYN, DYN, 1}, TransposeOrder{0, 2, 1}, ReferenceParams({0, 1, -1})),
std::make_tuple(InputShape{1, 1, DYN}, TransposeOrder{2, 1, 0}, ReferenceParams({-1, 0, 1})),
std::make_tuple(InputShape{DYN, 1, 64, 1}, TransposeOrder{1, 0, 3, 2}, ReferenceParams({1, -1, 1, 64}))));
INSTANTIATE_TEST_SUITE_P(ReshapeWithGather, TransposeToReshapeTests,
testing::Values(std::make_tuple(InputShape{DYN, 1, DYN, 1}, TransposeOrder{1, 0, 3, 2}, SHAPE_OF_GATHER),
std::make_tuple(InputShape{1, DYN, DYN, DYN}, TransposeOrder{1, 2, 3, 0}, SHAPE_OF_GATHER)));
#undef SAME_FUNCTION
#undef EMPTY_FUNCTION
#undef SHAPE_OF_GATHER
TEST(TransformationTests, replace_transpose_with_reshape) {
auto check_usecase = [](const PartialShape& shape,
const std::vector<int64_t>& perm_val,
bool i32,
bool multiout,
size_t num) {
static size_t id = 0;
auto casename = string("usecase #") + to_string(++id);
shared_ptr<Node> perm;
if (i32) {
std::vector<int32_t> perm_val_i32(perm_val.begin(), perm_val.end());
perm =
op::Constant::create<int32_t>(element::i32, Shape{perm_val.size()}, perm_val_i32);
} else {
perm = op::Constant::create<int64_t>(element::i64, Shape{perm_val.size()}, perm_val);
}
auto param = make_shared<op::Parameter>(element::f32, shape);
shared_ptr<Node> A1;
if (multiout) {
shared_ptr<Node> k;
auto last_dim = shape.rank().get_length() - 1;
if (shape[last_dim].is_dynamic()) {
k = make_shared<op::v1::Gather>(make_shared<op::ShapeOf>(param),
op::Constant::create(element::i64, {}, {last_dim}),
op::Constant::create(element::i64, {}, {0}));
} else {
k = make_shared<op::Constant>(element::i64, Shape{}, std::vector<int64_t>{shape[last_dim].get_length()});
}
A1 = make_shared<op::v1::TopK>(param, k, last_dim,
op::v1::TopK::Mode::MAX, op::v1::TopK::SortType::NONE);
} else {
A1 = make_shared<op::v0::Abs>(param);
}
auto transpose = make_shared<op::v1::Transpose>((multiout ? A1->output(0) : A1), perm);
auto transpose1 = make_shared<op::v0::Abs>(transpose);
auto baseline_f = make_shared<Function>(transpose1, ParameterVector{param});
auto optimized_f = clone_function(*baseline_f);
auto unh = std::make_shared<ngraph::pass::UniqueNamesHolder>();
pass::Manager m;
m.register_pass<pass::InitUniqueNames>(unh);
m.register_pass<ngraph::pass::InitNodeInfo>();
m.register_pass<ngraph::pass::Validate>();
m.register_pass<ngraph::pass::TransposeToReshape>();
m.register_pass<ngraph::pass::CheckUniqueNames>(unh);
m.run_passes(optimized_f);
auto ps = baseline_f->get_results()[0]->get_output_partial_shape(0);
auto ps_r = optimized_f->get_results()[0]->get_output_partial_shape(0);
EXPECT_TRUE(ps.rank().is_static() && ps_r.rank().is_static()) << casename;
ASSERT_EQ(ps.rank().get_length(), ps_r.rank().get_length()) << casename;
ASSERT_EQ(count_ops_of_type<op::v1::Transpose>(baseline_f), 1);
ASSERT_EQ(count_ops_of_type<op::v1::Reshape>(baseline_f), 0);
ASSERT_EQ(count_ops_of_type<op::v1::Transpose>(optimized_f), num);
ASSERT_EQ(count_ops_of_type<op::v1::Reshape>(optimized_f), (num ? 0 : 1));
};
for (auto& i32 : {true, false})
for (auto& multiout : {true, false}) {
check_usecase(Shape{1, 3}, vector<int64_t>{1, 0}, i32, multiout, 0);
check_usecase(Shape{2, 3, 1}, vector<int64_t>{2, 0, 1}, i32, multiout, 0);
check_usecase(Shape{10, 20, 1, 1}, vector<int64_t>{0, 2, 3, 1}, i32, multiout, 0);
check_usecase(Shape{10, 1, 1, 20}, vector<int64_t>{0, 3, 1, 2}, i32, multiout, 0);
check_usecase(Shape{10, 20, 1, 2}, vector<int64_t>{0, 2, 1, 3}, i32, multiout, 0);
check_usecase(Shape{10, 1, 1, 1, 20}, vector<int64_t>{0, 4, 1, 2, 3}, i32, multiout, 0);
check_usecase(Shape{10, 20, 1, 1, 1}, vector<int64_t>{0, 2, 3, 4, 1}, i32, multiout, 0);
check_usecase(Shape{10, 1, 1, 1, 1}, vector<int64_t>{1, 4, 2, 3, 0}, i32, multiout, 0);
check_usecase(Shape{10, 1, 1, 1, 1}, vector<int64_t>{4, 2, 0, 1, 3}, i32, multiout, 0);
check_usecase(Shape{10, 20, 1, 2}, vector<int64_t>{0, 2, 3, 1}, i32, multiout, 1);
check_usecase(Shape{10, 20, 1, 2}, vector<int64_t>{0, 3, 1, 2}, i32, multiout, 1);
check_usecase(Shape{10, 20}, vector<int64_t>{1, 0}, i32, multiout, 1);
check_usecase(PartialShape{Dimension::dynamic(), 20, 1, 1},
vector<int64_t>{
0, 2, 3, 1,
},
i32,
multiout,
0);
check_usecase(PartialShape{Dimension::dynamic(), Dimension::dynamic(), 20, 1, 1},
vector<int64_t>{0, 1, 3, 2, 4},
i32,
multiout,
0);
check_usecase(PartialShape{Dimension::dynamic(), Dimension::dynamic(), 20, 1, 1},
vector<int64_t>{0, 2, 1, 4, 3},
i32,
multiout,
1);
}
}
| 12,354
| 4,424
|
class Solution {
int helper(TreeNode *root, int M) {
if(!root)
return 0;
int good = root->val >= M;
if(good)
M = root->val;
return good + helper(root->left, M) + helper(root->right, M);
}
public:
int goodNodes(TreeNode* root) {
return helper(root, INT_MIN);
}
};
| 343
| 112
|
#include "ComparacionAviones.h"
CompRetorno ComparacionAviones::Comparar(const CostoArco& t1, const CostoArco& t2) const
{
if (t1.aviones > t2.aviones) return MAYOR;
if (t1.aviones < t2.aviones) return MENOR;
if (t1.tiempo > t2.tiempo) return MAYOR;
if (t1.tiempo < t2.tiempo) return MENOR;
return IGUALES;
}
| 318
| 151
|
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) return 1;
if (n < 0) return (1.0 / x) / (myPow(x, -(n + 1)));
double half = myPow(x, n / 2);
if (n % 2) return half * half * x;
else return half * half;
}
};
| 275
| 111
|
// STL includes.
#include <string>
#include <vector>
#include <utility>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
// CGAL includes.
#include <CGAL/Timer.h>
#include <CGAL/property_map.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Shape_detection/Region_growing/Region_growing.h>
#include <CGAL/Shape_detection/Region_growing/Region_growing_on_point_set.h>
namespace SD = CGAL::Shape_detection;
using Kernel = CGAL::Exact_predicates_inexact_constructions_kernel;
using FT = typename Kernel::FT;
using Point_2 = typename Kernel::Point_2;
using Vector_2 = typename Kernel::Vector_2;
using Point_with_normal = std::pair<Point_2, Vector_2>;
using Input_range = std::vector<Point_with_normal>;
using Point_map = CGAL::First_of_pair_property_map<Point_with_normal>;
using Normal_map = CGAL::Second_of_pair_property_map<Point_with_normal>;
using Neighbor_query = SD::Point_set::Sphere_neighbor_query<Kernel, Input_range, Point_map>;
using Region_type = SD::Point_set::Least_squares_line_fit_region<Kernel, Input_range, Point_map, Normal_map>;
using Region_growing = SD::Region_growing<Input_range, Neighbor_query, Region_type>;
using Timer = CGAL::Timer;
using Region = std::vector<std::size_t>;
void benchmark_region_growing_on_point_set_2(
const std::size_t test_count,
const Input_range& input_range,
const FT sphere_radius,
const FT distance_threshold,
const FT angle_threshold,
const std::size_t min_region_size) {
// Create instances of the parameter classes.
Neighbor_query neighbor_query(
input_range,
sphere_radius);
Region_type region_type(
input_range,
distance_threshold, angle_threshold, min_region_size);
// Create an instance of the region growing class.
Region_growing region_growing(
input_range, neighbor_query, region_type);
// Run the algorithm.
Timer timer;
std::vector<Region> regions;
timer.start();
region_growing.detect(std::back_inserter(regions));
timer.stop();
// Compute the number of points assigned to all found regions.
std::size_t number_of_assigned_points = 0;
for (const auto& region : regions)
number_of_assigned_points += region.size();
std::vector<std::size_t> unassigned_points;
region_growing.unassigned_items(std::back_inserter(unassigned_points));
// Print statistics.
std::cout << "Test #" << test_count << std::endl;
std::cout << " sphere_radius = " << sphere_radius << std::endl;
std::cout << " min_region_size = " << min_region_size << std::endl;
std::cout << " distance_threshold = " << distance_threshold << std::endl;
std::cout << " angle_threshold = " << angle_threshold << std::endl;
std::cout << " -----" << std::endl;
std::cout << " Time elapsed: " << timer.time() << std::endl;
std::cout << " Number of detected regions: " << regions.size() << std::endl;
std::cout << " Number of assigned points: " << number_of_assigned_points << std::endl;
std::cout << " Number of unassigned points: " << unassigned_points.size() << std::endl;
std::cout << std::endl << std::endl;
}
int main(int argc, char *argv[]) {
// Load xyz data either from a local folder or a user-provided file.
std::ifstream in(argc > 1 ? argv[1] : "data/point_set_2.xyz");
CGAL::set_ascii_mode(in);
if (!in) {
std::cout <<
"Error: cannot read the file point_set_2.xyz!" << std::endl;
std::cout <<
"You can either create a symlink to the data folder or provide this file by hand."
<< std::endl << std::endl;
return EXIT_FAILURE;
}
Input_range input_range;
FT a, b, c, d, e, f;
while (in >> a >> b >> c >> d >> e >> f)
input_range.push_back(std::make_pair(Point_2(a, b), Vector_2(d, e)));
in.close();
// Default parameter values for the data file point_set_2.xyz.
const FT distance_threshold = FT(45) / FT(10);
const FT angle_threshold = FT(45);
const std::size_t min_region_size = 5;
// Run benchmarks.
benchmark_region_growing_on_point_set_2(1, input_range, FT(1),
distance_threshold, angle_threshold, min_region_size);
benchmark_region_growing_on_point_set_2(2, input_range, FT(3),
distance_threshold, angle_threshold, min_region_size);
benchmark_region_growing_on_point_set_2(3, input_range, FT(6),
distance_threshold, angle_threshold, min_region_size);
benchmark_region_growing_on_point_set_2(4, input_range, FT(9),
distance_threshold, angle_threshold, min_region_size);
return EXIT_SUCCESS;
}
| 4,755
| 1,657
|
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/gmm_helper/gmm_helper.h"
#include "shared/source/gmm_helper/gmm_interface.h"
#include "shared/source/gmm_helper/resource_info.h"
#include "shared/source/helpers/api_specific_config.h"
#include "shared/source/os_interface/hw_info_config.h"
#include "shared/source/utilities/debug_settings_reader.h"
#include "shared/test/common/helpers/custom_event_listener.h"
#include "shared/test/common/helpers/default_hw_info.inl"
#include "shared/test/common/helpers/kernel_binary_helper.h"
#include "shared/test/common/helpers/memory_leak_listener.h"
#include "shared/test/common/helpers/test_files.h"
#include "shared/test/common/helpers/ult_hw_config.inl"
#include "shared/test/common/libult/global_environment.h"
#include "shared/test/common/mocks/mock_gmm.h"
#include "shared/test/common/mocks/mock_gmm_client_context.h"
#include "shared/test/common/mocks/mock_sip.h"
#include "shared/test/common/test_macros/test_checks_shared.h"
#include "shared/test/unit_test/base_ult_config_listener.h"
#include "shared/test/unit_test/test_stats.h"
#include "shared/test/unit_test/tests_configuration.h"
#include "gmock/gmock.h"
#include <algorithm>
#include <fstream>
#include <limits.h>
#include <mutex>
#include <sstream>
#include <thread>
#ifdef WIN32
const char *fSeparator = "\\";
#else
const char *fSeparator = "/";
#endif
TEST(Should, pass) { EXPECT_TRUE(true); }
namespace NEO {
extern const char *hardwarePrefix[];
extern const HardwareInfo *hardwareInfoTable[IGFX_MAX_PRODUCT];
extern const unsigned int ultIterationMaxTime;
extern bool useMockGmm;
extern TestMode testMode;
extern const char *executionDirectorySuffix;
std::thread::id tempThreadID;
namespace MockSipData {
extern std::unique_ptr<MockSipKernel> mockSipKernel;
}
namespace PagaFaultManagerTestConfig {
bool disabled = false;
}
} // namespace NEO
using namespace NEO;
PRODUCT_FAMILY productFamily = DEFAULT_TEST_PLATFORM::hwInfo.platform.eProductFamily;
extern GFXCORE_FAMILY renderCoreFamily;
extern std::string lastTest;
bool generateRandomInput = false;
void applyWorkarounds() {
{
std::ofstream f;
const std::string fileName("_tmp_");
f.open(fileName, std::ofstream::binary);
f.close();
}
{
std::mutex mtx;
std::unique_lock<std::mutex> stateLock(mtx);
}
{
std::stringstream ss("1");
int val;
ss >> val;
}
{
class BaseClass {
public:
int method(int param) { return 1; }
};
class MockClass : public BaseClass {
public:
MOCK_METHOD1(method, int(int param));
};
::testing::NiceMock<MockClass> mockObj;
EXPECT_CALL(mockObj, method(::testing::_))
.Times(1);
mockObj.method(2);
}
//intialize rand
srand(static_cast<unsigned int>(time(nullptr)));
//Create at least on thread to prevent false memory leaks in tests using threads
std::thread t([&]() {
});
tempThreadID = t.get_id();
t.join();
//Create FileLogger to prevent false memory leaks
{
NEO::FileLoggerInstance();
}
}
#ifdef __linux__
void handle_SIGALRM(int signal) {
std::cout << "Tests timeout on: " << lastTest << std::endl;
abort();
}
void handle_SIGSEGV(int signal) {
std::cout << "SIGSEGV on: " << lastTest << std::endl;
abort();
}
struct sigaction oldSigAbrt;
void handle_SIGABRT(int signal) {
std::cout << "SIGABRT on: " << lastTest << std::endl;
// restore signal handler to abort
if (sigaction(SIGABRT, &oldSigAbrt, nullptr) == -1) {
std::cout << "FATAL: cannot fatal SIGABRT handler" << std::endl;
std::cout << "FATAL: try SEGV" << std::endl;
uint8_t *ptr = nullptr;
*ptr = 0;
std::cout << "FATAL: still alive, call exit()" << std::endl;
exit(-1);
}
raise(signal);
}
#else
LONG WINAPI UltExceptionFilter(
_In_ struct _EXCEPTION_POINTERS *exceptionInfo) {
std::cout << "UnhandledException: 0x" << std::hex << exceptionInfo->ExceptionRecord->ExceptionCode << std::dec
<< " on test: " << lastTest
<< std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
std::string getHardwarePrefix() {
std::string s = hardwarePrefix[defaultHwInfo->platform.eProductFamily];
return s;
}
std::string getRunPath(char *argv0) {
std::string res(argv0);
auto pos = res.rfind(fSeparator);
if (pos != std::string::npos)
res = res.substr(0, pos);
if (res == "." || pos == std::string::npos) {
char *cwd;
#if defined(__linux__)
cwd = getcwd(nullptr, 0);
#else
cwd = _getcwd(nullptr, 0);
#endif
res = cwd;
free(cwd);
}
return res;
}
int main(int argc, char **argv) {
int retVal = 0;
bool useDefaultListener = false;
bool enable_alarm = true;
bool setupFeatureTableAndWorkaroundTable = testMode == TestMode::AubTests ? true : false;
bool showTestStats = false;
applyWorkarounds();
#if defined(__linux__)
bool enable_segv = true;
bool enable_abrt = true;
if (getenv("IGDRCL_TEST_SELF_EXEC") == nullptr) {
std::string wd = getRunPath(argv[0]);
char *ldLibraryPath = getenv("LD_LIBRARY_PATH");
if (ldLibraryPath == nullptr) {
setenv("LD_LIBRARY_PATH", wd.c_str(), 1);
} else {
std::string ldLibraryPathConcat = wd + ":" + std::string(ldLibraryPath);
setenv("LD_LIBRARY_PATH", ldLibraryPathConcat.c_str(), 1);
}
setenv("IGDRCL_TEST_SELF_EXEC", wd.c_str(), 1);
execv(argv[0], argv);
printf("FATAL ERROR: cannot self-exec test: %s!, errno: %d\n", argv[0], errno);
return -1;
}
#endif
::testing::InitGoogleMock(&argc, argv);
HardwareInfo hwInfoForTests = DEFAULT_TEST_PLATFORM::hwInfo;
uint32_t euPerSubSlice = 0;
uint32_t sliceCount = 0;
uint32_t subSlicePerSliceCount = 0;
int32_t revId = -1;
int dieRecovery = 0;
for (int i = 1; i < argc; ++i) {
if (!strcmp("--disable_default_listener", argv[i])) {
useDefaultListener = false;
} else if (!strcmp("--enable_default_listener", argv[i])) {
useDefaultListener = true;
} else if (!strcmp("--disable_alarm", argv[i])) {
enable_alarm = false;
} else if (!strcmp("--show_test_stats", argv[i])) {
showTestStats = true;
} else if (!strcmp("--disable_pagefaulting_tests", argv[i])) { //disable tests which raise page fault signal during execution
NEO::PagaFaultManagerTestConfig::disabled = true;
} else if (!strcmp("--tbx", argv[i])) {
if (testMode == TestMode::AubTests) {
testMode = TestMode::AubTestsWithTbx;
}
initialHardwareTag = 0;
} else if (!strcmp("--rev_id", argv[i])) {
++i;
if (i < argc) {
revId = atoi(argv[i]);
}
} else if (!strcmp("--product", argv[i])) {
++i;
if (i < argc) {
if (::isdigit(argv[i][0])) {
int productValue = atoi(argv[i]);
if (productValue > 0 && productValue < IGFX_MAX_PRODUCT && hardwarePrefix[productValue] != nullptr) {
productFamily = static_cast<PRODUCT_FAMILY>(productValue);
} else {
productFamily = IGFX_UNKNOWN;
}
} else {
productFamily = IGFX_UNKNOWN;
for (int j = 0; j < IGFX_MAX_PRODUCT; j++) {
if (hardwarePrefix[j] == nullptr)
continue;
if (strcmp(hardwarePrefix[j], argv[i]) == 0) {
productFamily = static_cast<PRODUCT_FAMILY>(j);
break;
}
}
}
if (productFamily == IGFX_UNKNOWN) {
std::cout << "unknown or unsupported product family has been set: " << argv[i] << std::endl;
return -1;
} else {
std::cout << "product family: " << hardwarePrefix[productFamily] << " (" << productFamily << ")" << std::endl;
}
hwInfoForTests = *hardwareInfoTable[productFamily];
}
} else if (!strcmp("--slices", argv[i])) {
++i;
if (i < argc) {
sliceCount = atoi(argv[i]);
}
} else if (!strcmp("--subslices", argv[i])) {
++i;
if (i < argc) {
subSlicePerSliceCount = atoi(argv[i]);
}
} else if (!strcmp("--eu_per_ss", argv[i])) {
++i;
if (i < argc) {
euPerSubSlice = atoi(argv[i]);
}
} else if (!strcmp("--die_recovery", argv[i])) {
++i;
if (i < argc) {
dieRecovery = atoi(argv[i]) ? 1 : 0;
}
} else if (!strcmp("--generate_random_inputs", argv[i])) {
generateRandomInput = true;
} else if (!strcmp("--read-config", argv[i]) && (testMode == TestMode::AubTests || testMode == TestMode::AubTestsWithTbx)) {
if (DebugManager.registryReadAvailable()) {
DebugManager.setReaderImpl(SettingsReader::create(ApiSpecificConfig::getRegistryPath()));
DebugManager.injectSettingsFromReader();
}
} else if (!strcmp("--dump_buffer_format", argv[i]) && testMode == TestMode::AubTests) {
++i;
std::string dumpBufferFormat(argv[i]);
std::transform(dumpBufferFormat.begin(), dumpBufferFormat.end(), dumpBufferFormat.begin(), ::toupper);
DebugManager.flags.AUBDumpBufferFormat.set(dumpBufferFormat);
} else if (!strcmp("--dump_image_format", argv[i]) && testMode == TestMode::AubTests) {
++i;
std::string dumpImageFormat(argv[i]);
std::transform(dumpImageFormat.begin(), dumpImageFormat.end(), dumpImageFormat.begin(), ::toupper);
DebugManager.flags.AUBDumpImageFormat.set(dumpImageFormat);
}
}
if (showTestStats) {
std::cout << getTestStats() << std::endl;
return 0;
}
productFamily = hwInfoForTests.platform.eProductFamily;
renderCoreFamily = hwInfoForTests.platform.eRenderCoreFamily;
uint32_t threadsPerEu = hwInfoConfigFactory[productFamily]->threadsPerEu;
PLATFORM &platform = hwInfoForTests.platform;
if (revId != -1) {
platform.usRevId = revId;
} else {
revId = platform.usRevId;
}
uint64_t hwInfoConfig = defaultHardwareInfoConfigTable[productFamily];
setHwInfoValuesFromConfig(hwInfoConfig, hwInfoForTests);
// set Gt and FeatureTable to initial state
hardwareInfoSetup[productFamily](&hwInfoForTests, setupFeatureTableAndWorkaroundTable, hwInfoConfig);
GT_SYSTEM_INFO >SystemInfo = hwInfoForTests.gtSystemInfo;
// and adjust dynamic values if not secified
sliceCount = sliceCount > 0 ? sliceCount : gtSystemInfo.SliceCount;
subSlicePerSliceCount = subSlicePerSliceCount > 0 ? subSlicePerSliceCount : (gtSystemInfo.SubSliceCount / sliceCount);
euPerSubSlice = euPerSubSlice > 0 ? euPerSubSlice : gtSystemInfo.MaxEuPerSubSlice;
// clang-format off
gtSystemInfo.SliceCount = sliceCount;
gtSystemInfo.SubSliceCount = gtSystemInfo.SliceCount * subSlicePerSliceCount;
gtSystemInfo.EUCount = gtSystemInfo.SubSliceCount * euPerSubSlice - dieRecovery;
gtSystemInfo.ThreadCount = gtSystemInfo.EUCount * threadsPerEu;
gtSystemInfo.MaxEuPerSubSlice = std::max(gtSystemInfo.MaxEuPerSubSlice, euPerSubSlice);
gtSystemInfo.MaxSlicesSupported = std::max(gtSystemInfo.MaxSlicesSupported, gtSystemInfo.SliceCount);
gtSystemInfo.MaxSubSlicesSupported = std::max(gtSystemInfo.MaxSubSlicesSupported, gtSystemInfo.SubSliceCount);
gtSystemInfo.IsDynamicallyPopulated = false;
// clang-format on
binaryNameSuffix.append(familyName[hwInfoForTests.platform.eRenderCoreFamily]);
binaryNameSuffix.append(hwInfoForTests.capabilityTable.platformType);
std::string testBinaryFiles = getRunPath(argv[0]);
testBinaryFiles.append("/");
testBinaryFiles.append(binaryNameSuffix);
testBinaryFiles.append("/");
testBinaryFiles.append(std::to_string(revId));
testBinaryFiles.append("/");
testBinaryFiles.append(testFiles);
testFiles = testBinaryFiles;
std::string executionDirectory(hardwarePrefix[productFamily]);
executionDirectory += NEO::executionDirectorySuffix; // _aub for aub_tests, empty otherwise
executionDirectory += "/";
executionDirectory += std::to_string(revId);
#ifdef WIN32
#include <direct.h>
if (_chdir(executionDirectory.c_str())) {
std::cout << "chdir into " << executionDirectory << " directory failed.\nThis might cause test failures." << std::endl;
}
#elif defined(__linux__)
#include <unistd.h>
if (chdir(executionDirectory.c_str()) != 0) {
std::cout << "chdir into " << executionDirectory << " directory failed.\nThis might cause test failures." << std::endl;
}
#endif
defaultHwInfo = std::make_unique<HardwareInfo>();
*defaultHwInfo = hwInfoForTests;
auto &listeners = ::testing::UnitTest::GetInstance()->listeners();
if (useDefaultListener == false) {
auto defaultListener = listeners.default_result_printer();
auto customEventListener = new CCustomEventListener(defaultListener, hardwarePrefix[productFamily]);
listeners.Release(defaultListener);
listeners.Append(customEventListener);
}
listeners.Append(new MemoryLeakListener);
listeners.Append(new BaseUltConfigListener);
gEnvironment = reinterpret_cast<TestEnvironment *>(::testing::AddGlobalTestEnvironment(new TestEnvironment));
MockCompilerDebugVars fclDebugVars;
MockCompilerDebugVars igcDebugVars;
std::string builtInsFileName;
if (TestChecks::supportsImages(defaultHwInfo)) {
builtInsFileName = KernelBinaryHelper::BUILT_INS_WITH_IMAGES;
} else {
builtInsFileName = KernelBinaryHelper::BUILT_INS;
}
retrieveBinaryKernelFilename(fclDebugVars.fileName, builtInsFileName + "_", ".bc");
retrieveBinaryKernelFilename(igcDebugVars.fileName, builtInsFileName + "_", ".gen");
gEnvironment->setMockFileNames(fclDebugVars.fileName, igcDebugVars.fileName);
gEnvironment->setDefaultDebugVars(fclDebugVars, igcDebugVars, hwInfoForTests);
#if defined(__linux__)
//ULTs timeout
if (enable_alarm) {
auto currentUltIterationMaxTime = NEO::ultIterationMaxTime;
auto ultIterationMaxTimeEnv = getenv("NEO_ULT_ITERATION_MAX_TIME");
if (ultIterationMaxTimeEnv != nullptr) {
currentUltIterationMaxTime = atoi(ultIterationMaxTimeEnv);
}
unsigned int alarmTime = currentUltIterationMaxTime * ::testing::GTEST_FLAG(repeat);
struct sigaction sa;
sa.sa_handler = &handle_SIGALRM;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGALRM, &sa, NULL) == -1) {
printf("FATAL ERROR: cannot intercept SIGALRM\n");
return -2;
}
alarm(alarmTime);
std::cout << "set timeout to: " << alarmTime << std::endl;
}
if (enable_segv) {
struct sigaction sa;
sa.sa_handler = &handle_SIGSEGV;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGSEGV, &sa, NULL) == -1) {
printf("FATAL ERROR: cannot intercept SIGSEGV\n");
return -2;
}
}
if (enable_abrt) {
struct sigaction sa;
sa.sa_handler = &handle_SIGABRT;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGABRT, &sa, &oldSigAbrt) == -1) {
printf("FATAL ERROR: cannot intercept SIGABRT\n");
return -2;
}
}
#else
SetUnhandledExceptionFilter(&UltExceptionFilter);
#endif
if (useMockGmm) {
GmmHelper::createGmmContextWrapperFunc = GmmClientContext::create<MockGmmClientContext>;
} else {
GmmInterface::initialize(nullptr, nullptr);
}
NEO::MockSipData::mockSipKernel.reset(new NEO::MockSipKernel());
retVal = RUN_ALL_TESTS();
return retVal;
}
| 16,671
| 5,423
|
#include <nano/lib/errors.hpp>
#include <nano/lib/threading.hpp>
#include <nano/lib/utility.hpp>
#include <nano/node/cli.hpp>
#include <nano/node/ipc/ipc_server.hpp>
#include <nano/rpc/rpc.hpp>
#include <nano/rpc/rpc_request_processor.hpp>
#include <nano/secure/utility.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/program_options.hpp>
#include <csignal>
namespace
{
void logging_init (boost::filesystem::path const & application_path_a)
{
static std::atomic_flag logging_already_added = ATOMIC_FLAG_INIT;
if (!logging_already_added.test_and_set ())
{
boost::log::add_common_attributes ();
auto path = application_path_a / "log";
uintmax_t max_size{ 128 * 1024 * 1024 };
uintmax_t rotation_size{ 4 * 1024 * 1024 };
bool flush{ true };
boost::log::add_file_log (boost::log::keywords::target = path, boost::log::keywords::file_name = path / "rpc_log_%Y-%m-%d_%H-%M-%S.%N.log", boost::log::keywords::rotation_size = rotation_size, boost::log::keywords::auto_flush = flush, boost::log::keywords::scan_method = boost::log::sinks::file::scan_method::scan_matching, boost::log::keywords::max_size = max_size, boost::log::keywords::format = "[%TimeStamp%]: %Message%");
}
}
volatile sig_atomic_t sig_int_or_term = 0;
void run (boost::filesystem::path const & data_path, std::vector<std::string> const & config_overrides)
{
boost::filesystem::create_directories (data_path);
boost::system::error_code error_chmod;
nano::set_secure_perm_directory (data_path, error_chmod);
std::unique_ptr<nano::thread_runner> runner;
nano::rpc_config rpc_config;
auto error = nano::read_rpc_config_toml (data_path, rpc_config, config_overrides);
if (!error)
{
logging_init (data_path);
boost::asio::io_context io_ctx;
try
{
nano::ipc_rpc_processor ipc_rpc_processor (io_ctx, rpc_config);
auto rpc = nano::get_rpc (io_ctx, rpc_config, ipc_rpc_processor);
rpc->start ();
debug_assert (!nano::signal_handler_impl);
nano::signal_handler_impl = [&io_ctx]() {
io_ctx.stop ();
sig_int_or_term = 1;
};
std::signal (SIGINT, &nano::signal_handler);
std::signal (SIGTERM, &nano::signal_handler);
runner = std::make_unique<nano::thread_runner> (io_ctx, rpc_config.rpc_process.io_threads);
runner->join ();
if (sig_int_or_term == 1)
{
rpc->stop ();
}
}
catch (const std::runtime_error & e)
{
std::cerr << "Error while running rpc (" << e.what () << ")\n";
}
}
else
{
std::cerr << "Error deserializing config: " << error.get_message () << std::endl;
}
}
}
int main (int argc, char * const * argv)
{
nano::set_umask ();
boost::program_options::options_description description ("Command line options");
// clang-format off
description.add_options ()
("help", "Print out options")
("config", boost::program_options::value<std::vector<std::string>>()->multitoken(), "Pass RPC configuration values. This takes precedence over any values in the configuration file. This option can be repeated multiple times.")
("daemon", "Start RPC daemon")
("data_path", boost::program_options::value<std::string> (), "Use the supplied path as the data directory")
("network", boost::program_options::value<std::string> (), "Use the supplied network (live, beta or test)")
("version", "Prints out version");
// clang-format on
boost::program_options::variables_map vm;
try
{
boost::program_options::store (boost::program_options::parse_command_line (argc, argv, description), vm);
}
catch (boost::program_options::error const & err)
{
std::cerr << err.what () << std::endl;
return 1;
}
boost::program_options::notify (vm);
auto network (vm.find ("network"));
if (network != vm.end ())
{
auto err (nano::network_constants::set_active_network (network->second.as<std::string> ()));
if (err)
{
std::cerr << nano::network_constants::active_network_err_msg << std::endl;
std::exit (1);
}
}
auto data_path_it = vm.find ("data_path");
if (data_path_it == vm.end ())
{
std::string error_string;
if (!nano::migrate_working_path (error_string))
{
std::cerr << error_string << std::endl;
return 1;
}
}
boost::filesystem::path data_path ((data_path_it != vm.end ()) ? data_path_it->second.as<std::string> () : nano::working_path ());
if (vm.count ("daemon") > 0)
{
std::vector<std::string> config_overrides;
auto config (vm.find ("config"));
if (config != vm.end ())
{
config_overrides = config->second.as<std::vector<std::string>> ();
}
run (data_path, config_overrides);
}
else if (vm.count ("version"))
{
std::cout << "Version " << NANO_VERSION_STRING << "\n"
<< "Build Info " << BUILD_INFO << std::endl;
}
else
{
std::cout << description << std::endl;
}
return 1;
}
| 4,835
| 1,895
|
/** @file
A brief file description
@section license License
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.
*/
/****************************************************************************
ink_hash_table.c
This file implements hash tables. This allows us to provide alternative
implementations of hash tables.
****************************************************************************/
#include "ts/ink_error.h"
#include "ts/ink_hash_table.h"
#include "ts/ink_memory.h"
/*===========================================================================*
This is the Tcl implementation of InkHashTable
*===========================================================================*/
/*---------------------------------------------------------------------------*
InkHashTable *ink_hash_table_create(InkHashTableKeyType key_type)
This routine allocates an initializes an empty InkHashTable, and returns a
pointer to the new table. The <key_type> argument indicates whether keys
are represented as strings, or as words. Legal values are
InkHashTableKeyType_String and InkHashTableKeyType_Word.
*---------------------------------------------------------------------------*/
InkHashTable *
ink_hash_table_create(InkHashTableKeyType key_type)
{
InkHashTable *ht_ptr;
Tcl_HashTable *tcl_ht_ptr;
int tcl_key_type;
tcl_ht_ptr = (Tcl_HashTable *)ats_malloc(sizeof(Tcl_HashTable));
if (key_type == InkHashTableKeyType_String)
tcl_key_type = TCL_STRING_KEYS;
else if (key_type == InkHashTableKeyType_Word)
tcl_key_type = TCL_ONE_WORD_KEYS;
else
ink_fatal("ink_hash_table_create: bad key_type %d", key_type);
Tcl_InitHashTable(tcl_ht_ptr, tcl_key_type);
ht_ptr = (InkHashTable *)tcl_ht_ptr;
return (ht_ptr);
} /* End ink_hash_table_create */
/*---------------------------------------------------------------------------*
void ink_hash_table_destroy(InkHashTable *ht_ptr)
This routine takes a hash table <ht_ptr>, and frees its storage.
*---------------------------------------------------------------------------*/
InkHashTable *
ink_hash_table_destroy(InkHashTable *ht_ptr)
{
Tcl_HashTable *tcl_ht_ptr;
tcl_ht_ptr = (Tcl_HashTable *)ht_ptr;
Tcl_DeleteHashTable(tcl_ht_ptr);
ats_free(tcl_ht_ptr);
return (InkHashTable *)0;
} /* End ink_hash_table_destroy */
/*---------------------------------------------------------------------------*
void ink_hash_table_destroy_and_free_values(InkHashTable *ht_ptr)
This routine takes a hash table <ht_ptr>, and frees its storage, after
first calling ink_free on all the values. You better darn well make sure the
values have been dynamically allocated.
*---------------------------------------------------------------------------*/
static int
_ink_hash_table_free_entry_value(InkHashTable *ht_ptr, InkHashTableEntry *e)
{
InkHashTableValue value;
value = ink_hash_table_entry_value(ht_ptr, e);
if (value != NULL) {
ats_free(value);
}
return (0);
} /* End _ink_hash_table_free_entry_value */
InkHashTable *
ink_hash_table_destroy_and_free_values(InkHashTable *ht_ptr)
{
ink_hash_table_map(ht_ptr, _ink_hash_table_free_entry_value);
ink_hash_table_destroy(ht_ptr);
return (InkHashTable *)0;
} /* End ink_hash_table_destroy_and_free_values */
/*---------------------------------------------------------------------------*
int ink_hash_table_isbound(InkHashTable *ht_ptr, InkHashTableKey key)
This routine takes a hash table <ht_ptr>, a key <key>, and returns 1
if the value <key> is bound in the hash table, 0 otherwise.
*---------------------------------------------------------------------------*/
int
ink_hash_table_isbound(InkHashTable *ht_ptr, const char *key)
{
InkHashTableEntry *he_ptr;
he_ptr = ink_hash_table_lookup_entry(ht_ptr, key);
return ((he_ptr == NULL) ? 0 : 1);
} /* End ink_hash_table_isbound */
/*---------------------------------------------------------------------------*
int ink_hash_table_lookup(InkHashTable *ht_ptr,
InkHashTableKey key,
InkHashTableValue *value_ptr)
This routine takes a hash table <ht_ptr>, a key <key>, and stores the
value bound to the key by reference through <value_ptr>. If no binding is
found, 0 is returned, else 1 is returned.
*---------------------------------------------------------------------------*/
int
ink_hash_table_lookup(InkHashTable *ht_ptr, const char *key, InkHashTableValue *value_ptr)
{
InkHashTableEntry *he_ptr;
InkHashTableValue value;
he_ptr = ink_hash_table_lookup_entry(ht_ptr, key);
if (he_ptr == NULL)
return (0);
value = ink_hash_table_entry_value(ht_ptr, he_ptr);
*value_ptr = value;
return (1);
} /* End ink_hash_table_lookup */
/*---------------------------------------------------------------------------*
int ink_hash_table_delete(InkHashTable *ht_ptr, InkHashTableKey key)
This routine takes a hash table <ht_ptr> and a key <key>, and deletes the
binding for the <key> in the hash table if it exists. This routine
returns 1 if the key existed, else 0.
*---------------------------------------------------------------------------*/
int
ink_hash_table_delete(InkHashTable *ht_ptr, const char *key)
{
char *tcl_key;
Tcl_HashTable *tcl_ht_ptr;
Tcl_HashEntry *tcl_he_ptr;
tcl_key = (char *)key;
tcl_ht_ptr = (Tcl_HashTable *)ht_ptr;
tcl_he_ptr = Tcl_FindHashEntry(tcl_ht_ptr, tcl_key);
if (!tcl_he_ptr)
return (0);
Tcl_DeleteHashEntry(tcl_he_ptr);
return (1);
} /* End ink_hash_table_delete */
/*---------------------------------------------------------------------------*
InkHashTableEntry *ink_hash_table_lookup_entry(InkHashTable *ht_ptr,
InkHashTableKey key)
This routine takes a hash table <ht_ptr> and a key <key>, and returns the
entry matching the key, or NULL otherwise.
*---------------------------------------------------------------------------*/
InkHashTableEntry *
ink_hash_table_lookup_entry(InkHashTable *ht_ptr, const char *key)
{
Tcl_HashTable *tcl_ht_ptr;
Tcl_HashEntry *tcl_he_ptr;
InkHashTableEntry *he_ptr;
tcl_ht_ptr = (Tcl_HashTable *)ht_ptr;
tcl_he_ptr = Tcl_FindHashEntry(tcl_ht_ptr, key);
he_ptr = (InkHashTableEntry *)tcl_he_ptr;
return (he_ptr);
} /* End ink_hash_table_lookup_entry */
/*---------------------------------------------------------------------------*
InkHashTableEntry *ink_hash_table_get_entry(InkHashTable *ht_ptr,
InkHashTableKey key,
int *new_value)
This routine takes a hash table <ht_ptr> and a key <key>, and returns the
entry matching the key, or creates, binds, and returns a new entry.
If the binding already existed, *new is set to 0, else 1.
*---------------------------------------------------------------------------*/
InkHashTableEntry *
ink_hash_table_get_entry(InkHashTable *ht_ptr, const char *key, int *new_value)
{
Tcl_HashTable *tcl_ht_ptr;
Tcl_HashEntry *tcl_he_ptr;
tcl_ht_ptr = (Tcl_HashTable *)ht_ptr;
tcl_he_ptr = Tcl_CreateHashEntry(tcl_ht_ptr, key, new_value);
if (tcl_he_ptr == NULL) {
ink_fatal("%s: Tcl_CreateHashEntry returned NULL", "ink_hash_table_get_entry");
}
return ((InkHashTableEntry *)tcl_he_ptr);
} /* End ink_hash_table_get_entry */
/*---------------------------------------------------------------------------*
void ink_hash_table_set_entry(InkHashTable *ht_ptr,
InkHashTableEntry *he_ptr,
InkHashTableValue value)
This routine takes a hash table <ht_ptr>, a hash table entry <he_ptr>,
and changes the value field of the entry to <value>.
*---------------------------------------------------------------------------*/
void
ink_hash_table_set_entry(InkHashTable *ht_ptr, InkHashTableEntry *he_ptr, InkHashTableValue value)
{
(void)ht_ptr;
ClientData tcl_value;
Tcl_HashEntry *tcl_he_ptr;
tcl_value = (ClientData)value;
tcl_he_ptr = (Tcl_HashEntry *)he_ptr;
Tcl_SetHashValue(tcl_he_ptr, tcl_value);
} /* End ink_hash_table_set_entry */
/*---------------------------------------------------------------------------*
void ink_hash_table_insert(InkHashTable *ht_ptr,
InkHashTableKey key,
InkHashTableValue value)
This routine takes a hash table <ht_ptr>, a key <key>, and binds the value
<value> to the key, replacing any previous binding, if any.
*---------------------------------------------------------------------------*/
void
ink_hash_table_insert(InkHashTable *ht_ptr, const char *key, InkHashTableValue value)
{
int new_value;
InkHashTableEntry *he_ptr;
he_ptr = ink_hash_table_get_entry(ht_ptr, key, &new_value);
ink_hash_table_set_entry(ht_ptr, he_ptr, value);
} /* End ink_hash_table_insert */
/*---------------------------------------------------------------------------*
void ink_hash_table_map(InkHashTable *ht_ptr, InkHashTableEntryFunction map)
This routine takes a hash table <ht_ptr> and a function pointer <map>, and
applies the function <map> to each entry in the hash table. The function
<map> should return 0 normally, otherwise the iteration will stop.
*---------------------------------------------------------------------------*/
void
ink_hash_table_map(InkHashTable *ht_ptr, InkHashTableEntryFunction map)
{
int retcode;
InkHashTableEntry *e;
InkHashTableIteratorState state;
for (e = ink_hash_table_iterator_first(ht_ptr, &state); e != NULL; e = ink_hash_table_iterator_next(ht_ptr, &state)) {
retcode = (*map)(ht_ptr, e);
if (retcode != 0)
break;
}
} /* End ink_hash_table_map */
/*---------------------------------------------------------------------------*
InkHashTableKey ink_hash_table_entry_key(InkHashTable *ht_ptr,
InkHashTableEntry *entry_ptr)
This routine takes a hash table <ht_ptr> and a pointer to a hash table
entry <entry_ptr>, and returns the key portion of the entry.
*---------------------------------------------------------------------------*/
InkHashTableKey
ink_hash_table_entry_key(InkHashTable *ht_ptr, InkHashTableEntry *entry_ptr)
{
char *tcl_key;
tcl_key = (char *)Tcl_GetHashKey((Tcl_HashTable *)ht_ptr, (Tcl_HashEntry *)entry_ptr);
return ((InkHashTableKey)tcl_key);
} /* End ink_hash_table_entry_key */
/*---------------------------------------------------------------------------*
InkHashTableValue ink_hash_table_entry_value(InkHashTable *ht_ptr,
InkHashTableEntry *entry_ptr)
This routine takes a hash table <ht_ptr> and a pointer to a hash table
entry <entry_ptr>, and returns the value portion of the entry.
*---------------------------------------------------------------------------*/
InkHashTableValue
ink_hash_table_entry_value(InkHashTable *ht_ptr, InkHashTableEntry *entry_ptr)
{
(void)ht_ptr;
ClientData tcl_value;
tcl_value = Tcl_GetHashValue((Tcl_HashEntry *)entry_ptr);
return ((InkHashTableValue)tcl_value);
} /* End ink_hash_table_entry_value */
/*---------------------------------------------------------------------------*
void ink_hash_table_dump_strings(InkHashTable *ht_ptr)
This routine takes a hash table of string values, and dumps the keys and
string values to stdout. It is the caller's responsibility to ensure that
both the key and the value are NUL terminated strings.
*---------------------------------------------------------------------------*/
static int
DumpStringEntry(InkHashTable *ht_ptr, InkHashTableEntry *e)
{
InkHashTableKey key;
InkHashTableValue value;
key = ink_hash_table_entry_key(ht_ptr, e);
value = ink_hash_table_entry_value(ht_ptr, e);
fprintf(stderr, "key = '%s', value = '%s'\n", (char *)key, (char *)value);
return (0);
}
void
ink_hash_table_dump_strings(InkHashTable *ht_ptr)
{
ink_hash_table_map(ht_ptr, DumpStringEntry);
} /* End ink_hash_table_dump_strings */
/*---------------------------------------------------------------------------*
void ink_hash_table_replace_string(InkHashTable *ht_ptr,
char *string_key, char *string_value)
This conveninece routine is intended for hash tables with keys of type
InkHashTableKeyType_String, and values being dynamically allocated strings.
This routine binds <string_key> to a copy of <string_value>, and any
previous bound value is deallocated.
*---------------------------------------------------------------------------*/
void
ink_hash_table_replace_string(InkHashTable *ht_ptr, char *string_key, char *string_value)
{
int new_value;
char *old_str;
InkHashTableEntry *he_ptr;
/*
* The following line will flag a type-conversion warning on the
* DEC Alpha, but that message can be ignored, since we're
* still dealing with pointers, and we aren't loosing any bits.
*/
he_ptr = ink_hash_table_get_entry(ht_ptr, (InkHashTableKey)string_key, &new_value);
if (new_value == 0) {
old_str = (char *)ink_hash_table_entry_value(ht_ptr, he_ptr);
if (old_str)
ats_free(old_str);
}
ink_hash_table_set_entry(ht_ptr, he_ptr, (InkHashTableValue)(ats_strdup(string_value)));
} /* End ink_hash_table_replace_string */
| 14,146
| 4,435
|
#include "Collision.h"
namespace Collision
{
bool rectRectIntersect(Vec2 posBoxA, Vec2 dimBoxA, Vec2 posBoxB, Vec2 dimBoxB)
{
if (posBoxA.x <= (posBoxB.x + dimBoxB.x)
&& posBoxA.y <= (posBoxB.y + dimBoxB.y)
&& posBoxB.x <= (posBoxA.x + dimBoxA.x)
&& posBoxB.y <= (posBoxA.y + dimBoxA.y))
{
return true;
}
return false;
}
bool cubeCubeIntersect(Vec3 posBoxA, Vec3 dimBoxA, Vec3 posBoxB, Vec3 dimBoxB)
{
Vec3 collisionSides = Vec3(0.0f, 0.0f, 0.0f);
return cubeCubeIntersect(posBoxA, dimBoxA, posBoxB, dimBoxB, collisionSides);
}
bool cubeCubeIntersect(Vec3 posBoxA, Vec3 dimBoxA, Vec3 posBoxB, Vec3 dimBoxB, Vec3 &collisionSides)
{
//Half dimensions for center
Vec3 halfDimA = dimBoxA * 0.5f;
Vec3 halfDimB = dimBoxB * 0.5f;
//calculate max/min coords for box a
float minAX = posBoxA.x - halfDimA.x;
float maxAX = posBoxA.x + halfDimA.x;
float minAY = posBoxA.y - halfDimA.y;
float maxAY = posBoxA.y + halfDimA.y;
float minAZ = posBoxA.z - halfDimA.z;
float maxAZ = posBoxA.z + halfDimA.z;
//calculate max/min coords for box b
float minBX = posBoxB.x - halfDimB.x;
float maxBX = posBoxB.x + halfDimB.x;
float minBY = posBoxB.y - halfDimB.y;
float maxBY = posBoxB.y + halfDimB.y;
float minBZ = posBoxB.z - halfDimB.z;
float maxBZ = posBoxB.z + halfDimB.z;
bool collisionX = false;
bool collisionY = false;
bool collisionZ = false;
if (minAX < minBX)
{
if (maxAX >= minBX)
{
collisionX = true;
collisionSides.x = 1.0f;
}
}
else if (maxBX >= minAX)
{
collisionX = true;
collisionSides.x = -1.0f;
}
if (minAY < minBY)
{
if (maxAY >= minBY)
{
collisionY = true;
collisionSides.y = 1.0f;
}
}
else if (maxBY >= minAY)
{
collisionY = true;
collisionSides.y = -1.0f;
}
if (minAZ < minBZ)
{
if (maxAZ >= minBZ)
{
collisionZ = true;
collisionSides.z = 1.0f;
}
}
else if (maxBZ >= minAZ)
{
collisionZ = true;
collisionSides.z = -1.0f;
}
//check for intersection
return (collisionX && collisionY && collisionZ);
}
bool sphereCubeIntersect(Vec3 posBox, Vec3 dimBox, Vec3 posSphere, float radSphere)
{
Vec3 collisionSides = Vec3(0.0f, 0.0f, 0.0f);
return sphereCubeIntersect(posBox, dimBox, posSphere, radSphere, collisionSides);
}
bool sphereCubeIntersect(Vec3 posBox, Vec3 dimBox, Vec3 posSphere, float radSphere, Vec3 &collisionSides)
{
//Half dimensions for center
Vec3 halfDim = dimBox * 0.5f;
//calculate max/min coords for box a
float minBoxX = posBox.x - halfDim.x;
float maxBoxX = posBox.x + halfDim.x;
float minBoxY = posBox.y - halfDim.y;
float maxBoxY = posBox.y + halfDim.y;
float minBoxZ = posBox.z - halfDim.z;
float maxBoxZ = posBox.z + halfDim.z;
//calculate max/min coords for sphere
float minSphereX = posSphere.x - radSphere;
float maxSphereX = posSphere.x + radSphere;
float minSphereY = posSphere.y - radSphere;
float maxSphereY = posSphere.y + radSphere;
float minSphereZ = posSphere.z - radSphere;
float maxSphereZ = posSphere.z + radSphere;
bool collisionX = false;
bool collisionY = false;
bool collisionZ = false;
if (minBoxX < minSphereX)
{
if (maxBoxX >= minSphereX)
{
collisionX = true;
collisionSides.x = 1.0f;
}
}
else if (maxSphereX >= minBoxX)
{
collisionX = true;
collisionSides.x = -1.0f;
}
if (minBoxY < minSphereY)
{
if (maxBoxY >= minSphereY)
{
collisionY = true;
collisionSides.y = 1.0f;
}
}
else if (maxSphereY >= minBoxY)
{
collisionY = true;
collisionSides.y = -1.0f;
}
if (minBoxZ < minSphereZ)
{
if (maxBoxZ >= minSphereZ)
{
collisionZ = true;
collisionSides.z = 1.0f;
}
}
else if (maxSphereZ >= minBoxZ)
{
collisionZ = true;
collisionSides.z = -1.0f;
}
//check for intersection
return (collisionX && collisionY && collisionZ);
}
bool circleCircleIntersect(Vec2 circle1Pos, Vec2 circle2Pos, float circle1Rad, float circle2Rad)
{
// gets the combination of the 2 circles radius
float radSum = circle1Rad + circle2Rad;
//work out the distance between the circles
float distance = Mechanics::distanceBetweenTwoPoints(circle1Pos, circle2Pos);
//if the distance between the two circles is less than the sum of the radius's then there will be a collision
if (distance < radSum)
{
return true;
}
return false;
}
bool sphereSphereIntersect(Vec3 sphere1Pos, Vec3 sphere2Pos, float sphere1Rad, float sphere2Rad)
{
Vec3 vel1 = Vec3(0.0f, 0.0f, 0.0f);
Vec3 vel2 = Vec3(0.0f, 0.0f, 0.0f);
return sphereSphereIntersect(sphere1Pos, sphere2Pos, sphere1Rad, sphere2Rad, vel1, vel2);
}
bool sphereSphereIntersect(Vec3 sphere1Pos, Vec3 sphere2Pos, float sphere1Rad, float sphere2Rad, Vec3 &vel1, Vec3 &vel2)
{
// gets the combination of the 2 sphere's radius
float radSum = sphere1Rad + sphere2Rad;
//work out the distance between the spheres
float distance = Mechanics::distanceBetweenTwoPoints(sphere1Pos, sphere2Pos);
//if the distance between the two spheres is less than the sum of the radius's then there will be a collision
if (distance < radSum)
{
if (vel1.x != 0.0f)
{
vel1.x = 0.0f;
}
if (vel1.y != 0.0f && vel1.y != -9.81f)
{
vel1.y = 0.0f;
}
if (vel1.z != 0.0f)
{
vel1.z = 0.0f;
}
if (vel2.x != 0.0f)
{
vel2.x = 0.0f;
}
if (vel2.y != 0.0f && vel2.y != -9.81f)
{
vel2.y = 0.0f;
}
if (vel2.z != 0.0f)
{
vel2.z = 0.0f;
}
return true;
}
return false;
}
bool circleRectIntersect(Vec2 circlePos, Vec2 boxPos, float circleRad, Vec2 boxDim)
{
//check if the the circle is inside the box
if (circlePos.x + circleRad < boxPos.x + boxDim.x && circlePos.x + circleRad > boxPos.x - boxDim.x
&& circlePos.y + circleRad < boxPos.y + boxDim.y && circlePos.y + circleRad > boxPos.y - boxDim.y
|| circlePos.x - circleRad < boxPos.x + boxDim.x && circlePos.x - circleRad > boxPos.x - boxDim.x
&& circlePos.y - circleRad < boxPos.y + boxDim.y && circlePos.y - circleRad > boxPos.y - boxDim.y)
{
return true;
}
return false;
}
}
| 6,154
| 2,874
|
#pragma once
#include "types.hpp"
#include "reg/peripheral_operations.hpp"
#include "board/regmap/uart.hpp"
#include "reg/set.hpp"
#include "reg/write.hpp"
#include "reg/apply.hpp"
namespace drivers::uart
{
namespace detail
{
using board::uart::CR1::PsVal;
using board::uart::CR1::MVal;
using board::uart::CR2::StopVal;
template<MVal _dataBits, StopVal _stopBits, bool _parityOn, PsVal _parity = PsVal::EVEN>
struct FrameFormatDef
{
constexpr bool_<_parityOn> getParityEnabled() const { return {}; }
constexpr integral_constant<PsVal, _parity> getParity() const { return {}; }
constexpr integral_constant<MVal, _dataBits> getDataBits() const { return {}; }
constexpr integral_constant<StopVal, _stopBits> getStopBits() const { return {}; }
};
template<
class UartX,
std::uint32_t _peripheralClockFrequency,
std::uint32_t _baudRate,
MVal _dataBits,
StopVal _stopBits,
bool _parityOn,
PsVal _parity>
void initUart(
UartX uartX,
constant_<_peripheralClockFrequency> peripheralClockFrequency,
constant_<_baudRate> baudRate,
FrameFormatDef<_dataBits, _stopBits, _parityOn, _parity>)
{
uartX.enable();
reg::set(uartX, board::uart::CR1::UE);
// Configure baud rate generator
// baud rate = pClockFrequency / (16 * usartDivider)
// where usartDivider = div_Mantissa.(div_fraction/16)
auto dividerTimes16 =
(peripheralClockFrequency + uint32_c<_baudRate/2>) / baudRate;
auto mantissa = dividerTimes16 / uint32_c<16>;
auto fraction = (dividerTimes16 - uint32_c<16> * mantissa);
reg::apply(uartX,
reg::write(board::uart::BRR::DIV_Mantissa, mantissa),
reg::write(board::uart::BRR::DIV_Fraction, fraction));
reg::write(uartX, board::uart::CR2::STOP, constant_c<_stopBits>);
reg::apply(uartX,
reg::write(board::uart::CR1::PCE, bool_c<_parityOn>),
reg::write(board::uart::CR1::PS, constant_c<_parity>),
reg::write(board::uart::CR1::M, constant_c<_dataBits>),
reg::set (board::uart::CR1::TE));
}
}
}
| 2,423
| 818
|
#include <EnginePluginAssetsPCH.h>
#include <EnginePluginAssets/TextureCubeAsset/TextureCubeContext.h>
#include <EnginePluginAssets/TextureCubeAsset/TextureCubeView.h>
#include <EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h>
#include <GameEngine/GameApplication/GameApplication.h>
#include <RendererCore/Debug/DebugRenderer.h>
#include <RendererCore/Pipeline/View.h>
#include <RendererCore/RenderWorld/RenderWorld.h>
ezTextureCubeViewContext::ezTextureCubeViewContext(ezTextureCubeContext* pContext)
: ezEngineProcessViewContext(pContext)
{
m_pTextureContext = pContext;
}
ezTextureCubeViewContext::~ezTextureCubeViewContext() {}
ezViewHandle ezTextureCubeViewContext::CreateView()
{
ezView* pView = nullptr;
ezRenderWorld::CreateView("Texture Cube Editor - View", pView);
pView->SetRenderPipelineResource(CreateDebugRenderPipeline());
pView->SetRenderPassProperty("DepthPrePass", "Active", false);
pView->SetRenderPassProperty("AOPass", "Active", false);
ezEngineProcessDocumentContext* pDocumentContext = GetDocumentContext();
pView->SetWorld(pDocumentContext->GetWorld());
pView->SetCamera(&m_Camera);
return pView->GetHandle();
}
void ezTextureCubeViewContext::SetCamera(const ezViewRedrawMsgToEngine* pMsg)
{
// Do not apply render mode here otherwise we would switch to a different pipeline.
// Also use hard-coded clipping planes so the quad is not culled to early.
ezCameraMode::Enum cameraMode = (ezCameraMode::Enum)pMsg->m_iCameraMode;
m_Camera.SetCameraMode(cameraMode, pMsg->m_fFovOrDim, 0.0001f, 50.0f);
m_Camera.LookAt(pMsg->m_vPosition, pMsg->m_vPosition + pMsg->m_vDirForwards, pMsg->m_vDirUp);
// Draw some stats
auto hResource = m_pTextureContext->GetTexture();
if (hResource.IsValid())
{
ezResourceLock<ezTextureCubeResource> pResource(hResource, ezResourceAcquireMode::AllowLoadingFallback);
ezGALResourceFormat::Enum format = pResource->GetFormat();
ezUInt32 uiWidthAndHeight = pResource->GetWidthAndHeight();
const ezUInt32 viewHeight = pMsg->m_uiWindowHeight;
ezStringBuilder sText;
if (ezReflectionUtils::EnumerationToString(ezGetStaticRTTI<ezGALResourceFormat>(), format, sText))
{
sText.Shrink(21, 0);
}
else
{
sText = "Unknown format";
}
sText.PrependFormat("{0}x{1}x6 - ", uiWidthAndHeight, uiWidthAndHeight);
ezDebugRenderer::Draw2DText(m_hView, sText, ezVec2I32(10, viewHeight - 10), ezColor::White, 16, ezDebugRenderer::HorizontalAlignment::Left,
ezDebugRenderer::VerticalAlignment::Bottom);
}
}
| 2,574
| 847
|
// Time: O(n)
// Space: O(|V|+|E|) = O(26 + 26^2) = O(1)
// BFS solution.
class Solution {
public:
string alienOrder(vector<string>& words) {
unordered_set<char> nodes;
unordered_map<char, unordered_set<char>> in_degree, out_degree;
queue<char> zero_in_degree_queue;
for (const auto& word : words) {
for (const auto& c : word) {
nodes.emplace(c);
}
}
for (int i = 1; i < words.size(); ++i) {
findEdges(words[i - 1], words[i], &in_degree, &out_degree);
}
for (const auto& node : nodes) {
if (in_degree.find(node) == in_degree.end()) {
zero_in_degree_queue.emplace(node);
}
}
// BFS
string result;
while (!zero_in_degree_queue.empty()) {
const auto& precedence = zero_in_degree_queue.front();
zero_in_degree_queue.pop();
result.push_back(precedence);
if (out_degree.find(precedence) != out_degree.end()) {
for (const auto& c : out_degree[precedence]) {
in_degree[c].erase(precedence);
if (in_degree[c].empty()) {
zero_in_degree_queue.emplace(c);
}
}
out_degree.erase(precedence);
}
}
if (!out_degree.empty()) {
return "";
}
return result;
}
private:
// Construct the graph.
void findEdges(const string &word1, const string &word2,
unordered_map<char, unordered_set<char>> *in_degree,
unordered_map<char, unordered_set<char>> *out_degree) {
const int len = min(word1.length(), word2.length());
for (int i = 0; i < len; ++i) {
if (word1[i] != word2[i]) {
(*in_degree)[word2[i]].emplace(word1[i]);
(*out_degree)[word1[i]].emplace(word2[i]);
break;
}
}
}
};
// DFS solution.
class Solution2 {
public:
string alienOrder(vector<string>& words) {
// Find ancestors of each node by DFS.
unordered_set<char> nodes;
unordered_map<char, vector<char>> ancestors;
for (int i = 0; i < words.size(); ++i) {
for (const auto& c : words[i]) {
nodes.emplace(c);
}
if (i > 0) {
findEdges(words[i - 1], words[i], &ancestors);
}
}
// Output topological order by DFS.
string result;
unordered_map<char, char> visited;
for (const auto& node : nodes) {
if (topSortDFS(node, node, &ancestors, &visited, &result)) {
return "";
}
}
return result;
}
private:
// Construct the graph.
void findEdges(const string &word1, const string &word2,
unordered_map<char, vector<char>> *ancestors) {
const int len = min(word1.length(), word2.length());
for (int i = 0; i < len; ++i) {
if (word1[i] != word2[i]) {
(*ancestors)[word2[i]].emplace_back(word1[i]);
break;
}
}
}
// Topological sort, return whether there is a cycle.
bool topSortDFS(const char& root,
const char& node,
unordered_map<char, vector<char>> *ancestors,
unordered_map<char, char> *visited,
string *result) {
if (visited->emplace(make_pair(node, root)).second) {
for (auto& ancestor: (*ancestors)[node]) {
if (topSortDFS(root, ancestor, ancestors, visited, result)) {
return true;
}
}
result->push_back(node);
} else if ((*visited)[node] == root) {
// Visited from the same root in the DFS path.
// So it is cyclic.
return true;
}
return false;
}
};
// DFS with adjacency matrix solution.
class Solution3 {
public:
string alienOrder(vector<string>& words) {
string result;
vector<vector<bool>> graph(26, vector<bool>(26));
findDependency(words, &graph);
findOrder(&graph, &result);
return result;
}
private:
void findEdges(const string &word1, const string &word2, vector<vector<bool>> *graph) {
const int len = min(word1.length(), word2.length());
for (int i = 0; i < len; ++i) {
if (word1[i] != word2[i]) {
(*graph)[word1[i] - 'a'][word2[i] - 'a'] = true;
break;
}
}
}
// Construct the graph.
void findDependency(const vector<string>& words, vector<vector<bool>> *graph) {
for (const auto& c : words[0]) {
(*graph)[c - 'a'][c - 'a'] = true;
}
for (int i = 1; i < words.size(); ++i) {
for (const auto& c : words[i]) {
(*graph)[c - 'a'] [c - 'a'] = true;
}
findEdges(words[i - 1], words[i], graph);
}
}
// Topological sort, return whether there is a cycle.
bool topSortDFS(string *result, vector<bool> *visited,
vector<vector<bool>> *graph, const int root) {
if ((*visited)[root]) {
result->clear();
return true;
}
(*visited)[root] = true;
for (int i = 0; i < 26; ++i) {
if (i != root && (*graph)[root][i]) {
if (topSortDFS(result, visited, graph, i)) {
return true;
}
}
}
(*graph)[root][root] = false;
result->push_back(root + 'a');
return false;
}
void findOrder(vector<vector<bool>> *graph, string *result) {
for (int i = 0; i < 26; ++i) {
// Find a root node.
bool root_node = (*graph)[i][i];
if ((*graph)[i][i]) {
for (int j = 0; j < 26; ++j) {
if (j != i && (*graph)[j][i]) {
root_node = false;
break;
}
}
}
if (root_node) {
string reversed_order = "";
vector<bool> visited(26, false);
if (topSortDFS(&reversed_order, &visited, graph, i)) {
result->clear();
return;
} else {
result->append(reversed_order);
}
}
}
// If there is any unvisited node, return "".
for (int i = 0; i < 26; ++i) {
if ((*graph)[i][i]) {
result->clear();
return;
}
}
// The order should be reversed.
reverse(result->begin(), result->end());
}
};
| 6,955
| 2,153
|
#include <iostream>
#include <vector>
using namespace std;
class A {
static int count;
public:
// 在此处补充你的代码
A ()
{
count++;
}
static int theNumberOfA() {
return count;
}
};
int A::count = 0;
int main() {
vector<A> v;
for(int i = 0; i < 3; i++) {
{
A a;
v.push_back(a);
}
cout << A::theNumberOfA() << endl;
}
system("pause");
return 0;
}
| 450
| 179
|
/*
* Mark Benjamin 6th March 2019
* Copyright (c) 2019 Mark Benjamin
*/
#ifndef FASTRL_MDP_CORE_OO_STATE_EXCEPTIONS_UNKNOWN_OBJECT_EXCEPTION_HPP
#define FASTRL_MDP_CORE_OO_STATE_EXCEPTIONS_UNKNOWN_OBJECT_EXCEPTION_HPP
class UnknownObjectException {
};
#endif //FASTRL_MDP_CORE_OO_STATE_EXCEPTIONS_UNKNOWN_OBJECT_EXCEPTION_HPP
| 334
| 164
|
#include "tls.h"
using namespace std;
void tls_init()
{
sem_init(&mutex_sem, 0, 1);
sem_wait(&mutex_sem);
PAGESIZE = getpagesize();
sem_post(&mutex_sem);
struct sigaction sigact;
sigemptyset(&sigact.sa_mask);
/* SA_SIGINFO will help to distinguish between page fault and normal SegFault */
sigact.sa_flags = SA_SIGINFO;
sigact.sa_sigaction = tls_handle_page_fault;
sigaction(SIGBUS, &sigact, NULL);
sigaction(SIGSEGV, &sigact, NULL);
sem_wait(&mutex_sem);
Initialized = 1;
sem_post(&mutex_sem);
}
void tls_handle_page_fault(int sig, siginfo_t *si, void *context)
{
sem_wait(&mutex_sem);
unsigned long p_fault = ((unsigned long)si->si_addr) & ~(PAGESIZE - 1);
sem_post(&mutex_sem);
sem_wait(&mutex_sem);
/* Check whether it is a "real" segfault or because a thread has touched forbidden memory */
/* Make a brute force scan through all allocated TLS regions and pages in each TLS */
for (auto const &tlsblock : TLSPOOL)
{
for (int j = 0; j < tlsblock.page_num; j++)
{
if (tlsblock.pages[j]->address == p_fault)
{
sem_post(&mutex_sem);
tls_destroy();
pthread_exit(NULL);
}
}
}
/* If not page fault, set up a normal Seg Fault */
signal(SIGSEGV, SIG_DFL);
signal(SIGBUS, SIG_DFL);
raise(sig);
sem_post(&mutex_sem);
}
int tls_create(unsigned int size)
{
pthread_t tid = pthread_self();
/* Initialize the TLS Pool */
if (!Initialized)
{
tls_init();
}
/* Check for errors */
/* The size has to be larger than 0 */
if (size <= 0)
{
return -1;
}
sem_wait(&mutex_sem);
/* Error to create a local storage for a thread that already has one */
auto iter = hash_table.find(tid);
if (iter != hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
sem_post(&mutex_sem);
sem_wait(&mutex_sem);
/* Allocate TLS */
struct TLSBLOCK tls;
tls.tid = tid;
tls.size = size;
tls.page_num = (size - 1) / PAGESIZE + 1;
tls.pages = (struct page **)calloc(tls.page_num, sizeof(struct page));
/* Allocate all pages for this TLS */
for (int i = 0; i < tls.page_num; i++)
{
struct page *p;
p = (struct page *)calloc(1, sizeof(struct page));
p->address = (unsigned long)mmap(NULL, PAGESIZE, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
p->ref_count = 1;
tls.pages[i] = p;
}
sem_post(&mutex_sem);
sem_wait(&mutex_sem);
/* Add this TLS to the TLSPOOL */
TLSPOOL.push_back(tls);
/* Add the threadID and TLSPOOL Index mapping to hash_table */
hash_table[tid] = TLSPOOL.size() - 1;
sem_post(&mutex_sem);
return 0;
}
int tls_write(unsigned int offset, unsigned int length, char *buffer)
{
pthread_t tid = pthread_self();
sem_wait(&mutex_sem);
/* Check if the current thread already has local storage */
auto iter = hash_table.find(tid);
if (iter == hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
auto tls_iter = next(TLSPOOL.begin(), iter->second);
sem_post(&mutex_sem);
/* Check if offset + length > size */
if (offset + length > tls_iter->size)
{
return -1;
}
sem_wait(&mutex_sem);
/* Unprotect all pages belong to the thread's TLS */
for (int i = 0; i < tls_iter->page_num; i++)
{
mprotect((void *)tls_iter->pages[i]->address, PAGESIZE, PROT_READ | PROT_WRITE);
}
/* Perform the write operation */
for (int i = 0, index = offset; index < (offset + length); i++, index++)
{
struct page *p;
unsigned int page_num, page_offset;
page_num = index / PAGESIZE;
page_offset = index % PAGESIZE;
p = tls_iter->pages[page_num];
/* If this page is shared */
if (p->ref_count > 1)
{
struct page *copy;
/* Copy on write */
copy = (struct page *)calloc(1, sizeof(struct page));
copy->address = (unsigned long)mmap(NULL, PAGESIZE, PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
copy->ref_count = 1;
/* Copy the entire page content */
memcpy((void *)copy->address, (void *)p->address, PAGESIZE);
tls_iter->pages[page_num] = copy;
/* Update original page */
p->ref_count--;
mprotect((void *)p->address, PAGESIZE, 0);
p = copy;
}
/* Copy single char from buffer for page address with page offset */
char *dst = ((char *)p->address) + page_offset;
*dst = buffer[i];
}
/* Reprotect all pages belong to thread's TLS */
for (int i = 0; i < tls_iter->page_num; i++)
{
mprotect((void *)tls_iter->pages[i]->address, PAGESIZE, 0);
}
sem_post(&mutex_sem);
return 0;
}
int tls_read(unsigned int offset, unsigned int length, char *buffer)
{
pthread_t tid = pthread_self();
sem_wait(&mutex_sem);
/* Check if the current thread already has local storage */
auto iter = hash_table.find(tid);
if (iter == hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
auto tls_iter = next(TLSPOOL.begin(), iter->second);
sem_post(&mutex_sem);
/* Check if offset + length > size */
if (offset + length > tls_iter->size)
{
return -1;
}
sem_wait(&mutex_sem);
/* Unprotect all pages belong to thread's TLS */
for (int i = 0; i < tls_iter->page_num; i++)
{
mprotect((void *)tls_iter->pages[i]->address, PAGESIZE, PROT_READ | PROT_WRITE);
}
/* Perform the read operation */
for (int i = 0, index = offset; index < (offset + length); i++, index++)
{
struct page *p;
unsigned int page_num, page_offset;
page_num = index / PAGESIZE;
page_offset = index % PAGESIZE;
p = tls_iter->pages[page_num];
char *src = ((char *)p->address) + page_offset;
buffer[i] = *src;
}
/* Reprotect all pages belong to thread's TLS */
for (int i = 0; i < tls_iter->page_num; i++)
{
mprotect((void *)tls_iter->pages[i]->address, PAGESIZE, 0);
}
sem_post(&mutex_sem);
return 0;
}
int tls_destroy()
{
pthread_t tid = pthread_self();
sem_wait(&mutex_sem);
/* Check if the current thread has local storage for destroying */
auto iter = hash_table.find(tid);
if (iter == hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
auto tls_iter = next(TLSPOOL.begin(), iter->second);
sem_post(&mutex_sem);
sem_wait(&mutex_sem);
/* Clean up all pages */
for (int i = 0; i < tls_iter->page_num; i++)
{
/* If the page is not shared by other threads */
if (tls_iter->pages[i]->ref_count == 1)
{
munmap((void *)tls_iter->pages[i]->address, PAGESIZE);
free(tls_iter->pages[i]);
}
/* If the page is shared by other threads */
else
{
/* Decrement the reference counter by one */
tls_iter->pages[i]->ref_count--;
}
}
sem_post(&mutex_sem);
sem_wait(&mutex_sem);
/* Update the index in the hash_table for elements after tls_iter in the list */
for_each(next(TLSPOOL.begin(), iter->second + 1), TLSPOOL.end(), [](TLSBLOCK tls) { hash_table[tls.tid]--; });
/* Clean up TLS */
free(tls_iter->pages);
TLSPOOL.erase(tls_iter);
/* Remove the mapping from hash_table */
hash_table.erase(iter);
sem_post(&mutex_sem);
return 0;
}
int tls_clone(pthread_t tid)
{
pthread_t tid_self = pthread_self();
sem_wait(&mutex_sem);
/* Check if the current thread has local storage */
auto iter = hash_table.find(tid_self);
if (iter != hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
/* Check if the target thread has local storage */
iter = hash_table.find(tid);
if (iter == hash_table.end())
{
sem_post(&mutex_sem);
return -1;
}
auto tls_iter = next(TLSPOOL.begin(), iter->second);
sem_post(&mutex_sem);
/* Allocate TLS */
struct TLSBLOCK tls;
tls.tid = tid_self;
tls.size = tls_iter->size;
tls.page_num = tls_iter->page_num;
tls.pages = (struct page **)calloc(tls.page_num, sizeof(struct page));
/* Allocate all pages for this TLS */
for (int i = 0; i < tls.page_num; i++)
{
tls.pages[i] = tls_iter->pages[i];
tls.pages[i]->ref_count++;
}
sem_wait(&mutex_sem);
/* Add this TLS to the TLSPOOL */
TLSPOOL.push_back(tls);
/* Add the threadID and TLSPOOL Index mapping to the hash_table */
hash_table[tid_self] = TLSPOOL.size() - 1;
sem_post(&mutex_sem);
return 0;
}
void *tls_get_internal_start_address()
{
pthread_t tid_self = pthread_self();
sem_wait(&mutex_sem);
/* Check if the current thread has local storage */
auto iter = hash_table.find(tid_self);
if (iter == hash_table.end())
{
sem_post(&mutex_sem);
/* If the current thread did not allocate any local storage area, the function should return NULL */
return NULL;
}
sem_post(&mutex_sem);
/* Returns a pointer to the starting address of the local storage area for the current thread */
return (void *)next(TLSPOOL.begin(), iter->second)->pages[0]->address;
}
| 9,536
| 3,370
|
// 210-Evt-EventListeners.cpp
// Contents:
// 1. Printing of listener data
// 2. My listener and registration
// 3. Test cases
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <catch2/catch_test_case_info.hpp>
#include <iostream>
// -----------------------------------------------------------------------
// 1. Printing of listener data:
//
namespace {
std::string ws(int const level) {
return std::string( 2 * level, ' ' );
}
std::ostream& operator<<(std::ostream& out, Catch::Tag t) {
return out << "original: " << t.original << "lower cased: " << t.lowerCased;
}
template< typename T >
std::ostream& operator<<( std::ostream& os, std::vector<T> const& v ) {
os << "{ ";
for ( const auto& x : v )
os << x << ", ";
return os << "}";
}
// struct SourceLineInfo {
// char const* file;
// std::size_t line;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::SourceLineInfo const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- file: " << info.file << "\n"
<< ws(level+1) << "- line: " << info.line << "\n";
}
//struct MessageInfo {
// std::string macroName;
// std::string message;
// SourceLineInfo lineInfo;
// ResultWas::OfType type;
// unsigned int sequence;
//};
void print( std::ostream& os, int const level, Catch::MessageInfo const& info ) {
os << ws(level+1) << "- macroName: '" << info.macroName << "'\n"
<< ws(level+1) << "- message '" << info.message << "'\n";
print( os,level+1 , "- lineInfo", info.lineInfo );
os << ws(level+1) << "- sequence " << info.sequence << "\n";
}
void print( std::ostream& os, int const level, std::string const& title, std::vector<Catch::MessageInfo> const& v ) {
os << ws(level ) << title << ":\n";
for ( const auto& x : v )
{
os << ws(level+1) << "{\n";
print( os, level+2, x );
os << ws(level+1) << "}\n";
}
// os << ws(level+1) << "\n";
}
// struct TestRunInfo {
// std::string name;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::TestRunInfo const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- name: " << info.name << "\n";
}
// struct Counts {
// std::size_t total() const;
// bool allPassed() const;
// bool allOk() const;
//
// std::size_t passed = 0;
// std::size_t failed = 0;
// std::size_t failedButOk = 0;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::Counts const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- total(): " << info.total() << "\n"
<< ws(level+1) << "- allPassed(): " << info.allPassed() << "\n"
<< ws(level+1) << "- allOk(): " << info.allOk() << "\n"
<< ws(level+1) << "- passed: " << info.passed << "\n"
<< ws(level+1) << "- failed: " << info.failed << "\n"
<< ws(level+1) << "- failedButOk: " << info.failedButOk << "\n";
}
// struct Totals {
// Counts assertions;
// Counts testCases;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::Totals const& info ) {
os << ws(level) << title << ":\n";
print( os, level+1, "- assertions", info.assertions );
print( os, level+1, "- testCases" , info.testCases );
}
// struct TestRunStats {
// TestRunInfo runInfo;
// Totals totals;
// bool aborting;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::TestRunStats const& info ) {
os << ws(level) << title << ":\n";
print( os, level+1 , "- runInfo", info.runInfo );
print( os, level+1 , "- totals" , info.totals );
os << ws(level+1) << "- aborting: " << info.aborting << "\n";
}
// struct Tag {
// StringRef original, lowerCased;
// };
//
//
// enum class TestCaseProperties : uint8_t {
// None = 0,
// IsHidden = 1 << 1,
// ShouldFail = 1 << 2,
// MayFail = 1 << 3,
// Throws = 1 << 4,
// NonPortable = 1 << 5,
// Benchmark = 1 << 6
// };
//
//
// struct TestCaseInfo : NonCopyable {
//
// bool isHidden() const;
// bool throws() const;
// bool okToFail() const;
// bool expectedToFail() const;
//
//
// std::string name;
// std::string className;
// std::vector<Tag> tags;
// SourceLineInfo lineInfo;
// TestCaseProperties properties = TestCaseProperties::None;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::TestCaseInfo const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- isHidden(): " << info.isHidden() << "\n"
<< ws(level+1) << "- throws(): " << info.throws() << "\n"
<< ws(level+1) << "- okToFail(): " << info.okToFail() << "\n"
<< ws(level+1) << "- expectedToFail(): " << info.expectedToFail() << "\n"
<< ws(level+1) << "- tagsAsString(): '" << info.tagsAsString() << "'\n"
<< ws(level+1) << "- name: '" << info.name << "'\n"
<< ws(level+1) << "- className: '" << info.className << "'\n"
<< ws(level+1) << "- tags: " << info.tags << "\n";
print( os, level+1 , "- lineInfo", info.lineInfo );
os << ws(level+1) << "- properties (flags): 0x" << std::hex << static_cast<uint32_t>(info.properties) << std::dec << "\n";
}
// struct TestCaseStats {
// TestCaseInfo testInfo;
// Totals totals;
// std::string stdOut;
// std::string stdErr;
// bool aborting;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::TestCaseStats const& info ) {
os << ws(level ) << title << ":\n";
print( os, level+1 , "- testInfo", *info.testInfo );
print( os, level+1 , "- totals" , info.totals );
os << ws(level+1) << "- stdOut: " << info.stdOut << "\n"
<< ws(level+1) << "- stdErr: " << info.stdErr << "\n"
<< ws(level+1) << "- aborting: " << info.aborting << "\n";
}
// struct SectionInfo {
// std::string name;
// std::string description;
// SourceLineInfo lineInfo;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::SectionInfo const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- name: " << info.name << "\n";
print( os, level+1 , "- lineInfo", info.lineInfo );
}
// struct SectionStats {
// SectionInfo sectionInfo;
// Counts assertions;
// double durationInSeconds;
// bool missingAssertions;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::SectionStats const& info ) {
os << ws(level ) << title << ":\n";
print( os, level+1 , "- sectionInfo", info.sectionInfo );
print( os, level+1 , "- assertions" , info.assertions );
os << ws(level+1) << "- durationInSeconds: " << info.durationInSeconds << "\n"
<< ws(level+1) << "- missingAssertions: " << info.missingAssertions << "\n";
}
// struct AssertionInfo
// {
// StringRef macroName;
// SourceLineInfo lineInfo;
// StringRef capturedExpression;
// ResultDisposition::Flags resultDisposition;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionInfo const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- macroName: '" << info.macroName << "'\n";
print( os, level+1 , "- lineInfo" , info.lineInfo );
os << ws(level+1) << "- capturedExpression: '" << info.capturedExpression << "'\n"
<< ws(level+1) << "- resultDisposition (flags): 0x" << std::hex << info.resultDisposition << std::dec << "\n";
}
//struct AssertionResultData
//{
// std::string reconstructExpression() const;
//
// std::string message;
// mutable std::string reconstructedExpression;
// LazyExpression lazyExpression;
// ResultWas::OfType resultType;
//};
void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionResultData const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- reconstructExpression(): '" << info.reconstructExpression() << "'\n"
<< ws(level+1) << "- message: '" << info.message << "'\n"
<< ws(level+1) << "- lazyExpression: '" << "(info.lazyExpression)" << "'\n"
<< ws(level+1) << "- resultType: '" << info.resultType << "'\n";
}
//class AssertionResult {
// bool isOk() const;
// bool succeeded() const;
// ResultWas::OfType getResultType() const;
// bool hasExpression() const;
// bool hasMessage() const;
// std::string getExpression() const;
// std::string getExpressionInMacro() const;
// bool hasExpandedExpression() const;
// std::string getExpandedExpression() const;
// std::string getMessage() const;
// SourceLineInfo getSourceInfo() const;
// std::string getTestMacroName() const;
//
// AssertionInfo m_info;
// AssertionResultData m_resultData;
//};
void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionResult const& info ) {
os << ws(level ) << title << ":\n"
<< ws(level+1) << "- isOk(): " << info.isOk() << "\n"
<< ws(level+1) << "- succeeded(): " << info.succeeded() << "\n"
<< ws(level+1) << "- getResultType(): " << info.getResultType() << "\n"
<< ws(level+1) << "- hasExpression(): " << info.hasExpression() << "\n"
<< ws(level+1) << "- hasMessage(): " << info.hasMessage() << "\n"
<< ws(level+1) << "- getExpression(): '" << info.getExpression() << "'\n"
<< ws(level+1) << "- getExpressionInMacro(): '" << info.getExpressionInMacro() << "'\n"
<< ws(level+1) << "- hasExpandedExpression(): " << info.hasExpandedExpression() << "\n"
<< ws(level+1) << "- getExpandedExpression(): " << info.getExpandedExpression() << "'\n"
<< ws(level+1) << "- getMessage(): '" << info.getMessage() << "'\n";
print( os, level+1 , "- getSourceInfo(): ", info.getSourceInfo() );
os << ws(level+1) << "- getTestMacroName(): '" << info.getTestMacroName() << "'\n";
print( os, level+1 , "- *** m_info (AssertionInfo)", info.m_info );
print( os, level+1 , "- *** m_resultData (AssertionResultData)", info.m_resultData );
}
// struct AssertionStats {
// AssertionResult assertionResult;
// std::vector<MessageInfo> infoMessages;
// Totals totals;
// };
void print( std::ostream& os, int const level, std::string const& title, Catch::AssertionStats const& info ) {
os << ws(level ) << title << ":\n";
print( os, level+1 , "- assertionResult", info.assertionResult );
print( os, level+1 , "- infoMessages", info.infoMessages );
print( os, level+1 , "- totals", info.totals );
}
// -----------------------------------------------------------------------
// 2. My listener and registration:
//
char const * dashed_line =
"--------------------------------------------------------------------------";
struct MyListener : Catch::EventListenerBase {
using EventListenerBase::EventListenerBase; // inherit constructor
// Get rid of Wweak-tables
~MyListener();
// The whole test run starting
void testRunStarting( Catch::TestRunInfo const& testRunInfo ) override {
std::cout
<< std::boolalpha
<< "\nEvent: testRunStarting:\n";
print( std::cout, 1, "- testRunInfo", testRunInfo );
}
// The whole test run ending
void testRunEnded( Catch::TestRunStats const& testRunStats ) override {
std::cout
<< dashed_line
<< "\nEvent: testRunEnded:\n";
print( std::cout, 1, "- testRunStats", testRunStats );
}
// A test is being skipped (because it is "hidden")
void skipTest( Catch::TestCaseInfo const& testInfo ) override {
std::cout
<< dashed_line
<< "\nEvent: skipTest:\n";
print( std::cout, 1, "- testInfo", testInfo );
}
// Test cases starting
void testCaseStarting( Catch::TestCaseInfo const& testInfo ) override {
std::cout
<< dashed_line
<< "\nEvent: testCaseStarting:\n";
print( std::cout, 1, "- testInfo", testInfo );
}
// Test cases ending
void testCaseEnded( Catch::TestCaseStats const& testCaseStats ) override {
std::cout << "\nEvent: testCaseEnded:\n";
print( std::cout, 1, "testCaseStats", testCaseStats );
}
// Sections starting
void sectionStarting( Catch::SectionInfo const& sectionInfo ) override {
std::cout << "\nEvent: sectionStarting:\n";
print( std::cout, 1, "- sectionInfo", sectionInfo );
}
// Sections ending
void sectionEnded( Catch::SectionStats const& sectionStats ) override {
std::cout << "\nEvent: sectionEnded:\n";
print( std::cout, 1, "- sectionStats", sectionStats );
}
// Assertions before/ after
void assertionStarting( Catch::AssertionInfo const& assertionInfo ) override {
std::cout << "\nEvent: assertionStarting:\n";
print( std::cout, 1, "- assertionInfo", assertionInfo );
}
void assertionEnded( Catch::AssertionStats const& assertionStats ) override {
std::cout << "\nEvent: assertionEnded:\n";
print( std::cout, 1, "- assertionStats", assertionStats );
}
};
} // end anonymous namespace
CATCH_REGISTER_LISTENER( MyListener )
// Get rid of Wweak-tables
MyListener::~MyListener() {}
// -----------------------------------------------------------------------
// 3. Test cases:
//
TEST_CASE( "1: Hidden testcase", "[.hidden]" ) {
}
TEST_CASE( "2: Testcase with sections", "[tag-A][tag-B]" ) {
int i = 42;
REQUIRE( i == 42 );
SECTION("Section 1") {
INFO("Section 1");
i = 7;
SECTION("Section 1.1") {
INFO("Section 1.1");
REQUIRE( i == 42 );
}
}
SECTION("Section 2") {
INFO("Section 2");
REQUIRE( i == 42 );
}
WARN("At end of test case");
}
struct Fixture {
int fortytwo() const {
return 42;
}
};
TEST_CASE_METHOD( Fixture, "3: Testcase with class-based fixture", "[tag-C][tag-D]" ) {
REQUIRE( fortytwo() == 42 );
}
// Compile & run:
// - g++ -std=c++11 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 210-Evt-EventListeners 210-Evt-EventListeners.cpp 000-CatchMain.o && 210-Evt-EventListeners --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 210-Evt-EventListeners.cpp 000-CatchMain.obj && 210-Evt-EventListeners --success
// Expected compact output (all assertions):
//
// prompt> 210-Evt-EventListeners --reporter compact --success
// result omitted for brevity.
| 14,900
| 4,930
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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 holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
////////////////////////////////////////////////////////////////////////////////
#include "ClusterBlocks.h"
#include "Aql/AqlItemBlock.h"
#include "Aql/AqlValue.h"
#include "Aql/BlockCollector.h"
#include "Aql/Collection.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/ExecutionStats.h"
#include "Aql/Query.h"
#include "Basics/Exceptions.h"
#include "Basics/StaticStrings.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VelocyPackHelper.h"
#include "Cluster/ClusterComm.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/ClusterMethods.h"
#include "Cluster/ServerState.h"
#include "Scheduler/JobGuard.h"
#include "Scheduler/SchedulerFeature.h"
#include "VocBase/ticks.h"
#include "VocBase/vocbase.h"
#include <velocypack/Builder.h>
#include <velocypack/Collection.h>
#include <velocypack/Parser.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::aql;
using VelocyPackHelper = arangodb::basics::VelocyPackHelper;
using StringBuffer = arangodb::basics::StringBuffer;
GatherBlock::GatherBlock(ExecutionEngine* engine, GatherNode const* en)
: ExecutionBlock(engine, en),
_sortRegisters(),
_isSimple(en->getElements().empty()) {
if (!_isSimple) {
for (auto const& p : en->getElements()) {
// We know that planRegisters has been run, so
// getPlanNode()->_registerPlan is set up
auto it = en->getRegisterPlan()->varInfo.find(p.var->id);
TRI_ASSERT(it != en->getRegisterPlan()->varInfo.end());
TRI_ASSERT(it->second.registerId < ExecutionNode::MaxRegisterId);
_sortRegisters.emplace_back(it->second.registerId, p.ascending);
if (!p.attributePath.empty()) {
_sortRegisters.back().attributePath = p.attributePath;
}
}
}
}
GatherBlock::~GatherBlock() {
DEBUG_BEGIN_BLOCK();
for (std::deque<AqlItemBlock*>& x : _gatherBlockBuffer) {
for (AqlItemBlock* y : x) {
delete y;
}
x.clear();
}
_gatherBlockBuffer.clear();
DEBUG_END_BLOCK();
}
/// @brief initialize
int GatherBlock::initialize() {
DEBUG_BEGIN_BLOCK();
_atDep = 0;
return ExecutionBlock::initialize();
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief shutdown: need our own method since our _buffer is different
int GatherBlock::shutdown(int errorCode) {
DEBUG_BEGIN_BLOCK();
// don't call default shutdown method since it does the wrong thing to
// _gatherBlockBuffer
int ret = TRI_ERROR_NO_ERROR;
for (auto it = _dependencies.begin(); it != _dependencies.end(); ++it) {
int res = (*it)->shutdown(errorCode);
if (res != TRI_ERROR_NO_ERROR) {
ret = res;
}
}
if (ret != TRI_ERROR_NO_ERROR) {
return ret;
}
if (!_isSimple) {
for (std::deque<AqlItemBlock*>& x : _gatherBlockBuffer) {
for (AqlItemBlock* y : x) {
delete y;
}
x.clear();
}
_gatherBlockBuffer.clear();
_gatherBlockPos.clear();
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief initializeCursor
int GatherBlock::initializeCursor(AqlItemBlock* items, size_t pos) {
DEBUG_BEGIN_BLOCK();
int res = ExecutionBlock::initializeCursor(items, pos);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
_atDep = 0;
if (!_isSimple) {
for (std::deque<AqlItemBlock*>& x : _gatherBlockBuffer) {
for (AqlItemBlock* y : x) {
delete y;
}
x.clear();
}
_gatherBlockBuffer.clear();
_gatherBlockPos.clear();
_gatherBlockBuffer.reserve(_dependencies.size());
_gatherBlockPos.reserve(_dependencies.size());
for (size_t i = 0; i < _dependencies.size(); i++) {
_gatherBlockBuffer.emplace_back();
_gatherBlockPos.emplace_back(std::make_pair(i, 0));
}
}
if (_dependencies.empty()) {
_done = true;
} else {
_done = false;
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief count: the sum of the count() of the dependencies or -1 (if any
/// dependency has count -1
int64_t GatherBlock::count() const {
DEBUG_BEGIN_BLOCK();
int64_t sum = 0;
for (auto const& x : _dependencies) {
if (x->count() == -1) {
return -1;
}
sum += x->count();
}
return sum;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief remaining: the sum of the remaining() of the dependencies or -1 (if
/// any dependency has remaining -1
int64_t GatherBlock::remaining() {
DEBUG_BEGIN_BLOCK();
int64_t sum = 0;
for (auto const& x : _dependencies) {
if (x->remaining() == -1) {
return -1;
}
sum += x->remaining();
}
return sum;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief hasMore: true if any position of _buffer hasMore and false
/// otherwise.
bool GatherBlock::hasMore() {
DEBUG_BEGIN_BLOCK();
if (_done || _dependencies.empty()) {
return false;
}
if (_isSimple) {
for (size_t i = 0; i < _dependencies.size(); i++) {
if (_dependencies.at(i)->hasMore()) {
return true;
}
}
} else {
for (size_t i = 0; i < _gatherBlockBuffer.size(); i++) {
if (!_gatherBlockBuffer.at(i).empty()) {
return true;
} else if (getBlock(i, DefaultBatchSize(), DefaultBatchSize())) {
_gatherBlockPos.at(i) = std::make_pair(i, 0);
return true;
}
}
}
_done = true;
return false;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getSome
AqlItemBlock* GatherBlock::getSome(size_t atLeast, size_t atMost) {
DEBUG_BEGIN_BLOCK();
traceGetSomeBegin();
if (_dependencies.empty()) {
_done = true;
}
if (_done) {
traceGetSomeEnd(nullptr);
return nullptr;
}
// the simple case . . .
if (_isSimple) {
auto res = _dependencies.at(_atDep)->getSome(atLeast, atMost);
while (res == nullptr && _atDep < _dependencies.size() - 1) {
_atDep++;
res = _dependencies.at(_atDep)->getSome(atLeast, atMost);
}
if (res == nullptr) {
_done = true;
}
traceGetSomeEnd(res);
return res;
}
// the non-simple case . . .
size_t available = 0; // nr of available rows
size_t index = 0; // an index of a non-empty buffer
// pull more blocks from dependencies . . .
TRI_ASSERT(_gatherBlockBuffer.size() == _dependencies.size());
TRI_ASSERT(_gatherBlockBuffer.size() == _gatherBlockPos.size());
for (size_t i = 0; i < _dependencies.size(); i++) {
if (_gatherBlockBuffer.at(i).empty()) {
if (getBlock(i, atLeast, atMost)) {
index = i;
_gatherBlockPos.at(i) = std::make_pair(i, 0);
}
} else {
index = i;
}
auto const& cur = _gatherBlockBuffer.at(i);
if (!cur.empty()) {
available += cur.at(0)->size() - _gatherBlockPos.at(i).second;
for (size_t j = 1; j < cur.size(); j++) {
available += cur.at(j)->size();
}
}
}
if (available == 0) {
_done = true;
traceGetSomeEnd(nullptr);
return nullptr;
}
size_t toSend = (std::min)(available, atMost); // nr rows in outgoing block
// the following is similar to AqlItemBlock's slice method . . .
std::unordered_map<AqlValue, AqlValue> cache;
// comparison function
OurLessThan ourLessThan(_trx, _gatherBlockBuffer, _sortRegisters);
AqlItemBlock* example = _gatherBlockBuffer.at(index).front();
size_t nrRegs = example->getNrRegs();
// automatically deleted if things go wrong
std::unique_ptr<AqlItemBlock> res(requestBlock(toSend, static_cast<arangodb::aql::RegisterId>(nrRegs)));
for (size_t i = 0; i < toSend; i++) {
// get the next smallest row from the buffer . . .
std::pair<size_t, size_t> val = *(std::min_element(
_gatherBlockPos.begin(), _gatherBlockPos.end(), ourLessThan));
// copy the row in to the outgoing block . . .
for (RegisterId col = 0; col < nrRegs; col++) {
AqlValue const& x(
_gatherBlockBuffer.at(val.first).front()->getValue(val.second, col));
if (!x.isEmpty()) {
auto it = cache.find(x);
if (it == cache.end()) {
AqlValue y = x.clone();
try {
res->setValue(i, col, y);
} catch (...) {
y.destroy();
throw;
}
cache.emplace(x, y);
} else {
res->setValue(i, col, it->second);
}
}
}
// renew the _gatherBlockPos and clean up the buffer if necessary
_gatherBlockPos.at(val.first).second++;
if (_gatherBlockPos.at(val.first).second ==
_gatherBlockBuffer.at(val.first).front()->size()) {
AqlItemBlock* cur = _gatherBlockBuffer.at(val.first).front();
returnBlock(cur);
_gatherBlockBuffer.at(val.first).pop_front();
_gatherBlockPos.at(val.first) = std::make_pair(val.first, 0);
if (_gatherBlockBuffer.at(val.first).empty()) {
// if we pulled everything from the buffer, we need to fetch
// more data for the shard for which we have no more local
// values.
getBlock(val.first, atLeast, atMost);
// note that if getBlock() returns false here, this is not
// a problem, because the sort function used takes care of
// this
}
}
}
traceGetSomeEnd(res.get());
return res.release();
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief skipSome
size_t GatherBlock::skipSome(size_t atLeast, size_t atMost) {
DEBUG_BEGIN_BLOCK();
if (_done) {
return 0;
}
// the simple case . . .
if (_isSimple) {
auto skipped = _dependencies.at(_atDep)->skipSome(atLeast, atMost);
while (skipped == 0 && _atDep < _dependencies.size() - 1) {
_atDep++;
skipped = _dependencies.at(_atDep)->skipSome(atLeast, atMost);
}
if (skipped == 0) {
_done = true;
}
return skipped;
}
// the non-simple case . . .
size_t available = 0; // nr of available rows
TRI_ASSERT(_dependencies.size() != 0);
// pull more blocks from dependencies . . .
for (size_t i = 0; i < _dependencies.size(); i++) {
if (_gatherBlockBuffer.at(i).empty()) {
if (getBlock(i, atLeast, atMost)) {
_gatherBlockPos.at(i) = std::make_pair(i, 0);
}
}
auto cur = _gatherBlockBuffer.at(i);
if (!cur.empty()) {
available += cur.at(0)->size() - _gatherBlockPos.at(i).second;
for (size_t j = 1; j < cur.size(); j++) {
available += cur.at(j)->size();
}
}
}
if (available == 0) {
_done = true;
return 0;
}
size_t skipped = (std::min)(available, atMost); // nr rows in outgoing block
// comparison function
OurLessThan ourLessThan(_trx, _gatherBlockBuffer, _sortRegisters);
for (size_t i = 0; i < skipped; i++) {
// get the next smallest row from the buffer . . .
std::pair<size_t, size_t> val = *(std::min_element(
_gatherBlockPos.begin(), _gatherBlockPos.end(), ourLessThan));
// renew the _gatherBlockPos and clean up the buffer if necessary
_gatherBlockPos.at(val.first).second++;
if (_gatherBlockPos.at(val.first).second ==
_gatherBlockBuffer.at(val.first).front()->size()) {
AqlItemBlock* cur = _gatherBlockBuffer.at(val.first).front();
returnBlock(cur);
_gatherBlockBuffer.at(val.first).pop_front();
_gatherBlockPos.at(val.first) = std::make_pair(val.first, 0);
}
}
return skipped;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getBlock: from dependency i into _gatherBlockBuffer.at(i),
/// non-simple case only
bool GatherBlock::getBlock(size_t i, size_t atLeast, size_t atMost) {
DEBUG_BEGIN_BLOCK();
TRI_ASSERT(i < _dependencies.size());
TRI_ASSERT(!_isSimple);
std::unique_ptr<AqlItemBlock> docs(_dependencies.at(i)->getSome(atLeast, atMost));
if (docs != nullptr) {
_gatherBlockBuffer.at(i).emplace_back(docs.get());
docs.release();
return true;
}
return false;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief OurLessThan: comparison method for elements of _gatherBlockPos
bool GatherBlock::OurLessThan::operator()(std::pair<size_t, size_t> const& a,
std::pair<size_t, size_t> const& b) {
// nothing in the buffer is maximum!
if (_gatherBlockBuffer[a.first].empty()) {
return false;
}
if (_gatherBlockBuffer[b.first].empty()) {
return true;
}
size_t i = 0;
for (auto const& reg : _sortRegisters) {
// Fast path if there is no attributePath:
int cmp;
if (reg.attributePath.empty()) {
cmp = AqlValue::Compare(
_trx,
_gatherBlockBuffer[a.first].front()->getValue(a.second, reg.reg),
_gatherBlockBuffer[b.first].front()->getValue(b.second, reg.reg),
true);
} else {
// Take attributePath into consideration:
AqlValue topA = _gatherBlockBuffer[a.first].front()->getValue(a.second,
reg.reg);
AqlValue topB = _gatherBlockBuffer[b.first].front()->getValue(b.second,
reg.reg);
bool mustDestroyA;
AqlValue aa = topA.get(_trx, reg.attributePath, mustDestroyA, false);
AqlValueGuard guardA(aa, mustDestroyA);
bool mustDestroyB;
AqlValue bb = topB.get(_trx, reg.attributePath, mustDestroyB, false);
AqlValueGuard guardB(bb, mustDestroyB);
cmp = AqlValue::Compare(_trx, aa, bb, true);
}
if (cmp == -1) {
return reg.ascending;
} else if (cmp == 1) {
return !reg.ascending;
}
i++;
}
return false;
}
BlockWithClients::BlockWithClients(ExecutionEngine* engine,
ExecutionNode const* ep,
std::vector<std::string> const& shardIds)
: ExecutionBlock(engine, ep), _nrClients(shardIds.size()), _wasShutdown(false) {
_shardIdMap.reserve(_nrClients);
for (size_t i = 0; i < _nrClients; i++) {
_shardIdMap.emplace(std::make_pair(shardIds[i], i));
}
}
/// @brief initializeCursor: reset _doneForClient
int BlockWithClients::initializeCursor(AqlItemBlock* items, size_t pos) {
DEBUG_BEGIN_BLOCK();
int res = ExecutionBlock::initializeCursor(items, pos);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
_doneForClient.clear();
_doneForClient.reserve(_nrClients);
for (size_t i = 0; i < _nrClients; i++) {
_doneForClient.push_back(false);
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief shutdown
int BlockWithClients::shutdown(int errorCode) {
DEBUG_BEGIN_BLOCK();
_doneForClient.clear();
if (_wasShutdown) {
return TRI_ERROR_NO_ERROR;
}
int res = ExecutionBlock::shutdown(errorCode);
_wasShutdown = true;
return res;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getSomeForShard
AqlItemBlock* BlockWithClients::getSomeForShard(size_t atLeast, size_t atMost,
std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
size_t skipped = 0;
AqlItemBlock* result = nullptr;
int out =
getOrSkipSomeForShard(atLeast, atMost, false, result, skipped, shardId);
if (out == TRI_ERROR_NO_ERROR) {
return result;
}
if (result != nullptr) {
delete result;
}
THROW_ARANGO_EXCEPTION(out);
DEBUG_END_BLOCK();
}
/// @brief skipSomeForShard
size_t BlockWithClients::skipSomeForShard(size_t atLeast, size_t atMost,
std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
size_t skipped = 0;
AqlItemBlock* result = nullptr;
int out =
getOrSkipSomeForShard(atLeast, atMost, true, result, skipped, shardId);
TRI_ASSERT(result == nullptr);
if (out != TRI_ERROR_NO_ERROR) {
THROW_ARANGO_EXCEPTION(out);
}
return skipped;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief skipForShard
bool BlockWithClients::skipForShard(size_t number, std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
size_t skipped = skipSomeForShard(number, number, shardId);
size_t nr = skipped;
while (nr != 0 && skipped < number) {
nr = skipSomeForShard(number - skipped, number - skipped, shardId);
skipped += nr;
}
if (nr == 0) {
return true;
}
return !hasMoreForShard(shardId);
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getClientId: get the number <clientId> (used internally)
/// corresponding to <shardId>
size_t BlockWithClients::getClientId(std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
if (shardId.empty()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "got empty shard id");
}
auto it = _shardIdMap.find(shardId);
if (it == _shardIdMap.end()) {
std::string message("AQL: unknown shard id ");
message.append(shardId);
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, message);
}
return ((*it).second);
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief initializeCursor
int ScatterBlock::initializeCursor(AqlItemBlock* items, size_t pos) {
DEBUG_BEGIN_BLOCK();
int res = BlockWithClients::initializeCursor(items, pos);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
// local clean up
_posForClient.clear();
for (size_t i = 0; i < _nrClients; i++) {
_posForClient.emplace_back(std::make_pair(0, 0));
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief initializeCursor
int ScatterBlock::shutdown(int errorCode) {
DEBUG_BEGIN_BLOCK();
int res = BlockWithClients::shutdown(errorCode);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
// local clean up
_posForClient.clear();
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief hasMoreForShard: any more for shard <shardId>?
bool ScatterBlock::hasMoreForShard(std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
TRI_ASSERT(_nrClients != 0);
size_t clientId = getClientId(shardId);
if (_doneForClient.at(clientId)) {
return false;
}
std::pair<size_t, size_t> pos = _posForClient.at(clientId);
// (i, j) where i is the position in _buffer, and j is the position in
// _buffer.at(i) we are sending to <clientId>
if (pos.first > _buffer.size()) {
if (!ExecutionBlock::getBlock(DefaultBatchSize(), DefaultBatchSize())) {
_doneForClient.at(clientId) = true;
return false;
}
}
return true;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief remainingForShard: remaining for shard, sum of the number of row left
/// in the buffer and _dependencies[0]->remaining()
int64_t ScatterBlock::remainingForShard(std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
size_t clientId = getClientId(shardId);
if (_doneForClient.at(clientId)) {
return 0;
}
int64_t sum = _dependencies[0]->remaining();
if (sum == -1) {
return -1;
}
std::pair<size_t, size_t> pos = _posForClient.at(clientId);
if (pos.first <= _buffer.size()) {
sum += _buffer.at(pos.first)->size() - pos.second;
for (auto i = pos.first + 1; i < _buffer.size(); i++) {
sum += _buffer.at(i)->size();
}
}
return sum;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getOrSkipSomeForShard
int ScatterBlock::getOrSkipSomeForShard(size_t atLeast, size_t atMost,
bool skipping, AqlItemBlock*& result,
size_t& skipped,
std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
TRI_ASSERT(0 < atLeast && atLeast <= atMost);
TRI_ASSERT(result == nullptr && skipped == 0);
size_t clientId = getClientId(shardId);
if (_doneForClient.at(clientId)) {
return TRI_ERROR_NO_ERROR;
}
std::pair<size_t, size_t> pos = _posForClient.at(clientId);
// pull more blocks from dependency if necessary . . .
if (pos.first >= _buffer.size()) {
if (!getBlock(atLeast, atMost)) {
_doneForClient.at(clientId) = true;
return TRI_ERROR_NO_ERROR;
}
}
size_t available = _buffer.at(pos.first)->size() - pos.second;
// available should be non-zero
skipped = (std::min)(available, atMost); // nr rows in outgoing block
if (!skipping) {
result = _buffer.at(pos.first)->slice(pos.second, pos.second + skipped);
}
// increment the position . . .
_posForClient.at(clientId).second += skipped;
// check if we're done at current block in buffer . . .
if (_posForClient.at(clientId).second ==
_buffer.at(_posForClient.at(clientId).first)->size()) {
_posForClient.at(clientId).first++;
_posForClient.at(clientId).second = 0;
// check if we can pop the front of the buffer . . .
bool popit = true;
for (size_t i = 0; i < _nrClients; i++) {
if (_posForClient.at(i).first == 0) {
popit = false;
break;
}
}
if (popit) {
delete _buffer.front();
_buffer.pop_front();
// update the values in first coord of _posForClient
for (size_t i = 0; i < _nrClients; i++) {
_posForClient.at(i).first--;
}
}
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
DistributeBlock::DistributeBlock(ExecutionEngine* engine,
DistributeNode const* ep,
std::vector<std::string> const& shardIds,
Collection const* collection)
: BlockWithClients(engine, ep, shardIds),
_collection(collection),
_index(0),
_regId(ExecutionNode::MaxRegisterId),
_alternativeRegId(ExecutionNode::MaxRegisterId),
_allowSpecifiedKeys(false) {
// get the variable to inspect . . .
VariableId varId = ep->_varId;
// get the register id of the variable to inspect . . .
auto it = ep->getRegisterPlan()->varInfo.find(varId);
TRI_ASSERT(it != ep->getRegisterPlan()->varInfo.end());
_regId = (*it).second.registerId;
TRI_ASSERT(_regId < ExecutionNode::MaxRegisterId);
if (ep->_alternativeVarId != ep->_varId) {
// use second variable
auto it = ep->getRegisterPlan()->varInfo.find(ep->_alternativeVarId);
TRI_ASSERT(it != ep->getRegisterPlan()->varInfo.end());
_alternativeRegId = (*it).second.registerId;
TRI_ASSERT(_alternativeRegId < ExecutionNode::MaxRegisterId);
}
_usesDefaultSharding = collection->usesDefaultSharding();
_allowSpecifiedKeys = ep->_allowSpecifiedKeys;
}
/// @brief initializeCursor
int DistributeBlock::initializeCursor(AqlItemBlock* items, size_t pos) {
DEBUG_BEGIN_BLOCK();
int res = BlockWithClients::initializeCursor(items, pos);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
// local clean up
_distBuffer.clear();
_distBuffer.reserve(_nrClients);
for (size_t i = 0; i < _nrClients; i++) {
_distBuffer.emplace_back();
}
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief shutdown
int DistributeBlock::shutdown(int errorCode) {
DEBUG_BEGIN_BLOCK();
int res = BlockWithClients::shutdown(errorCode);
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
// local clean up
_distBuffer.clear();
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief hasMore: any more for any shard?
bool DistributeBlock::hasMoreForShard(std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
size_t clientId = getClientId(shardId);
if (_doneForClient.at(clientId)) {
return false;
}
if (!_distBuffer.at(clientId).empty()) {
return true;
}
if (!getBlockForClient(DefaultBatchSize(), DefaultBatchSize(), clientId)) {
_doneForClient.at(clientId) = true;
return false;
}
return true;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getOrSkipSomeForShard
int DistributeBlock::getOrSkipSomeForShard(size_t atLeast, size_t atMost,
bool skipping, AqlItemBlock*& result,
size_t& skipped,
std::string const& shardId) {
DEBUG_BEGIN_BLOCK();
traceGetSomeBegin();
TRI_ASSERT(0 < atLeast && atLeast <= atMost);
TRI_ASSERT(result == nullptr && skipped == 0);
size_t clientId = getClientId(shardId);
if (_doneForClient.at(clientId)) {
traceGetSomeEnd(result);
return TRI_ERROR_NO_ERROR;
}
std::deque<std::pair<size_t, size_t>>& buf = _distBuffer.at(clientId);
BlockCollector collector(&_engine->_itemBlockManager);
if (buf.empty()) {
if (!getBlockForClient(atLeast, atMost, clientId)) {
_doneForClient.at(clientId) = true;
traceGetSomeEnd(result);
return TRI_ERROR_NO_ERROR;
}
}
skipped = (std::min)(buf.size(), atMost);
if (skipping) {
for (size_t i = 0; i < skipped; i++) {
buf.pop_front();
}
traceGetSomeEnd(result);
return TRI_ERROR_NO_ERROR;
}
size_t i = 0;
while (i < skipped) {
std::vector<size_t> chosen;
size_t const n = buf.front().first;
while (buf.front().first == n && i < skipped) {
chosen.emplace_back(buf.front().second);
buf.pop_front();
i++;
// make sure we are not overreaching over the end of the buffer
if (buf.empty()) {
break;
}
}
std::unique_ptr<AqlItemBlock> more(_buffer.at(n)->slice(chosen, 0, chosen.size()));
collector.add(std::move(more));
}
if (!skipping) {
result = collector.steal();
}
// _buffer is left intact, deleted and cleared at shutdown
traceGetSomeEnd(result);
return TRI_ERROR_NO_ERROR;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getBlockForClient: try to get atLeast pairs into
/// _distBuffer.at(clientId), this means we have to look at every row in the
/// incoming blocks until they run out or we find enough rows for clientId. We
/// also keep track of blocks which should be sent to other clients than the
/// current one.
bool DistributeBlock::getBlockForClient(size_t atLeast, size_t atMost,
size_t clientId) {
DEBUG_BEGIN_BLOCK();
if (_buffer.empty()) {
_index = 0; // position in _buffer
_pos = 0; // position in _buffer.at(_index)
}
std::vector<std::deque<std::pair<size_t, size_t>>>& buf = _distBuffer;
// it should be the case that buf.at(clientId) is empty
while (buf.at(clientId).size() < atLeast) {
if (_index == _buffer.size()) {
if (!ExecutionBlock::getBlock(atLeast, atMost)) {
if (buf.at(clientId).size() == 0) {
_doneForClient.at(clientId) = true;
return false;
}
break;
}
}
AqlItemBlock* cur = _buffer.at(_index);
while (_pos < cur->size() && buf.at(clientId).size() < atMost) {
// this may modify the input item buffer in place
size_t id = sendToClient(cur);
buf.at(id).emplace_back(std::make_pair(_index, _pos++));
}
if (_pos == cur->size()) {
_pos = 0;
_index++;
} else {
break;
}
}
return true;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief sendToClient: for each row of the incoming AqlItemBlock use the
/// attributes <shardKeys> of the Aql value <val> to determine to which shard
/// the row should be sent and return its clientId
size_t DistributeBlock::sendToClient(AqlItemBlock* cur) {
DEBUG_BEGIN_BLOCK();
// inspect cur in row _pos and check to which shard it should be sent . .
AqlValue val = cur->getValueReference(_pos, _regId);
VPackSlice input = val.slice(); // will throw when wrong type
bool usedAlternativeRegId = false;
if (input.isNull() && _alternativeRegId != ExecutionNode::MaxRegisterId) {
// value is set, but null
// check if there is a second input register available (UPSERT makes use of
// two input registers,
// one for the search document, the other for the insert document)
val = cur->getValueReference(_pos, _alternativeRegId);
input = val.slice(); // will throw when wrong type
usedAlternativeRegId = true;
}
VPackSlice value = input;
VPackBuilder builder;
VPackBuilder builder2;
bool hasCreatedKeyAttribute = false;
if (input.isString() &&
static_cast<DistributeNode const*>(_exeNode)
->_allowKeyConversionToObject) {
builder.openObject();
builder.add(StaticStrings::KeyString, input);
builder.close();
// clear the previous value
cur->destroyValue(_pos, _regId);
// overwrite with new value
cur->setValue(_pos, _regId, AqlValue(builder));
value = builder.slice();
hasCreatedKeyAttribute = true;
} else if (!input.isObject()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_TYPE_INVALID);
}
TRI_ASSERT(value.isObject());
if (static_cast<DistributeNode const*>(_exeNode)->_createKeys) {
// we are responsible for creating keys if none present
if (_usesDefaultSharding) {
// the collection is sharded by _key...
if (!hasCreatedKeyAttribute && !value.hasKey(StaticStrings::KeyString)) {
// there is no _key attribute present, so we are responsible for
// creating one
VPackBuilder temp;
temp.openObject();
temp.add(StaticStrings::KeyString, VPackValue(createKey(value)));
temp.close();
builder2 = VPackCollection::merge(input, temp.slice(), true);
// clear the previous value and overwrite with new value:
if (usedAlternativeRegId) {
cur->destroyValue(_pos, _alternativeRegId);
cur->setValue(_pos, _alternativeRegId, AqlValue(builder2));
} else {
cur->destroyValue(_pos, _regId);
cur->setValue(_pos, _regId, AqlValue(builder2));
}
value = builder2.slice();
}
} else {
// the collection is not sharded by _key
if (hasCreatedKeyAttribute || value.hasKey(StaticStrings::KeyString)) {
// a _key was given, but user is not allowed to specify _key
if (usedAlternativeRegId || !_allowSpecifiedKeys) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_MUST_NOT_SPECIFY_KEY);
}
} else {
VPackBuilder temp;
temp.openObject();
temp.add(StaticStrings::KeyString, VPackValue(createKey(value)));
temp.close();
builder2 = VPackCollection::merge(input, temp.slice(), true);
// clear the previous value and overwrite with new value:
if (usedAlternativeRegId) {
cur->destroyValue(_pos, _alternativeRegId);
cur->setValue(_pos, _alternativeRegId, AqlValue(builder2.slice()));
} else {
cur->destroyValue(_pos, _regId);
cur->setValue(_pos, _regId, AqlValue(builder2.slice()));
}
value = builder2.slice();
}
}
}
std::string shardId;
bool usesDefaultShardingAttributes;
auto clusterInfo = arangodb::ClusterInfo::instance();
auto collInfo = _collection->getCollection();
int res = clusterInfo->getResponsibleShard(collInfo.get(), value, true,
shardId, usesDefaultShardingAttributes);
// std::cout << "SHARDID: " << shardId << "\n";
if (res != TRI_ERROR_NO_ERROR) {
THROW_ARANGO_EXCEPTION(res);
}
TRI_ASSERT(!shardId.empty());
return getClientId(shardId);
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief create a new document key, argument is unused here
#ifndef USE_ENTERPRISE
std::string DistributeBlock::createKey(VPackSlice) const {
ClusterInfo* ci = ClusterInfo::instance();
uint64_t uid = ci->uniqid();
return std::to_string(uid);
}
#endif
/// @brief local helper to throw an exception if a HTTP request went wrong
static bool throwExceptionAfterBadSyncRequest(ClusterCommResult* res,
bool isShutdown) {
DEBUG_BEGIN_BLOCK();
if (res->status == CL_COMM_TIMEOUT ||
res->status == CL_COMM_BACKEND_UNAVAILABLE) {
THROW_ARANGO_EXCEPTION_MESSAGE(res->getErrorCode(),
res->stringifyErrorMessage());
}
if (res->status == CL_COMM_ERROR) {
std::string errorMessage = std::string("Error message received from shard '") +
std::string(res->shardID) +
std::string("' on cluster node '") +
std::string(res->serverID) + std::string("': ");
int errorNum = TRI_ERROR_INTERNAL;
if (res->result != nullptr) {
errorNum = TRI_ERROR_NO_ERROR;
arangodb::basics::StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder = VPackParser::fromJson(
responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (!slice.hasKey("error") || slice.get("error").getBoolean()) {
errorNum = TRI_ERROR_INTERNAL;
}
if (slice.isObject()) {
VPackSlice v = slice.get("errorNum");
if (v.isNumber()) {
if (v.getNumericValue<int>() != TRI_ERROR_NO_ERROR) {
/* if we've got an error num, error has to be true. */
TRI_ASSERT(errorNum == TRI_ERROR_INTERNAL);
errorNum = v.getNumericValue<int>();
}
}
v = slice.get("errorMessage");
if (v.isString()) {
errorMessage += v.copyString();
} else {
errorMessage += std::string("(no valid error in response)");
}
}
}
if (isShutdown && errorNum == TRI_ERROR_QUERY_NOT_FOUND) {
// this error may happen on shutdown and is thus tolerated
// pass the info to the caller who can opt to ignore this error
return true;
}
// In this case a proper HTTP error was reported by the DBserver,
if (errorNum > 0 && !errorMessage.empty()) {
THROW_ARANGO_EXCEPTION_MESSAGE(errorNum, errorMessage);
}
// default error
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_AQL_COMMUNICATION);
}
return false;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief timeout
double const RemoteBlock::defaultTimeOut = 3600.0;
/// @brief creates a remote block
RemoteBlock::RemoteBlock(ExecutionEngine* engine, RemoteNode const* en,
std::string const& server, std::string const& ownName,
std::string const& queryId)
: ExecutionBlock(engine, en),
_server(server),
_ownName(ownName),
_queryId(queryId),
_isResponsibleForInitializeCursor(
en->isResponsibleForInitializeCursor()) {
TRI_ASSERT(!queryId.empty());
TRI_ASSERT(
(arangodb::ServerState::instance()->isCoordinator() && ownName.empty()) ||
(!arangodb::ServerState::instance()->isCoordinator() &&
!ownName.empty()));
}
RemoteBlock::~RemoteBlock() {}
/// @brief local helper to send a request
std::unique_ptr<ClusterCommResult> RemoteBlock::sendRequest(
arangodb::rest::RequestType type, std::string const& urlPart,
std::string const& body) const {
DEBUG_BEGIN_BLOCK();
auto cc = ClusterComm::instance();
if (cc != nullptr) {
// nullptr only happens on controlled shutdown
// Later, we probably want to set these sensibly:
ClientTransactionID const clientTransactionId = "AQL";
CoordTransactionID const coordTransactionId = TRI_NewTickServer();
std::unordered_map<std::string, std::string> headers;
if (!_ownName.empty()) {
headers.emplace("Shard-Id", _ownName);
}
++_engine->_stats.httpRequests;
{
JobGuard guard(SchedulerFeature::SCHEDULER);
guard.block();
auto result =
cc->syncRequest(clientTransactionId, coordTransactionId, _server, type,
std::string("/_db/") +
arangodb::basics::StringUtils::urlEncode(
_engine->getQuery()->trx()->vocbase()->name()) +
urlPart + _queryId,
body, headers, defaultTimeOut);
return result;
}
}
return std::make_unique<ClusterCommResult>();
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief initialize
int RemoteBlock::initialize() {
DEBUG_BEGIN_BLOCK();
if (!_isResponsibleForInitializeCursor) {
// do nothing...
return TRI_ERROR_NO_ERROR;
}
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::PUT, "/_api/aql/initialize/", "{}");
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder =
VPackParser::fromJson(responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (slice.hasKey("code")) {
return slice.get("code").getNumericValue<int>();
}
return TRI_ERROR_INTERNAL;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief initializeCursor, could be called multiple times
int RemoteBlock::initializeCursor(AqlItemBlock* items, size_t pos) {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
if (!_isResponsibleForInitializeCursor) {
// do nothing...
return TRI_ERROR_NO_ERROR;
}
VPackOptions options(VPackOptions::Defaults);
options.buildUnindexedArrays = true;
options.buildUnindexedObjects = true;
VPackBuilder builder(&options);
builder.openObject();
if (items == nullptr) {
// first call, items is still a nullptr
builder.add("exhausted", VPackValue(true));
builder.add("error", VPackValue(false));
} else {
builder.add("exhausted", VPackValue(false));
builder.add("error", VPackValue(false));
builder.add("pos", VPackValue(pos));
builder.add(VPackValue("items"));
builder.openObject();
items->toVelocyPack(_engine->getQuery()->trx(), builder);
builder.close();
}
builder.close();
std::string bodyString(builder.slice().toJson());
std::unique_ptr<ClusterCommResult> res = sendRequest(
rest::RequestType::PUT, "/_api/aql/initializeCursor/", bodyString);
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
{
std::shared_ptr<VPackBuilder> builder = VPackParser::fromJson(
responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (slice.hasKey("code")) {
return slice.get("code").getNumericValue<int>();
}
return TRI_ERROR_INTERNAL;
}
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief shutdown, will be called exactly once for the whole query
int RemoteBlock::shutdown(int errorCode) {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::PUT, "/_api/aql/shutdown/",
std::string("{\"code\":" + std::to_string(errorCode) + "}"));
try {
if (throwExceptionAfterBadSyncRequest(res.get(), true)) {
// artificially ignore error in case query was not found during shutdown
return TRI_ERROR_NO_ERROR;
}
} catch (arangodb::basics::Exception &ex) {
if (ex.code() == TRI_ERROR_CLUSTER_BACKEND_UNAVAILABLE) {
return TRI_ERROR_CLUSTER_BACKEND_UNAVAILABLE;
}
throw;
}
StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder =
VPackParser::fromJson(responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (slice.isObject()) {
if (slice.hasKey("stats")) {
ExecutionStats newStats(slice.get("stats"));
_engine->_stats.add(newStats);
}
// read "warnings" attribute if present and add it to our query
VPackSlice warnings = slice.get("warnings");
if (warnings.isArray()) {
auto query = _engine->getQuery();
for (auto const& it : VPackArrayIterator(warnings)) {
if (it.isObject()) {
VPackSlice code = it.get("code");
VPackSlice message = it.get("message");
if (code.isNumber() && message.isString()) {
query->registerWarning(code.getNumericValue<int>(),
message.copyString().c_str());
}
}
}
}
}
if (slice.hasKey("code")) {
return slice.get("code").getNumericValue<int>();
}
return TRI_ERROR_INTERNAL;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief getSome
AqlItemBlock* RemoteBlock::getSome(size_t atLeast, size_t atMost) {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
traceGetSomeBegin();
VPackBuilder builder;
builder.openObject();
builder.add("atLeast", VPackValue(atLeast));
builder.add("atMost", VPackValue(atMost));
builder.close();
std::string bodyString(builder.slice().toJson());
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::PUT, "/_api/aql/getSome/", bodyString);
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
std::shared_ptr<VPackBuilder> responseBodyBuilder =
res->result->getBodyVelocyPack();
VPackSlice responseBody = responseBodyBuilder->slice();
if (VelocyPackHelper::getBooleanValue(responseBody, "exhausted", true)) {
traceGetSomeEnd(nullptr);
return nullptr;
}
auto r = std::make_unique<AqlItemBlock>(_engine->getQuery()->resourceMonitor(), responseBody);
traceGetSomeEnd(r.get());
return r.release();
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief skipSome
size_t RemoteBlock::skipSome(size_t atLeast, size_t atMost) {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
VPackBuilder builder;
builder.openObject();
builder.add("atLeast", VPackValue(atLeast));
builder.add("atMost", VPackValue(atMost));
builder.close();
std::string bodyString(builder.slice().toJson());
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::PUT, "/_api/aql/skipSome/", bodyString);
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
{
std::shared_ptr<VPackBuilder> builder = VPackParser::fromJson(
responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (!slice.hasKey("error") || slice.get("error").getBoolean()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_AQL_COMMUNICATION);
}
size_t skipped = 0;
if (slice.hasKey("skipped")) {
skipped = slice.get("skipped").getNumericValue<size_t>();
}
return skipped;
}
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief hasMore
bool RemoteBlock::hasMore() {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::GET, "/_api/aql/hasMore/", std::string());
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder =
VPackParser::fromJson(responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (!slice.hasKey("error") || slice.get("error").getBoolean()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_AQL_COMMUNICATION);
}
bool hasMore = true;
if (slice.hasKey("hasMore")) {
hasMore = slice.get("hasMore").getBoolean();
}
return hasMore;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief count
int64_t RemoteBlock::count() const {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
std::unique_ptr<ClusterCommResult> res =
sendRequest(rest::RequestType::GET, "/_api/aql/count/", std::string());
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder =
VPackParser::fromJson(responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (!slice.hasKey("error") || slice.get("error").getBoolean()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_AQL_COMMUNICATION);
}
int64_t count = 0;
if (slice.hasKey("count")) {
count = slice.get("count").getNumericValue<int64_t>();
}
return count;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
/// @brief remaining
int64_t RemoteBlock::remaining() {
DEBUG_BEGIN_BLOCK();
// For every call we simply forward via HTTP
std::unique_ptr<ClusterCommResult> res = sendRequest(
rest::RequestType::GET, "/_api/aql/remaining/", std::string());
throwExceptionAfterBadSyncRequest(res.get(), false);
// If we get here, then res->result is the response which will be
// a serialized AqlItemBlock:
StringBuffer const& responseBodyBuf(res->result->getBody());
std::shared_ptr<VPackBuilder> builder =
VPackParser::fromJson(responseBodyBuf.c_str(), responseBodyBuf.length());
VPackSlice slice = builder->slice();
if (!slice.hasKey("error") || slice.get("error").getBoolean()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_AQL_COMMUNICATION);
}
int64_t remaining = 0;
if (slice.hasKey("remaining")) {
remaining = slice.get("remaining").getNumericValue<int64_t>();
}
return remaining;
// cppcheck-suppress style
DEBUG_END_BLOCK();
}
| 46,661
| 15,933
|
#ifndef DNS_data_parser_HPP
#define DNS_data_parser_HPP
#include "./libs/logger/easylogging++.h"
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "libs/jzon/Jzon.h"
class audioObject {
public:
audioObject ();
float distance;
float angle;
};
class speakerData {
public:
speakerData ();
std::string speakerid;
std::map<std::string, audioObject> objects;
};
class data_parser {
private:
Jzon::Parser _filereader;
Jzon::Writer _filewriter;
public:
data_parser ();
speakerData parseClientData (std::string jsonstring,
std::string client_id,
std::map<std::string, std::vector<float>>& objects);
std::map<std::string, std::string> parseAudioSourceData (std::string jsonstring);
std::string composeClientData (speakerData speaker);
std::string composeAudioSourceData (std::map<std::string, std::string> audioSources);
};
#endif
| 958
| 316
|
#include <gtest/gtest.h>
#include "distribution/Distribution.h"
TEST(DistributionTest, RandomTest) {
auto value = Distribution::random(0.0, 1.0);
EXPECT_TRUE(value <= 1 && value >= -1);
}
TEST(DistributionTest, RandomTest2) {
auto value = Distribution::random(1.0);
EXPECT_TRUE(value <= 1 && value >= 0);
}
| 313
| 120
|
#include <at_tests>
#include "argparser.h"
void test_args() {
const char* args[] = {"", "arg1", "-notarg", "--notarg", "arg2", "-not=arg", "--not=arg"};
ArgParser a = ArgParser(7, args);
ASSERT(a.num_arguments() == 2);
ASSERT(a.get_argument(0) == "arg1");
ASSERT(a.get_argument(1) == "arg2");
const char* args2[] = {"", "--no-args-supplied"};
ArgParser b = ArgParser(2, args2);
ASSERT(b.num_arguments() == 0);
const char* args3[] = {"", "only", "args", "provided"};
ArgParser c = ArgParser(4, args3);
ASSERT(c.num_arguments() == 3);
ASSERT(c.get_argument(0) == "only");
ASSERT(c.get_argument(1) == "args");
ASSERT(c.get_argument(2) == "provided");
}
void test_flags() {
const char* args[] = {"", "arg1", "-flagflag", "--flag", "arg2", "-not=flag", "--also-not=flag"};
ArgParser a = ArgParser(7, args);
ASSERT(a.num_flags() == 9);
ASSERT(a.has_flag("f"));
ASSERT(a.has_flag("l"));
ASSERT(!a.has_flag("x"));
ASSERT(a.flag_count("g") == 2);
ASSERT(a.has_flag("flag"));
const char* args2[] = {"", "noflags", "given"};
ArgParser b = ArgParser(3, args2);
ASSERT(b.num_flags() == 0);
const char* args3[] = {"", "--only", "-flags"};
ArgParser c = ArgParser(3, args3);
ASSERT(c.num_flags() == 6);
ASSERT(!c.has_flag("flag"));
ASSERT(c.has_flag("s"));
}
void test_variables() {
const char* args[] = {"", "arg1", "-flag", "--flag", "arg2", "-var=1", "--var2=val"};
ArgParser a = ArgParser(7, args);
ASSERT(a.num_variables() == 2);
ASSERT(a.has_variable("var"));
ASSERT(!a.has_variable("foo"));
ASSERT(a.get_variable("var2") == "val");
const char* args2[] = {"", "novars", "given"};
ArgParser b = ArgParser(3, args2);
ASSERT(b.num_variables() == 0);
const char* args3[] = {"", "-only=vars", "--are=given"};
ArgParser c = ArgParser(3, args3);
ASSERT(c.num_variables() == 2);
ASSERT(c.has_variable("are"));
ASSERT(!c.has_variable("bar"));
ASSERT(c.get_variable("only") == "vars");
}
void run_argparse_tests() {
TEST(test_args)
TEST(test_flags)
TEST(test_variables)
}
| 2,225
| 919
|
/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include <merge.hpp>
#include <cmdline.hpp>
#include <kdb.hpp>
#include <keysetio.hpp>
#include <modules.hpp>
#include <iostream>
#include <string>
#include <mergehelper.hpp>
#include <merging/metamergestrategy.hpp>
#include <merging/threewaymerge.hpp>
using namespace kdb;
using namespace kdb::tools::merging;
using namespace std;
MergeCommand::MergeCommand ()
{
}
MergeCommand::~MergeCommand ()
{
}
int MergeCommand::execute (Cmdline const & cl)
{
if (cl.arguments.size () < 4)
{
throw invalid_argument ("wrong number of arguments, 4 needed");
}
Key oursRoot = cl.createKey (0);
Key theirsRoot = cl.createKey (1);
Key baseRoot = cl.createKey (2);
Key resultRoot = cl.createKey (3);
KeySet ours;
KeySet theirs;
KeySet base;
{
KDB lkdb;
lkdb.get (ours, oursRoot);
ours = ours.cut (oursRoot);
ours.lookup (oursRoot, KDB_O_POP);
if (cl.verbose) std::cout << "we got ours: " << oursRoot << " with keys " << ours << std::endl;
}
{
KDB lkdb;
lkdb.get (theirs, theirsRoot);
theirs = theirs.cut (theirsRoot);
ours.lookup (oursRoot, KDB_O_POP);
if (cl.verbose) std::cout << "we got theirs: " << theirsRoot << " with keys " << theirs << std::endl;
}
{
KDB lkdb;
lkdb.get (base, baseRoot);
base = base.cut (baseRoot);
ours.lookup (oursRoot, KDB_O_POP);
if (cl.verbose) std::cout << "we got base: " << baseRoot << " with keys " << base << std::endl;
}
KeySet resultKeys;
kdb.get (resultKeys, resultRoot);
KeySet discard = resultKeys.cut (resultRoot);
if (discard.size () != 0)
{
if (cl.force)
{
if (cl.verbose)
{
std::cout << "will remove " << discard.size () << " keys, because -f was given" << std::endl;
}
}
else
{
std::cerr << discard.size () << " keys exist in merge resultpath, will quit. Use -f to override the keys there."
<< std::endl;
}
}
MergeHelper helper;
ThreeWayMerge merger;
helper.configureMerger (cl, merger);
MergeResult result = merger.mergeKeySet (
MergeTask (BaseMergeKeys (base, baseRoot), OurMergeKeys (ours, oursRoot), TheirMergeKeys (theirs, theirsRoot), resultRoot));
helper.reportResult (cl, result, cout, cerr);
int ret = 0;
if (!result.hasConflicts ())
{
resultKeys.append (result.getMergedKeys ());
kdb.set (resultKeys, resultRoot);
}
else
{
ret = -1;
}
return ret;
}
| 2,423
| 1,001
|
/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
*/
#include "library/library_task_builder.h"
#include "library/message_builder.h"
namespace lean {
struct library_scopes_imp : public delegating_task_imp {
io_state m_ios;
log_tree::node m_lt;
library_scopes_imp(std::unique_ptr<gtask_imp> && base, log_tree::node const & lt) :
delegating_task_imp(std::forward<std::unique_ptr<gtask_imp>>(base)),
m_ios(get_global_ios()), m_lt(lt) {}
// TODO(gabriel): set logtree status to cancelled?
void execute(void * result) override {
scope_global_ios scope1(m_ios);
scope_log_tree scope2(m_lt);
if (m_lt) m_lt.set_state(log_tree::state::Running);
try {
delegating_task_imp::execute(result);
} catch (interrupted) {
if (m_lt) m_lt.set_state(log_tree::state::Cancelled);
throw;
}
}
};
std::unique_ptr<gtask_imp> library_scopes::operator()(std::unique_ptr<gtask_imp> && base) {
return std::unique_ptr<gtask_imp>(new library_scopes_imp(
std::forward<std::unique_ptr<gtask_imp>>(base), m_lt));
}
struct exception_reporter_imp : public delegating_task_imp {
exception_reporter_imp(std::unique_ptr<gtask_imp> && base) :
delegating_task_imp(std::forward<std::unique_ptr<gtask_imp>>(base)) {}
void execute(void * result) override {
try {
delegating_task_imp::execute(result);
} catch (std::exception & ex) {
message_builder(environment(), get_global_ios(),
logtree().get_location().m_file_name,
logtree().get_location().m_range.m_begin,
ERROR)
.set_exception(ex)
.report();
throw;
}
}
};
std::unique_ptr<gtask_imp> exception_reporter::operator()(std::unique_ptr<gtask_imp> && base) {
return std::unique_ptr<gtask_imp>(new exception_reporter_imp(
std::forward<std::unique_ptr<gtask_imp>>(base)));
}
}
| 2,157
| 704
|
// Boost.Function library
// Copyright Douglas Gregor 2001-2003. Use, modification and
// distribution is 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)
// For more information, see http://www.boost.org/libs/function
// William Kempf, Jesse Jones and Karl Nelson were all very helpful in the
// design of this library.
#include <functional> // unary_function, binary_function
#include <boost/preprocessor/iterate.hpp>
#include <boost/detail/workaround.hpp>
#ifndef BOOST_FUNCTION_MAX_ARGS
# define BOOST_FUNCTION_MAX_ARGS 10
#endif // BOOST_FUNCTION_MAX_ARGS
// Include the prologue here so that the use of file-level iteration
// in anything that may be included by function_template.hpp doesn't break
#include <boost/function/detail/prologue.hpp>
// Older Visual Age C++ version do not handle the file iteration well
#if BOOST_WORKAROUND(__IBMCPP__, >= 500) && BOOST_WORKAROUND(__IBMCPP__, < 800)
# if BOOST_FUNCTION_MAX_ARGS >= 0
# include <boost/function/function0.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 1
# include <boost/function/function1.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 2
# include <boost/function/function2.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 3
# include <boost/function/function3.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 4
# include <boost/function/function4.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 5
# include <boost/function/function5.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 6
# include <boost/function/function6.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 7
# include <boost/function/function7.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 8
# include <boost/function/function8.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 9
# include <boost/function/function9.hpp>
# endif
# if BOOST_FUNCTION_MAX_ARGS >= 10
# include <boost/function/function10.hpp>
# endif
#else
// What is the '3' for?
# define BOOST_PP_ITERATION_PARAMS_1 (3,(0,BOOST_FUNCTION_MAX_ARGS,<boost/function/detail/function_iterate.hpp>))
# include BOOST_PP_ITERATE()
# undef BOOST_PP_ITERATION_PARAMS_1
#endif
| 2,200
| 842
|
// Created by: Peter KURNEV
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BOPTools_AlgoTools2D_HeaderFile
#define _BOPTools_AlgoTools2D_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Real.hxx>
#include <BOPCol_ListOfShape.hxx>
#include <Standard_Integer.hxx>
class TopoDS_Edge;
class TopoDS_Face;
class gp_Vec;
class Geom2d_Curve;
class Geom_Curve;
class BRepAdaptor_Surface;
class ProjLib_ProjectedCurve;
class IntTools_Context;
//! The class contains handy static functions
//! dealing with the topology
//! This is the copy of the BOPTools_AlgoTools2D.cdl
class BOPTools_AlgoTools2D
{
public:
DEFINE_STANDARD_ALLOC
//! Compute P-Curve for the edge <aE> on the face <aF>.<br>
//! Raises exception Standard_ConstructionError if projection algorithm fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void BuildPCurveForEdgeOnFace (const TopoDS_Edge& aE,
const TopoDS_Face& aF,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Compute tangent for the edge <aE> [in 3D] at parameter <aT>
Standard_EXPORT static Standard_Boolean EdgeTangent (const TopoDS_Edge& anE, const Standard_Real aT, gp_Vec& Tau);
//! Compute surface parameters <U,V> of the face <aF>
//! for the point from the edge <aE> at parameter <aT>.<br>
//! If <aE> has't pcurve on surface, algorithm tries to get it by
//! projection and can
//! raise exception Standard_ConstructionError if projection algorithm fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void PointOnSurface (const TopoDS_Edge& aE,
const TopoDS_Face& aF,
const Standard_Real aT,
Standard_Real& U,
Standard_Real& V,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Get P-Curve <aC> for the edge <aE> on surface <aF> .<br>
//! If the P-Curve does not exist, build it using Make2D().<br>
//! [aToler] - reached tolerance
//! Raises exception Standard_ConstructionError if algorithm Make2D() fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void CurveOnSurface (const TopoDS_Edge& aE,
const TopoDS_Face& aF,
Handle(Geom2d_Curve)& aC,
Standard_Real& aToler,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Get P-Curve <aC> for the edge <aE> on surface <aF> .<br>
//! If the P-Curve does not exist, build it using Make2D().<br>
//! [aFirst, aLast] - range of the P-Curve<br>
//! [aToler] - reached tolerance<br>
//! Raises exception Standard_ConstructionError if algorithm Make2D() fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void CurveOnSurface (const TopoDS_Edge& aE,
const TopoDS_Face& aF,
Handle(Geom2d_Curve)& aC,
Standard_Real& aFirst,
Standard_Real& aLast,
Standard_Real& aToler,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Returns TRUE if the edge <aE> has P-Curve <aC>
//! on surface <aF> .
//! [aFirst, aLast] - range of the P-Curve
//! [aToler] - reached tolerance
//! If the P-Curve does not exist, aC.IsNull()=TRUE.
Standard_EXPORT static Standard_Boolean HasCurveOnSurface (const TopoDS_Edge& aE, const TopoDS_Face& aF, Handle(Geom2d_Curve)& aC, Standard_Real& aFirst, Standard_Real& aLast, Standard_Real& aToler);
//! Returns TRUE if the edge <aE> has P-Curve <aC>
//! on surface <aF> .
//! If the P-Curve does not exist, aC.IsNull()=TRUE.
Standard_EXPORT static Standard_Boolean HasCurveOnSurface (const TopoDS_Edge& aE, const TopoDS_Face& aF);
//! Adjust P-Curve <theC2D> (3D-curve <theC3D>) on surface of the face <theF>.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void AdjustPCurveOnFace (const TopoDS_Face& theF,
const Handle(Geom_Curve)& theC3D,
const Handle(Geom2d_Curve)& theC2D,
Handle(Geom2d_Curve)& theC2DA,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Adjust P-Curve <aC2D> (3D-curve <C3D>) on surface <aF> .<br>
//! [aT1, aT2] - range to adjust<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void AdjustPCurveOnFace (const TopoDS_Face& theF,
const Standard_Real theFirst,
const Standard_Real theLast,
const Handle(Geom2d_Curve)& theC2D,
Handle(Geom2d_Curve)& theC2DA,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Adjust P-Curve <aC2D> (3D-curve <C3D>) on surface <aF> .
//! [aT1, aT2] - range to adjust
Standard_EXPORT static void AdjustPCurveOnSurf (const BRepAdaptor_Surface& aF, const Standard_Real aT1, const Standard_Real aT2, const Handle(Geom2d_Curve)& aC2D, Handle(Geom2d_Curve)& aC2DA);
//! Compute intermediate value in between [aFirst, aLast] .
Standard_EXPORT static Standard_Real IntermediatePoint (const Standard_Real aFirst, const Standard_Real aLast);
//! Compute intermediate value of parameter for the edge <anE>.
Standard_EXPORT static Standard_Real IntermediatePoint (const TopoDS_Edge& anE);
//! Build pcurve of edge on face if the surface is plane, and update the edge.
Standard_EXPORT static void BuildPCurveForEdgeOnPlane (const TopoDS_Edge& theE, const TopoDS_Face& theF);
//! Build pcurve of edge on face if the surface is plane, but do not update the edge.
//! The output are the pcurve and the flag telling that pcurve was built.
Standard_EXPORT static void BuildPCurveForEdgeOnPlane (const TopoDS_Edge& theE, const TopoDS_Face& theF,
Handle(Geom2d_Curve)& aC2D, Standard_Boolean& bToUpdate);
Standard_EXPORT static void BuildPCurveForEdgesOnPlane (const BOPCol_ListOfShape& theLE, const TopoDS_Face& theF);
//! Make P-Curve <aC> for the edge <aE> on surface <aF> .<br>
//! [aFirst, aLast] - range of the P-Curve<br>
//! [aToler] - reached tolerance<br>
//! Raises exception Standard_ConstructionError if algorithm fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void Make2D (const TopoDS_Edge& aE,
const TopoDS_Face& aF,
Handle(Geom2d_Curve)& aC,
Standard_Real& aFirst,
Standard_Real& aLast,
Standard_Real& aToler,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Make P-Curve <aC> for the 3D-curve <C3D> on surface <aF> .<br>
//! [aToler] - reached tolerance<br>
//! Raises exception Standard_ConstructionError if projection algorithm fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void MakePCurveOnFace (const TopoDS_Face& aF,
const Handle(Geom_Curve)& C3D,
Handle(Geom2d_Curve)& aC,
Standard_Real& aToler,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Make P-Curve <aC> for the 3D-curve <C3D> on surface <aF> .<br>
//! [aT1, aT2] - range to build<br>
//! [aToler] - reached tolerance<br>
//! Raises exception Standard_ConstructionError if projection algorithm fails.<br>
//! <theContext> - storage for caching the geometrical tools
Standard_EXPORT static void MakePCurveOnFace (const TopoDS_Face& aF,
const Handle(Geom_Curve)& C3D,
const Standard_Real aT1,
const Standard_Real aT2,
Handle(Geom2d_Curve)& aC,
Standard_Real& aToler,
const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)());
//! Attach P-Curve from the edge <aEold> on surface <aF>
//! to the edge <aEnew>
//! Returns 0 in case of success
Standard_EXPORT static Standard_Integer AttachExistingPCurve (const TopoDS_Edge& aEold, const TopoDS_Edge& aEnew, const TopoDS_Face& aF, const Handle(IntTools_Context)& aCtx);
//! Checks if CurveOnSurface of theE on theF matches with isoline of theF surface.
//! Sets corresponding values for isTheUIso and isTheVIso variables.
//! ATTENTION!!!
//! This method is based on comparation between direction of
//! surface (which theF is based on) iso-lines and the direction
//! of the edge p-curve (on theF) in middle-point of the p-curve.
//! This method should be used carefully
//! (e.g. BRep_Tool::IsClosed(...) together) in order to
//! avoid false classification some p-curves as isoline (e.g. circle
//! on a plane).
Standard_EXPORT static void IsEdgeIsoline(const TopoDS_Edge& theE,
const TopoDS_Face& theF,
Standard_Boolean& isTheUIso,
Standard_Boolean& isTheVIso);
protected:
private:
};
#endif // _BOPTools_AlgoTools2D_HeaderFile
| 11,329
| 3,433
|
#define PROBLEM "https://yukicoder.me/problems/no/306"
#define ERROR 1e-6
#include <cstdio>
#include <cmath>
#include "algorithm/ternary_search.cpp"
int main() {
long double xa, ya, xb, yb;
scanf("%Lf %Lf %Lf %Lf", &xa, &ya, &xb, &yb);
auto f = [&](auto y) { return std::hypot(xa, y-ya) + std::hypot(xb, yb-y); };
long double y = optimize_convex(f, 0.0L, 1e3L, 1e-6L, false).first;
printf("%.20Lf\n", y);
}
| 421
| 211
|
//
// Created by sokol on 02.10.19.
//
#include "path_finder/routing/Dijkstra.h"
#include <queue>
pathFinder::Dijkstra::Dijkstra(const pathFinder::Graph &graph) : graph(graph) {
costs.reserve(graph.numberOfNodes);
previousNode.reserve(graph.numberOfNodes);
while (costs.size() < graph.numberOfNodes) {
costs.emplace_back(MAX_DISTANCE);
previousNode.emplace_back(std::nullopt);
}
}
std::optional<pathFinder::Distance> pathFinder::Dijkstra::getShortestDistance(pathFinder::NodeId source,
pathFinder::NodeId target) {
if (source >= graph.numberOfNodes || target >= graph.numberOfNodes)
return std::nullopt;
// clean up distances
for (auto &nodeId : visited) {
costs[nodeId] = MAX_DISTANCE;
}
visited.clear();
visited.emplace_back(source);
costs[source] = 0;
std::priority_queue<CostNode> q;
q.emplace(source, 0, source);
while (!q.empty()) {
const auto costNode = q.top();
q.pop();
if (costNode.id == target) {
return costNode.cost;
}
for (const auto &edge : graph.edgesFor(costNode.id)) {
Distance currentCost = costNode.cost + edge.distance;
if (currentCost < costs[edge.target]) {
costs[edge.target] = currentCost;
q.emplace(edge.target, currentCost, edge.source);
visited.emplace_back(edge.target);
}
}
}
return costs[target];
}
| 1,430
| 487
|
#include <iostream>
#include <vector>
#include<list>
using namespace std;
#define ll long long int
#define OJ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
#define FIO \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
bool visited[100001] = {false};
list<int> adj[100001];
void dfs(int index, list<int> *adj){
visited[index] = true;
for(auto a: adj[index]){
if(visited[a] == false){
dfs(a, adj);
}
}
}
int main()
{
OJ;
FIO;
int n, r;
cin >> n >> r;
int a, b;
for(int i=0; i<r; i++){
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<long long int> ans;
for(int i=1; i<=n; i++){
if(visited[i] == false){
ans.push_back(i);
dfs(i, adj);
}
}
cout << ans.size()-1 << endl;
for(int i=1; i<ans.size(); i++){
cout << ans[i] << " " << ans[i]-1 << endl;
}
}
| 1,077
| 421
|
/*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cgSolverKernel.hpp"
#include "utils.hpp"
#include "binFiles.hpp"
using namespace std;
template <typename t_DataType,
unsigned int t_InstrBytes,
unsigned int t_ParEntries,
unsigned int t_NumChannels,
typename t_MemInstr,
typename t_CGSolverInstr>
class CgSolverGemv {
public:
CgSolverGemv(FPGA* fpga, unsigned int p_maxIter, t_DataType p_tol) {
m_fpga = fpga;
m_maxIter = p_maxIter;
m_tol = p_tol;
m_instrSize = t_InstrBytes * (1 + p_maxIter);
h_instr.resize(m_instrSize);
m_kernelControl.fpga(m_fpga);
m_kernelControl.getCU("krnl_control");
m_kernelGemv.fpga(m_fpga);
m_kernelGemv.getCU("krnl_gemv");
m_kernelUpdatePk.fpga(m_fpga);
m_kernelUpdatePk.getCU("krnl_update_pk");
m_kernelUpdateRkJacobi.fpga(m_fpga);
m_kernelUpdateRkJacobi.getCU("krnl_update_rk_jacobi");
m_kernelUpdateXk.fpga(m_fpga);
m_kernelUpdateXk.getCU("krnl_update_xk");
}
void setA(const string filePath, unsigned int p_size) {
m_matrixSize = p_size * p_size;
m_vecSize = p_size;
h_A.resize(m_matrixSize);
h_jacobi.resize(m_vecSize);
readBin(filePath, h_A.size() * sizeof(t_DataType), h_A);
for (unsigned int i = 0; i < m_vecSize; i++) {
h_jacobi[i] = 1.0 / h_A[i * m_vecSize + i];
}
}
void setB(const string filePath) {
h_b.resize(m_vecSize);
h_pk.resize(m_vecSize);
h_Apk.resize(m_vecSize);
h_xk.resize(m_vecSize);
h_rk.resize(m_vecSize);
h_zk.resize(m_vecSize);
readBin(filePath, h_b.size() * sizeof(t_DataType), h_b);
t_DataType l_dot = 0, l_rz = 0;
for (unsigned int i = 0; i < m_vecSize; i++) {
h_xk[i] = 0;
h_Apk[i] = 0;
h_rk[i] = h_b[i];
h_zk[i] = h_jacobi[i] * h_rk[i];
l_dot += h_b[i] * h_b[i];
l_rz += h_rk[i] * h_zk[i];
h_pk[i] = h_zk[i];
}
m_cgInstr.setMaxIter(m_maxIter);
m_cgInstr.setTols(l_dot * m_tol * m_tol);
m_cgInstr.setRes(l_dot);
m_cgInstr.setRZ(l_rz);
m_cgInstr.setVecSize(m_vecSize);
m_cgInstr.store(h_instr.data(), m_memInstr);
m_kernelControl.setMem(h_instr);
m_kernelGemv.setMem(h_A, h_pk, h_Apk);
m_kernelUpdatePk.setMem(h_pk, h_zk);
m_kernelUpdateRkJacobi.setMem(h_rk, h_zk, h_jacobi, h_Apk);
m_kernelUpdateXk.setMem(h_xk, h_pk);
m_kernels.push_back(m_kernelControl);
m_kernels.push_back(m_kernelGemv);
m_kernels.push_back(m_kernelUpdatePk);
m_kernels.push_back(m_kernelUpdateXk);
m_kernels.push_back(m_kernelUpdateRkJacobi);
}
void solve(int& lastIter, uint64_t& finalClock) {
lastIter = 0;
finalClock = 0;
Kernel::run(m_kernels);
m_kernelControl.getMem();
m_kernelUpdateRkJacobi.getMem();
m_kernelUpdateXk.getMem();
for (unsigned int i = 0; i < m_maxIter; i++) {
lastIter = i;
m_cgInstr.load(h_instr.data() + (i + 1) * t_InstrBytes, m_memInstr);
if (m_cgInstr.getMaxIter() == 0) {
break;
}
finalClock = m_cgInstr.getClock();
}
}
int verify(const string filePath) {
host_buffer_t<CG_dataType> h_x(m_vecSize);
readBin(filePath, h_x.size() * sizeof(t_DataType), h_x);
int err = 0;
compare(h_x.size(), h_x.data(), h_xk.data(), err);
return err;
}
private:
FPGA* m_fpga;
vector<Kernel> m_kernels;
unsigned int m_maxIter, m_instrSize;
t_DataType m_tol;
unsigned int m_matrixSize, m_vecSize;
t_MemInstr m_memInstr;
t_CGSolverInstr m_cgInstr;
host_buffer_t<uint8_t> h_instr;
host_buffer_t<t_DataType> h_A, h_x, h_b;
host_buffer_t<t_DataType> h_pk, h_Apk, h_xk, h_rk, h_zk, h_jacobi;
CGKernelControl m_kernelControl;
CGKernelGemv<t_DataType, t_ParEntries, t_NumChannels> m_kernelGemv;
CGKernelUpdatePk<t_DataType> m_kernelUpdatePk;
CGKernelUpdateRkJacobi<t_DataType> m_kernelUpdateRkJacobi;
CGKernelUpdateXk<t_DataType> m_kernelUpdateXk;
};
| 4,871
| 1,960
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
// Microsoft (c) 2019, NNFusion Team
#pragma once
#include <memory>
#include "nnfusion/common/descriptor/tensor.hpp"
namespace nnfusion
{
namespace graph
{
class Output
{
public:
/// \param tensor The view of this tensor; where the value will be written
Output(const std::shared_ptr<nnfusion::descriptor::Tensor>& tensor)
: m_tensor(tensor)
{
}
nnfusion::descriptor::Tensor& get_tensor() const { return *m_tensor; }
std::shared_ptr<nnfusion::descriptor::Tensor> get_tensor_ptr() const
{
return m_tensor;
}
void set_tensor_ptr(const std::shared_ptr<nnfusion::descriptor::Tensor>& tensor)
{
m_tensor = tensor;
}
/// \return the element type of the output
const nnfusion::element::Type& get_element_type() const
{
return m_tensor->get_element_type();
}
/// \return the shape of the output
const nnfusion::Shape& get_shape() const { return m_tensor->get_shape(); }
const nnfusion::PartialShape& get_partial_shape() const
{
return m_tensor->get_partial_shape();
}
void set_type_and_shape(const nnfusion::element::Type& element_type,
const nnfusion::PartialShape& pshape)
{
m_tensor->set_tensor_type(element_type, pshape);
}
protected:
std::shared_ptr<nnfusion::descriptor::Tensor> m_tensor;
private:
Output(const Output&) = delete;
Output(Output&&) = delete;
Output& operator=(const Output&) = delete;
};
}
}
| 2,590
| 694
|
// Copyright 2012 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
// Author: grundmann@google.com (Steffen Grundmann)
#include "common/point_of_sail.h"
#include <algorithm>
#include <math.h>
#include <stdio.h>
#include "common/angle.h"
#include "common/check.h"
#include "common/convert.h"
#include "common/delta_angle.h"
#include "common/normalize.h"
#include "common/polar_diagram.h"
#include "common/sign.h"
extern int debug;
PointOfSail::PointOfSail() {
Reset();
}
// We make the decision about the point of sail on the slowly
// filtered true wind only. If the wind turns quickly, then we
// react on that with the AntiWindGust method.
// Everything in radians here.
// If alpha_star and alpha_true are rate limited then the sector
// output doesn't jump.
Angle PointOfSail::SailableHeading(
Angle alpha_star, // rate limited alpha star
Angle alpha_true, // true wind vector, slowly filtered
Angle previous_output, // previous output direction, needed to implement hysteresis
SectorT* sector, // sector codes for state handling and maneuver
Angle* target) {
Angle limit1 = alpha_true.opposite() - TackZone();
Angle limit2 = alpha_true.opposite() + TackZone();
Angle limit3 = alpha_true - JibeZoneHalfWidth();
Angle limit4 = alpha_true + JibeZoneHalfWidth();
if (debug) {
fprintf(stderr, "limits true : % 5.2lf % 5.2lf % 5.2lf % 5.2lf degrees\n",
limit1.deg(), limit2.deg(), limit3.deg(), limit4.deg());
}
// This keeps a small part of the previous output, later used in the hysteresis
// calculation. The hysteresis is good for minimizing the number of maneuvers.
Angle hysteresis_tack = (alpha_star - previous_output) * 0.1; // about 5 degrees
Angle hysteresis_jibe = (alpha_star - previous_output) * 0.3;
bool left = false;
/* Sector defintion
1, 2: left and right in the tack zone
3 : Reaching with sail on starboard
4, 5: right and left in the jibe zone
6 : Reaching with sail on portside
*/
*target = 0;
Angle alpha_star_limited = alpha_star;
if (limit1 <= alpha_star && alpha_star < limit2) {
// Modify if in the non-sailable tack range.
alpha_star_limited = (alpha_star - hysteresis_tack).nearest(limit1, limit2, &left);
*sector = left ? TackPort : TackStar;
*target = left ? limit1 : limit2;
} else if (limit2 <= alpha_star && alpha_star < limit3) {
*sector = ReachStar;
} else if ((limit3 <= alpha_star) && (alpha_star < limit4)) {
// Modify if in the non-sailable jibe range.
alpha_star_limited = (alpha_star - hysteresis_jibe).nearest(limit3, limit4, &left);
*sector = left ? JibeStar : JibePort;
*target = left ? limit3 : limit4;
} else if ((limit4 <= alpha_star) && (alpha_star < limit1)) {
*sector = ReachPort;
} else {
fprintf(stderr, "Illegal sector range: limits: %lf %lf %lf %lf alpha*: %lf degrees\n",
limit1.deg(), limit2.deg(), limit3.deg(), limit4.deg(), alpha_star.deg());
limit1.print("limit1");
limit2.print("limit2");
limit3.print("limit3");
limit4.print("limit4");
alpha_star.print("alpha_star");
CHECK(0);
}
if (debug) {
fprintf(stderr, "limits: % 5.2lf % 5.2lf % 5.2lf % 5.2lf alpha*: %lf degrees, sector %d %c\n",
limit1.deg(), limit2.deg(), limit3.deg(), limit4.deg(), alpha_star.deg(), int(*sector), left?'L':'R');
}
return alpha_star_limited;
}
// We use the apparent wind (which is not as inert as the
// true wind) and react to wind gusts at the very start
// of the normal controller logic.
// If the sector is stable, we can calculate a bearing correction in response to fast wind
// turns.
Angle PointOfSail::AntiWindGust(SectorT sector, // sector codes
Angle alpha_app,
double mag_app_m_s) {
// If the apparent wind has direct influence on the desired heading then
// an instable system is created. We observed such oscillations during our
// lake tests: their exact mechanism is not clear. We apply an asymmetric
// change rate limitation, i.e. if we notice that we went too much into the wind then
// we fall off quickly and return very slowly only. Just like a real helmsman.
const Angle decay = deg(0.2 * 0.1); // 0.2 degree per second (very slow)
Angle correction;
if (mag_app_m_s > 0.5) {
// For the apparent wind the tack zone is smaller and the jibe zone is bigger.
// For the Jibe zone we do not take this into account because it will not
// have much of a negative effect, but would reduce the sailable angles
// a lot.
const Angle kAppOffset = deg(12); // TODO: 10 degrees seems to be better.
// Bigger than 0, if we are too close and have to fall off left.
Angle delta1 = rad(TackZoneRad()).opposite() - kAppOffset - alpha_app;
// Bigger than 0, if we shall fall off right.
Angle delta2 = -rad(TackZoneRad()).opposite() + kAppOffset - alpha_app;
// What do these deltas mean? It means that the normal control has failed or
// that the wind turned quickly.
// If delta1 is positive then the current phi_z (precisely the phi_z averaged during the
// measuring period of the most recent available apparent wind) should be changed by
// (-delta1). By doing that the boat would turn in such a way that it steers at the limit of the
// tack zone.
// If delta1 is negative it can be ignored.
switch (sector) {
case TackPort:
case ReachPort:
buffer2_ = 0;
correction = -PositiveFilterOffset(delta1, decay, &buffer1_);
if (debug && correction.negative()) {
fprintf(stderr, "corr1 FALL OFF LEFT: % 5.2lf \n", correction.deg());
}
break;
case TackStar:
case ReachStar:
buffer1_ = 0;
correction = PositiveFilterOffset(-delta2, decay, &buffer2_);
if (debug && correction > 0) {
fprintf(stderr, "corr2 FALL OFF RIGHT: % 5.2lf \n", correction.deg());
}
break;
case JibeStar:
case JibePort:
correction = 0;
buffer1_ = 0;
buffer2_ = 0;
break;
}
}
return correction;
}
void PointOfSail::Reset() {
buffer1_ = 0;
buffer2_ = 0;
}
Angle FilterOffset(Angle in, Angle decay, Angle* prev) {
if (in.sign() != 0 && in.sign() != prev->sign()) {
*prev = in;
return in;
}
if (in.positive() || prev->positive()) {
if (prev->positive())
*prev -= decay;
if (in > *prev)
*prev = in;
}
if (in.negative() || prev->negative()) {
if (prev->negative())
*prev += decay;
if (in < *prev)
*prev = in;
}
return *prev;
}
Angle PositiveFilterOffset(Angle in, Angle decay, Angle* prev) {
if (in.positive()) {
// clip the correction at 45 degrees.
return FilterOffset(std::min(in, deg(45)), decay, prev);
} else {
return FilterOffset(deg(0), decay, prev);
}
}
| 7,031
| 2,338
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_MAKE_UNIQUE_HPP
#define MAPNIK_MAKE_UNIQUE_HPP
#include <memory>
// http://stackoverflow.com/questions/14131454/visual-studio-2012-cplusplus-and-c-11
#if defined(_MSC_VER) && _MSC_VER < 1800 || !defined(_MSC_VER) && __cplusplus <= 201103L
namespace std {
// C++14 backfill from http://herbsutter.com/gotw/_102/
template<typename T, typename ...Args>
inline std::unique_ptr<T> make_unique(Args&& ...args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif
#endif // MAPNIK_MAKE_UNIQUE_HPP
| 1,537
| 512
|
/*
* refit/scan/common.c
*
* Copyright (c) 2006-2010 Christoph Pfisterer
* 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 Christoph Pfisterer nor the names of the
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 <Platform.h> // Only use angled for Platform, else, xcode project won't compile
#include "entry_scan.h"
#include "../refit/menu.h"
#include "../Platform/guid.h"
#include "../Platform/APFS.h"
#include "../Platform/cpu.h"
#include "../gui/REFIT_MENU_SCREEN.h"
#include "../include/OSTypes.h"
#include "../libeg/XTheme.h"
#ifndef DEBUG_ALL
#define DEBUG_COMMON_MENU 1
#else
#define DEBUG_COMMON_MENU DEBUG_ALL
#endif
#if DEBUG_COMMON_MENU == 0
#define DBG(...)
#else
#define DBG(...) DebugLog(DEBUG_COMMON_MENU, __VA_ARGS__)
#endif
extern CONST CHAR8* IconsNames[];
const XIcon& ScanVolumeDefaultIcon(REFIT_VOLUME *Volume, IN UINT8 OSType, const EFI_DEVICE_PATH_PROTOCOL *DevicePath)
{
UINTN IconNum = 0;
const XIcon* IconX;
// default volume icon based on disk kind
switch (Volume->DiskKind) {
case DISK_KIND_INTERNAL:
switch (OSType) {
case OSTYPE_OSX:
case OSTYPE_OSX_INSTALLER:
while (!IsDevicePathEndType(DevicePath) &&
!(DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType (DevicePath) == MEDIA_VENDOR_DP)) {
DevicePath = NextDevicePathNode(DevicePath);
}
if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType (DevicePath) == MEDIA_VENDOR_DP) {
if ( ApfsSignatureUUID == *(EFI_GUID *)((UINT8 *)DevicePath+0x04) ) {
IconNum = BUILTIN_ICON_VOL_INTERNAL_APFS;
}
} else {
IconNum = BUILTIN_ICON_VOL_INTERNAL_HFS;
}
break;
case OSTYPE_RECOVERY:
IconNum = BUILTIN_ICON_VOL_INTERNAL_REC;
break;
case OSTYPE_LIN:
case OSTYPE_LINEFI:
IconNum = BUILTIN_ICON_VOL_INTERNAL_EXT3;
break;
case OSTYPE_WIN:
case OSTYPE_WINEFI:
IconNum = BUILTIN_ICON_VOL_INTERNAL_NTFS;
break;
default:
IconNum = BUILTIN_ICON_VOL_INTERNAL;
break;
}
break;
case DISK_KIND_EXTERNAL:
IconNum = BUILTIN_ICON_VOL_EXTERNAL;
break;
case DISK_KIND_OPTICAL:
IconNum = BUILTIN_ICON_VOL_OPTICAL;
break;
case DISK_KIND_FIREWIRE:
IconNum = BUILTIN_ICON_VOL_FIREWIRE;
break;
case DISK_KIND_BOOTER:
IconNum = BUILTIN_ICON_VOL_BOOTER;
break;
default:
IconNum = BUILTIN_ICON_VOL_INTERNAL;
break;
}
// DBG("asked IconNum = %llu Volume->DiskKind=%d OSType=%d\n", IconNum, Volume->DiskKind, OSType);
IconX = &ThemeX.GetIcon(IconNum); //asked IconNum = BUILTIN_ICON_VOL_INTERNAL_HFS, got day icon
if (IconX->Image.isEmpty()) {
DBG("asked Icon %s not found, took internal\n", IconsNames[IconNum]);
IconX = &ThemeX.GetIcon(BUILTIN_ICON_VOL_INTERNAL); //including embedded which is really present
}
return *IconX;
}
#define TO_LOWER(ch) (((ch >= L'A') && (ch <= L'Z')) ? ((ch - L'A') + L'a') : ch)
INTN StrniCmp(IN CONST CHAR16 *Str1,
IN CONST CHAR16 *Str2,
IN UINTN Count)
{
CHAR16 Ch1, Ch2;
if (Count == 0) {
return 0;
}
if (Str1 == NULL) {
if (Str2 == NULL) {
return 0;
} else {
return -1;
}
} else if (Str2 == NULL) {
return 1;
}
do {
Ch1 = TO_LOWER(*Str1);
Ch2 = TO_LOWER(*Str2);
Str1++;
Str2++;
if (Ch1 != Ch2) {
return (Ch1 - Ch2);
}
if (Ch1 == 0) {
return 0;
}
} while (--Count > 0);
return 0;
}
CONST CHAR16 *StriStr(IN CONST CHAR16 *Str,
IN CONST CHAR16 *SearchFor)
{
CONST CHAR16 *End;
UINTN Length;
UINTN SearchLength;
if ((Str == NULL) || (SearchFor == NULL)) {
return NULL;
}
Length = StrLen(Str);
if (Length == 0) {
return NULL;
}
SearchLength = StrLen(SearchFor);
if (SearchLength > Length) {
return NULL;
}
End = Str + (Length - SearchLength) + 1;
while (Str < End) {
if (StrniCmp(Str, SearchFor, SearchLength) == 0) {
return Str;
}
++Str;
}
return NULL;
}
void StrToLower(IN CHAR16 *Str)
{
while (*Str) {
*Str = TO_LOWER(*Str);
++Str;
}
}
// TODO remove that and AlertMessage with a printf-like format
STATIC void CreateInfoLines(IN CONST XStringW& Message, OUT XStringWArray* Information)
{
if (Message.isEmpty()) {
return;
}
Information->setEmpty();
//TODO will fill later
}
#if 0 //not needed?
STATIC void CreateInfoLines(IN CONST CHAR16 *Message, OUT XStringWArray* Information)
{
CONST CHAR16 *Ptr;
// CHAR16 **Information;
UINTN Index = 0, Total = 0;
UINTN Length = ((Message == NULL) ? 0 : StrLen(Message));
// Check parameters
if (Length == 0) {
return;
}
// Count how many new lines
Ptr = Message - 1;
while (Ptr != NULL) {
++Total;
Ptr = StrStr(++Ptr, L"\n");
}
// // Create information
// Information = (CHAR16 **)AllocatePool((Total * sizeof(CHAR16 *)) + ((Length + 1) * sizeof(CHAR16)));
// if (Information == NULL) {
// return NULL;
// }
Information->Empty();
// Copy strings
CHAR16* Ptr2 = NULL; // VS2017 complains about uninitialized var.
// CHAR16* Ptr2 = Information[Index++] = (CHAR16 *)(Information + Total);
// StrCpyS(Ptr2, Length + 1, Message);
while ((Index < Total) &&
((Ptr2 = (CHAR16*)StrStr(Ptr2, L"\n")) != NULL)) { // cast is ok because FilePath is not const, and we know that StrStr returns a pointer in FilePath. Will disappear when using a string object instead of CHAR16*
*Ptr2++ = 0;
XStringW* s = new XStringW;
s->takeValueFrom(Ptr2);
Information->AddReference(s, true);
// Information[Index++] = Ptr2;
}
// // Return the info lines
// if (Count != NULL) {
// *Count = Total;
// }
// return Information;
}
#endif
extern REFIT_MENU_ITEM_RETURN MenuEntryReturn;
// it is not good to use Options menu style for messages and one line dialogs
// it can be a semitransparent rectangular at the screen centre as it was in Clover v1.0
STATIC REFIT_MENU_SCREEN AlertMessageMenu(0, XStringW(), XStringW(), &MenuEntryReturn, NULL);
void AlertMessage(const XStringW& Title, const XStringW& Message)
{
CreateInfoLines(Message, &AlertMessageMenu.InfoLines);
AlertMessageMenu.Title = Title;
AlertMessageMenu.RunMenu(NULL);
AlertMessageMenu.InfoLines.setEmpty();
}
#define TAG_YES 1
#define TAG_NO 2
//REFIT_SIMPLE_MENU_ENTRY_TAG(CONST CHAR16 *Title_, UINTN Tag_, ACTION AtClick_)
STATIC REFIT_SIMPLE_MENU_ENTRY_TAG YesMessageEntry(XStringW().takeValueFrom(L"Yes"), TAG_YES, ActionEnter);
STATIC REFIT_SIMPLE_MENU_ENTRY_TAG NoMessageEntry(XStringW().takeValueFrom(L"No"), TAG_NO, ActionEnter);
//REFIT_MENU_SCREEN(UINTN ID, CONST CHAR16* Title, CONST CHAR16* TimeoutText, REFIT_ABSTRACT_MENU_ENTRY* entry1, REFIT_ABSTRACT_MENU_ENTRY* entry2)
STATIC REFIT_MENU_SCREEN YesNoMessageMenu(0, XStringW(), XStringW(), &YesMessageEntry, &NoMessageEntry);
// Display a yes/no prompt
XBool YesNoMessage(IN XStringW& Title, IN CONST XStringW& Message)
{
XBool Result = false;
UINTN MenuExit;
CreateInfoLines(Message, &YesNoMessageMenu.InfoLines);
YesNoMessageMenu.Title = Title;
do
{
REFIT_ABSTRACT_MENU_ENTRY *ChosenEntry = NULL;
MenuExit = YesNoMessageMenu.RunMenu(&ChosenEntry);
if ( ChosenEntry != NULL && ChosenEntry->getREFIT_SIMPLE_MENU_ENTRY_TAG() && ChosenEntry->getREFIT_SIMPLE_MENU_ENTRY_TAG()->Tag == TAG_YES &&
((MenuExit == MENU_EXIT_ENTER) || (MenuExit == MENU_EXIT_DETAILS))) {
Result = true;
MenuExit = MENU_EXIT_ENTER;
}
} while (MenuExit != MENU_EXIT_ENTER);
YesNoMessageMenu.InfoLines.setEmpty();
return Result;
}
// Ask user for file path from directory menu
XBool AskUserForFilePathFromDir(const CHAR16 *Title OPTIONAL, IN REFIT_VOLUME *Volume,
const CHAR16 *ParentPath OPTIONAL, const EFI_FILE *Dir,
OUT EFI_DEVICE_PATH_PROTOCOL **Result)
{
//REFIT_MENU_SCREEN Menu = { 0, L"Please Select File...", NULL, 0, NULL, 0, NULL,
// 0, NULL, false, false, 0, 0, 0, 0, { 0, 0, 0, 0 }, NULL};
// Check parameters
if ((Volume == NULL) || (Dir == NULL) || (Result == NULL)) {
return false;
}
// TODO: Generate directory menu
return false;
}
#define TAG_OFFSET 1000
//STATIC REFIT_MENU_SCREEN InitialMenu = {0, L"Please Select File...", NULL, 0, NULL,
// 0, NULL, NULL, false, false, 0, 0, 0, 0,
// { 0, 0, 0, 0 }, NULL};
//STATIC REFIT_MENU_SCREEN InitialMenu(0, L"Please Select File..."_XSW, XStringW());
// Ask user for file path from volumes menu
XBool AskUserForFilePathFromVolumes(const CHAR16 *Title OPTIONAL, OUT EFI_DEVICE_PATH_PROTOCOL **Result)
{
REFIT_MENU_SCREEN Menu(0, L"Please Select File..."_XSW, XStringW());
UINTN Index = 0, /*Count = 0,*/ MenuExit;
XBool Responded = false;
if (Result == NULL) {
return false;
}
// Create volume entries
for (Index = 0; Index < Volumes.size(); ++Index) {
REFIT_VOLUME *Volume = &Volumes[Index];
if ((Volume == NULL) || (Volume->RootDir == NULL) ||
((Volume->DevicePathString.isEmpty()) && (Volume->VolName.isEmpty()))) {
continue;
}
REFIT_SIMPLE_MENU_ENTRY_TAG *Entry = new REFIT_SIMPLE_MENU_ENTRY_TAG(SWPrintf("%ls", (Volume->VolName.isEmpty()) ? Volume->DevicePathString.wc_str() : Volume->VolName.wc_str()), TAG_OFFSET + Index, MENU_EXIT_ENTER);
Menu.Entries.AddReference(Entry, true);
}
// Setup menu
Menu.Entries.AddReference(&MenuEntryReturn, false);
Menu.Title.takeValueFrom(Title);
do
{
REFIT_ABSTRACT_MENU_ENTRY *ChosenEntry = NULL;
// Run the volume chooser menu
MenuExit = Menu.RunMenu(&ChosenEntry);
if ((ChosenEntry != NULL) && ChosenEntry->getREFIT_SIMPLE_MENU_ENTRY_TAG() &&
((MenuExit == MENU_EXIT_ENTER) || (MenuExit == MENU_EXIT_DETAILS))) {
if (ChosenEntry->getREFIT_SIMPLE_MENU_ENTRY_TAG()->Tag >= TAG_OFFSET) {
Index = (ChosenEntry->getREFIT_SIMPLE_MENU_ENTRY_TAG()->Tag - TAG_OFFSET);
if (Index < Volumes.size()) {
// Run directory chooser menu
if (!AskUserForFilePathFromDir(Title, &Volumes[Index], NULL, Volumes[Index].RootDir, Result)) {
continue;
}
Responded = true;
}
}
break;
}
} while (MenuExit != MENU_EXIT_ESCAPE);
// FreePool(Entries);
return Responded;
}
// Ask user for file path
XBool AskUserForFilePath(IN CHAR16 *Title OPTIONAL, IN EFI_DEVICE_PATH_PROTOCOL *Root OPTIONAL, OUT EFI_DEVICE_PATH_PROTOCOL **Result)
{
EFI_FILE *Dir = NULL;
if (Result == NULL) {
return false;
}
if (Root != NULL) {
// Get the file path
XStringW DevicePathStr = FileDevicePathToXStringW(Root);
if (DevicePathStr.notEmpty()) {
UINTN Index = 0;
// Check the volumes for a match
for (Index = 0; Index < Volumes.size(); ++Index) {
REFIT_VOLUME *Volume = &Volumes[Index];
if ((Volume == NULL) || (Volume->RootDir == NULL) ||
(Volume->DevicePathString.isEmpty())) {
continue;
}
if (Volume->DevicePathString.length() == 0) {
continue;
}
// If the path begins with this volumes path it matches
if (StrniCmp(DevicePathStr.wc_str(), Volume->DevicePathString.wc_str(), Volume->DevicePathString.length())) {
// Need to
const CHAR16 *FilePath = DevicePathStr.data(Volume->DevicePathString.length());
UINTN FileLength = StrLen(FilePath);
if (FileLength == 0) {
// If there is no path left then open the root
return AskUserForFilePathFromDir(Title, Volume, NULL, Volume->RootDir, Result);
} else {
// Check to make sure this is directory
if (!EFI_ERROR(Volume->RootDir->Open(Volume->RootDir, &Dir, FilePath, EFI_FILE_MODE_READ, 0)) &&
(Dir != NULL)) {
// Get file information
EFI_FILE_INFO *Info = EfiLibFileInfo(Dir);
if (Info != NULL) {
// Check if the file is a directory
if ((Info->Attribute & EFI_FILE_DIRECTORY) == 0) {
// Return the passed device path if it is a file
FreePool(Info);
Dir->Close(Dir);
*Result = Root;
return true;
} else {
// Ask user other wise
XBool Success = AskUserForFilePathFromDir(Title, Volume, FilePath, Dir, Result);
FreePool(Info);
Dir->Close(Dir);
return Success;
}
//FreePool(Info);
}
Dir->Close(Dir);
}
}
}
}
}
}
return AskUserForFilePathFromVolumes(Title, Result);
}
// input - tsc
// output - milliseconds
// the caller is responsible for t1 > t0
UINT64 TimeDiff(UINT64 t0, UINT64 t1)
{
return DivU64x64Remainder((t1 - t0), DivU64x32(gCPUStructure.TSCFrequency, 1000), 0);
}
| 14,646
| 5,307
|
#define __STDC_FORMAT_MACROS 1
#include <algorithm>
#include <cassert>
#include <cinttypes>
#include <cstdint>
#include <cstring>
#include <queue>
#include <memory>
#include <map>
#include <set>
#include <stdexcept>
#include <unordered_set>
#include <unordered_map>
#include <vector>
extern "C" {
#include <libvex.h>
#include <pyvex.h>
}
#include <unicorn/unicorn.h>
#include "sim_unicorn.hpp"
//#include "log.h"
State::State(uc_engine *_uc, uint64_t cache_key):uc(_uc) {
hooked = false;
h_read = h_write = h_block = h_prot = 0;
max_steps = cur_steps = 0;
stopped = true;
stop_details.stop_reason = STOP_NOSTART;
ignore_next_block = false;
ignore_next_selfmod = false;
interrupt_handled = false;
transmit_sysno = -1;
vex_guest = VexArch_INVALID;
syscall_count = 0;
uc_context_alloc(uc, &saved_regs);
executed_pages_iterator = NULL;
cpu_flags_register = -1;
mem_updates_head = NULL;
auto it = global_cache.find(cache_key);
if (it == global_cache.end()) {
page_cache = new PageCache();
global_cache[cache_key] = {page_cache};
} else {
page_cache = it->second.page_cache;
}
arch = *((uc_arch*)uc); // unicorn hides all its internals...
mode = *((uc_mode*)((uc_arch*)uc + 1));
curr_block_details.reset();
symbolic_read_in_progress = false;
}
/*
* HOOK_MEM_WRITE is called before checking if the address is valid. so we might
* see uninitialized pages. Using HOOK_MEM_PROT is too late for tracking taint.
* so we don't have to use HOOK_MEM_PROT to track dirty pages.
*/
void State::hook() {
if (hooked) {
//LOG_D("already hooked");
return ;
}
uc_err err;
err = uc_hook_add(uc, &h_read, UC_HOOK_MEM_READ, (void *)hook_mem_read, this, 1, 0);
err = uc_hook_add(uc, &h_write, UC_HOOK_MEM_WRITE, (void *)hook_mem_write, this, 1, 0);
err = uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, this, 1, 0);
err = uc_hook_add(uc, &h_prot, UC_HOOK_MEM_PROT, (void *)hook_mem_prot, this, 1, 0);
err = uc_hook_add(uc, &h_unmap, UC_HOOK_MEM_UNMAPPED, (void *)hook_mem_unmapped, this, 1, 0);
err = uc_hook_add(uc, &h_intr, UC_HOOK_INTR, (void *)hook_intr, this, 1, 0);
hooked = true;
}
void State::unhook() {
if (!hooked)
return ;
uc_err err;
err = uc_hook_del(uc, h_read);
err = uc_hook_del(uc, h_write);
err = uc_hook_del(uc, h_block);
err = uc_hook_del(uc, h_prot);
err = uc_hook_del(uc, h_unmap);
err = uc_hook_del(uc, h_intr);
hooked = false;
h_read = h_write = h_block = h_prot = h_unmap = 0;
}
uc_err State::start(address_t pc, uint64_t step) {
stopped = false;
stop_details.stop_reason = STOP_NOSTART;
max_steps = step;
cur_steps = -1;
unicorn_next_instr_addr = pc;
executed_pages.clear();
// error if pc is 0
// TODO: why is this check here and not elsewhere
if (pc == 0) {
stop_details.stop_reason = STOP_ZEROPAGE;
cur_steps = 0;
return UC_ERR_MAP;
}
uc_err out = uc_emu_start(uc, unicorn_next_instr_addr, 0, 0, 0);
if (out == UC_ERR_OK && stop_details.stop_reason == STOP_NOSTART && get_instruction_pointer() == 0) {
// handle edge case where we stop because we reached our bogus stop address (0)
commit();
stop_details.stop_reason = STOP_ZEROPAGE;
}
rollback();
if (out == UC_ERR_INSN_INVALID) {
stop_details.stop_reason = STOP_NODECODE;
}
// if we errored out right away, fix the step count to 0
if (cur_steps == -1) cur_steps = 0;
return out;
}
void State::stop(stop_t reason, bool do_commit) {
stopped = true;
stop_details.stop_reason = reason;
stop_details.block_addr = curr_block_details.block_addr;
stop_details.block_size = curr_block_details.block_size;
if ((reason == STOP_SYSCALL) || do_commit) {
commit();
}
else if ((reason != STOP_NORMAL) && (reason != STOP_STOPPOINT)) {
// Stop reason is not NORMAL, STOPPOINT or SYSCALL. Rollback.
// EXECNONE, ZEROPAGE, NOSTART, ZERO_DIV, NODECODE and HLT are never passed to this function.
rollback();
}
uc_emu_stop(uc);
// Prepare details of blocks with symbolic instructions to re-execute for returning to state plugin
for (auto &block: blocks_with_symbolic_instrs) {
sym_block_details_t sym_block;
sym_block.reset();
sym_block.block_addr = block.block_addr;
sym_block.block_size = block.block_size;
std::set<instr_details_t> sym_instrs;
std::unordered_set<register_value_t> reg_values;
for (auto &sym_instr: block.symbolic_instrs) {
auto sym_instr_list = get_list_of_dep_instrs(sym_instr);
sym_instrs.insert(sym_instr_list.begin(), sym_instr_list.end());
sym_instrs.insert(sym_instr);
reg_values.insert(sym_instr.reg_deps.begin(), sym_instr.reg_deps.end());
}
sym_block.register_values.insert(sym_block.register_values.end(), reg_values.begin(), reg_values.end());
for (auto &instr: sym_instrs) {
sym_instr_details_t sym_instr;
sym_instr.instr_addr = instr.instr_addr;
sym_instr.memory_values = instr.memory_values;
sym_instr.memory_values_count = instr.memory_values_count;
sym_instr.has_memory_dep = instr.has_concrete_memory_dep;
sym_block.symbolic_instrs.emplace_back(sym_instr);
}
block_details_to_return.emplace_back(sym_block);
}
}
void State::step(address_t current_address, int32_t size, bool check_stop_points) {
if (track_bbls) {
bbl_addrs.push_back(current_address);
}
if (track_stack) {
stack_pointers.push_back(get_stack_pointer());
}
executed_pages.insert(current_address & ~0xFFFULL);
cur_address = current_address;
cur_size = size;
if (cur_steps >= max_steps) {
stop(STOP_NORMAL);
} else if (check_stop_points) {
// If size is zero, that means that the current basic block was too large for qemu
// and it got split into multiple parts. unicorn will only call this hook for the
// first part and not for the remaining ones, so it is impossible to find the
// accurate size of the BB block here.
//
// See https://github.com/unicorn-engine/unicorn/issues/874
//
// Until that is resolved, we use the maximum size of a Qemu basic block here. This means
// that some stop points may not work, but there is no way to do better.
uint32_t real_size = size == 0 ? MAX_BB_SIZE : size;
// if there are any stop points in the current basic block, then there is no chance
// for us to stop in the middle of a block.
// since we do not support stopping in the middle of a block.
auto stop_point = stop_points.lower_bound(current_address);
if (stop_point != stop_points.end() && *stop_point < current_address + real_size) {
stop(STOP_STOPPOINT);
}
}
}
void State::commit() {
// save registers
uc_context_save(uc, saved_regs);
// mark memory sync status
// we might miss some dirty bits, this happens if hitting the memory
// write before mapping
/* THIS SHOULDN'T BE REQUIRED, we have the same logic to do this in the page activation code
for (auto it = mem_writes.begin(); it != mem_writes.end(); it++) {
if (it->clean == -1) {
taint_t *bitmap = page_lookup(it->address);
if (it->is_symbolic) {
memset(&bitmap[it->address & 0xFFFULL], TAINT_SYMBOLIC, sizeof(taint_t) * it->size);
}
else {
memset(&bitmap[it->address & 0xFFFULL], TAINT_DIRTY, sizeof(taint_t) * it->size);
it->clean = (1 << it->size) - 1;
//LOG_D("commit: lazy initialize mem_write [%#lx, %#lx]", it->address, it->address + it->size);
}
}
}
*/
// clear memory rollback status
mem_writes.clear();
cur_steps++;
// Sync all block level taint statuses reads with state's taint statuses and block level
// symbolic instruction list with state's symbolic instruction list
for (auto ®_offset: block_symbolic_registers) {
symbolic_registers.emplace(reg_offset);
}
for (auto ®_offset: block_concrete_registers) {
symbolic_registers.erase(reg_offset);
}
if (curr_block_details.symbolic_instrs.size() > 0) {
for (auto &symbolic_instr: curr_block_details.symbolic_instrs) {
compute_slice_of_instr(symbolic_instr);
// Save all concrete memory dependencies of the block
save_concrete_memory_deps(symbolic_instr);
}
blocks_with_symbolic_instrs.emplace_back(curr_block_details);
}
// Clear all block level taint status trackers and symbolic instruction list
block_symbolic_registers.clear();
block_concrete_registers.clear();
block_instr_concrete_regs.clear();
curr_block_details.reset();
block_mem_reads_data.clear();
block_mem_reads_map.clear();
mem_writes_taint_map.clear();
taint_engine_next_instr_address = 0;
taint_engine_stop_mem_read_instruction = 0;
taint_engine_stop_mem_read_size = 0;
return;
}
void State::rollback() {
// roll back memory changes
for (auto rit = mem_writes.rbegin(); rit != mem_writes.rend(); rit++) {
uc_err err = uc_mem_write(uc, rit->address, rit->value, rit->size);
if (err) {
//LOG_I("rollback: %s", uc_strerror(err));
break;
}
auto page = page_lookup(rit->address);
taint_t *bitmap = page.first;
uint64_t start = rit->address & 0xFFF;
int size = rit->size;
for (auto i = 0; i < size; i++) {
bitmap[start + i] = rit->previous_taint[i];
}
}
mem_writes.clear();
// restore registers
uc_context_restore(uc, saved_regs);
if (track_bbls) bbl_addrs.pop_back();
if (track_stack) stack_pointers.pop_back();
}
/*
* return the PageBitmap only if the page is remapped for writing,
* or initialized with symbolic variable, otherwise return NULL.
*/
std::pair<taint_t *, uint8_t *> State::page_lookup(address_t address) const {
address &= ~0xFFFULL;
auto it = active_pages.find(address);
if (it == active_pages.end()) {
return std::pair<taint_t *, uint8_t *>(NULL, NULL);
}
return it->second;
}
void State::page_activate(address_t address, uint8_t *taint, uint8_t *data) {
address &= ~0xFFFULL;
auto it = active_pages.find(address);
if (it == active_pages.end()) {
if (data == NULL) {
// We need to copy the taint bitmap
taint_t *bitmap = new PageBitmap;
memcpy(bitmap, taint, sizeof(PageBitmap));
active_pages.insert(std::pair<address_t, std::pair<taint_t*, uint8_t*>>(address, std::pair<taint_t*, uint8_t*>(bitmap, NULL)));
} else {
// We can directly use the passed taint and data
taint_t *bitmap = (taint_t*)taint;
active_pages.insert(std::pair<uint64_t, std::pair<taint_t*, uint8_t*>>(address, std::pair<taint_t*, uint8_t*>(bitmap, data)));
}
} else {
// TODO: un-hardcode this address, or at least do this warning from python land
if (address == 0x4000) {
printf("[sim_unicorn] You've mapped something at 0x4000! "
"Please don't do that, I put my GDT there!\n");
} else {
printf("[sim_unicorn] Something very bad is happening; please investigate. "
"Trying to activate the page at %#" PRIx64 " but it's already activated.\n", address);
// to the person who sees this error:
// you're gonna need to spend some time looking into it.
// I'm not 100% sure that this is necessarily a bug condition.
}
}
/* SHOULD NOT BE NECESSARY
for (auto a = mem_writes.begin(); a != mem_writes.end(); a++)
if (a->clean == -1 && (a->address & ~0xFFFULL) == address) {
// This mapping was prompted by this write.
// initialize this memory access immediately so that the
// record is valid.
//printf("page_activate: lazy initialize mem_write [%#lx, %#lx]\n", a->address, a->address + a->size);
if (data == NULL) {
memset(&bitmap[a->address & 0xFFFULL], TAINT_DIRTY, sizeof(taint_t) * a->size);
a->clean = (1ULL << a->size) - 1;
} else {
a->clean = 0;
for (int i = 0; i < a->size; i++) {
if (bitmap[(a->address & 0xFFFULL) + i] == TAINT_SYMBOLIC) {
a->clean |= 1 << i;
}
}
memset(&bitmap[a->address & 0xFFFULL], TAINT_CLEAN, sizeof(taint_t) * a->size);
memcpy(a->value, &data[a->address & 0xFFFULL], a->size);
}
}
*/
}
mem_update_t *State::sync() {
for (auto it = active_pages.begin(); it != active_pages.end(); it++) {
uint8_t *data = it->second.second;
if (data != NULL) {
// nothing to sync, direct mapped :)
continue;
}
taint_t *start = it->second.first;
taint_t *end = &it->second.first[0x1000];
//LOG_D("found active page %#lx (%p)", it->first, start);
for (taint_t *i = start; i < end; i++)
if ((*i) == TAINT_DIRTY) {
taint_t *j = i;
while (j < end && (*j) == TAINT_DIRTY) j++;
char buf[0x1000];
uc_mem_read(uc, it->first + (i - start), buf, j - i);
//LOG_D("sync [%#lx, %#lx] = %#lx", it->first + (i - start), it->first + (j - start), *(uint64_t *)buf);
mem_update_t *range = new mem_update_t;
range->address = it->first + (i - start);
range->length = j - i;
range->next = mem_updates_head;
mem_updates_head = range;
i = j;
}
}
return mem_updates_head;
}
void State::set_stops(uint64_t count, address_t *stops) {
stop_points.clear();
for (auto i = 0; i < count; i++) {
stop_points.insert(stops[i]);
}
}
std::pair<address_t, size_t> State::cache_page(address_t address, size_t size, char* bytes, uint64_t permissions) {
assert(address % 0x1000 == 0);
assert(size % 0x1000 == 0);
for (auto offset = 0; offset < size; offset += 0x1000) {
auto page = page_cache->find(address+offset);
if (page != page_cache->end()) {
fprintf(stderr, "[%#" PRIx64 ", %#" PRIx64 "](%#zx) already in cache.\n", address+offset, address+offset + 0x1000, 0x1000lu);
assert(page->second.size == 0x1000);
assert(memcmp(page->second.bytes, bytes + offset, 0x1000) == 0);
continue;
}
uint8_t *copy = (uint8_t *)malloc(0x1000);
CachedPage cached_page = {
0x1000,
copy,
permissions
};
// address should be aligned to 0x1000
memcpy(copy, &bytes[offset], 0x1000);
page_cache->insert(std::pair<address_t, CachedPage>(address+offset, cached_page));
}
return std::make_pair(address, size);
}
void State::wipe_page_from_cache(address_t address) {
auto page = page_cache->find(address);
if (page != page_cache->end()) {
//printf("Internal: unmapping %#llx size %#x, result %#x", page->first, page->second.size, uc_mem_unmap(uc, page->first, page->second.size));
uc_err err = uc_mem_unmap(uc, page->first, page->second.size);
//if (err) {
// fprintf(stderr, "wipe_page_from_cache [%#lx, %#lx]: %s\n", page->first, page->first + page->second.size, uc_strerror(err));
//}
free(page->second.bytes); // might explode
page_cache->erase(page);
}
else {
//printf("Uh oh! Couldn't find page at %#llx\n", address);
}
}
void State::uncache_pages_touching_region(address_t address, uint64_t length) {
address &= ~(0x1000-1);
for (auto offset = 0; offset < length; offset += 0x1000) {
wipe_page_from_cache(address + offset);
}
}
void State::clear_page_cache() {
while (!page_cache->empty()) {
wipe_page_from_cache(page_cache->begin()->first);
}
}
bool State::map_cache(address_t address, size_t size) {
assert(address % 0x1000 == 0);
assert(size % 0x1000 == 0);
bool success = true;
for (auto offset = 0; offset < size; offset += 0x1000) {
auto page = page_cache->find(address+offset);
if (page == page_cache->end())
{
success = false;
continue;
}
auto cached_page = page->second;
size_t page_size = cached_page.size;
uint8_t *bytes = cached_page.bytes;
uint64_t permissions = cached_page.perms;
assert(page_size == 0x1000);
//LOG_D("hit cache [%#lx, %#lx]", address, address + size);
uc_err err = uc_mem_map_ptr(uc, page->first, page_size, permissions, bytes);
if (err) {
fprintf(stderr, "map_cache [%#lx, %#lx]: %s\n", address, address + size, uc_strerror(err));
success = false;
continue;
}
}
return success;
}
bool State::in_cache(address_t address) const {
return page_cache->find(address) != page_cache->end();
}
// Finds tainted data in the provided range and returns the address.
// Returns -1 if no tainted data is present.
int64_t State::find_tainted(address_t address, int size) {
taint_t *bitmap = page_lookup(address).first;
int start = address & 0xFFF;
int end = (address + size - 1) & 0xFFF;
if (end >= start) {
if (bitmap) {
for (auto i = start; i <= end; i++) {
if (bitmap[i] & TAINT_SYMBOLIC) {
return (address & ~0xFFF) + i;
}
}
}
}
else {
// cross page boundary
if (bitmap) {
for (auto i = start; i <= 0xFFF; i++) {
if (bitmap[i] & TAINT_SYMBOLIC) {
return (address & ~0xFFF) + i;
}
}
}
bitmap = page_lookup(address + size - 1).first;
if (bitmap) {
for (auto i = 0; i <= end; i++) {
if (bitmap[i] & TAINT_SYMBOLIC) {
return ((address + size - 1) & ~0xFFF) + i;
}
}
}
}
return -1;
}
void State::handle_write(address_t address, int size, bool is_interrupt) {
// If the write spans a page, chop it up
if ((address & 0xfff) + size > 0x1000) {
int chopsize = 0x1000 - (address & 0xfff);
handle_write(address, chopsize, is_interrupt);
if (stopped) {
return;
}
handle_write(address + chopsize, size - chopsize, is_interrupt);
return;
}
// From here, we are definitely only dealing with one page
mem_write_t record;
record.address = address;
record.size = size;
uc_err err = uc_mem_read(uc, address, record.value, size);
if (err == UC_ERR_READ_UNMAPPED) {
if (py_mem_callback(uc, UC_MEM_WRITE_UNMAPPED, address, size, 0, (void*)1)) {
err = UC_ERR_OK;
}
}
if (err) {
stop(STOP_ERROR);
return;
}
auto pair = page_lookup(address);
taint_t *bitmap = pair.first;
uint8_t *data = pair.second;
int start = address & 0xFFF;
int end = (address + size - 1) & 0xFFF;
short clean;
address_t curr_instr_addr;
bool is_dst_symbolic;
if (!bitmap) {
// We should never have a missing bitmap because we explicitly called the callback!
printf("This should never happen, right? %#" PRIx64 "\n", address);
abort();
}
clean = 0;
if (is_interrupt || is_symbolic_tracking_disabled() || curr_block_details.vex_lift_failed) {
// If symbolic tracking is disabled, all writes are concrete
// is_interrupt flag is a workaround for CGC transmit syscall, which never passes symbolic data
// If VEX lift failed, then write is definitely concrete since execution continues only
// if no symbolic data is present
is_dst_symbolic = false;
}
else {
curr_instr_addr = get_instruction_pointer();
auto mem_writes_taint_map_entry = mem_writes_taint_map.find(curr_instr_addr);
if (mem_writes_taint_map_entry != mem_writes_taint_map.end()) {
is_dst_symbolic = mem_writes_taint_map_entry->second;
}
// We did not find a memory write at this instruction when processing the VEX statements.
// This likely means unicorn reported the current PC register value wrong.
// If there are no symbolic registers, assume write is concrete and continue concrete execution else stop.
else if ((symbolic_registers.size() == 0) && (block_symbolic_registers.size() == 0)) {
is_dst_symbolic = false;
}
else {
stop(STOP_UNKNOWN_MEMORY_WRITE);
return;
}
}
if (is_dst_symbolic) {
// Save the details of memory location written to in the instruction details
for (auto &symbolic_instr: curr_block_details.symbolic_instrs) {
if (symbolic_instr.instr_addr == curr_instr_addr) {
symbolic_instr.mem_write_addr = address;
symbolic_instr.mem_write_size = size;
break;
}
}
}
if ((find_tainted(address, size) != -1) & (!is_dst_symbolic)) {
// We are writing to a memory location that is currently symbolic. If the destination if a memory dependency
// of some instruction to be re-executed, we need to re-execute that instruction before continuing.
auto write_start_addr = address;
auto write_end_addr = address + size;
for (auto &block: blocks_with_symbolic_instrs) {
for (auto &sym_instr: block.symbolic_instrs) {
for (auto &symbolic_mem_dep: sym_instr.symbolic_mem_deps) {
auto symbolic_start_addr = symbolic_mem_dep.first;
auto symbolic_end_addr = symbolic_mem_dep.first + symbolic_mem_dep.second;
if (!((symbolic_end_addr < write_start_addr) || (write_end_addr < symbolic_start_addr))) {
// No overlap condition test failed => there is some overlap. Thus, some symbolic memory dependency
// will be lost. Stop execution.
stop(STOP_SYMBOLIC_MEM_DEP_NOT_LIVE);
return;
}
}
}
}
// Also check if the destination is a memory dependency of an instruction in current block should be re-executed
for (auto &sym_instr: curr_block_details.symbolic_instrs) {
for (auto &symbolic_mem_dep: sym_instr.symbolic_mem_deps) {
auto symbolic_start_addr = symbolic_mem_dep.first;
auto symbolic_end_addr = symbolic_mem_dep.first + symbolic_mem_dep.second;
if (!((symbolic_end_addr < write_start_addr) || (write_end_addr < symbolic_start_addr))) {
// No overlap condition test failed => there is some overlap. Thus, some symbolic memory dependency
// will be lost. Stop execution.
stop(STOP_SYMBOLIC_MEM_DEP_NOT_LIVE_CURR_BLOCK);
return;
}
}
}
// The destination is not a memory dependency of some instruction to be re-executed. We now check if any
// instructions to be re-executed write to this same location. If there is one, they need not be re-executed
// since this concrete write nullifies their effects.
auto curr_write_start_addr = address;
auto curr_write_end_addr = address + size;
std::vector<std::vector<instr_details_t>::iterator> instrs_to_erase_it;
for (auto &block: blocks_with_symbolic_instrs) {
instrs_to_erase_it.clear();
for (auto sym_instr_it = block.symbolic_instrs.begin(); sym_instr_it != block.symbolic_instrs.end(); sym_instr_it++) {
int64_t symbolic_write_start_addr = sym_instr_it->mem_write_addr;
if (symbolic_write_start_addr == -1) {
// Instruction does not write a symbolic write to memory. No need to check this.
continue;
}
int64_t symbolic_write_end_addr = sym_instr_it->mem_write_addr + sym_instr_it->mem_write_size;
if ((curr_write_start_addr <= symbolic_write_start_addr) && (symbolic_write_end_addr <= curr_write_end_addr)) {
// Currrent write fully overwrites the previous written symbolic value and so the symbolic write
// instruction need not be re-executed
// TODO: How to handle partial overwrite?
// TODO: If this block is not fully executed in unicorn before control returns to python land,
// the state will be inconsistent until this concrete memory write is executed. If this happens,
// the symbolic memory write should be removed from list of instructions to re-execute in commit.
instrs_to_erase_it.emplace_back(sym_instr_it);
}
}
for (auto &instr_to_erase_it: instrs_to_erase_it) {
block.symbolic_instrs.erase(instr_to_erase_it);
}
}
}
if (data == NULL) {
for (auto i = start; i <= end; i++) {
record.previous_taint.push_back(bitmap[i]);
if (is_dst_symbolic) {
// Don't mark as TAINT_DIRTY since we don't want to sync it back to angr
// Also, no need to set clean: rollback will set it to TAINT_NONE which
// is fine for symbolic bytes and rollback is called when exiting unicorn
// due to an error encountered
bitmap[i] = TAINT_SYMBOLIC;
}
else if (bitmap[i] != TAINT_DIRTY) {
bitmap[i] = TAINT_DIRTY;
}
}
}
else {
for (auto i = start; i <= end; i++) {
record.previous_taint.push_back(bitmap[i]);
if (is_dst_symbolic) {
// Don't mark as TAINT_DIRTY since we don't want to sync it back to angr
// Also, no need to set clean: rollback will set it to TAINT_NONE which
// is fine for symbolic bytes and rollback is called when exiting unicorn
// due to an error encountered
bitmap[i] = TAINT_SYMBOLIC;
}
else if (bitmap[i] != TAINT_NONE) {
bitmap[i] = TAINT_NONE;
}
}
}
mem_writes.push_back(record);
}
void State::compute_slice_of_instr(instr_details_t &instr) {
// Compute block slice of instruction needed to setup concrete registers needed by it and also save values of
// registers not changed from start of the block
std::unordered_set<address_t> instrs_to_process;
bool all_dep_regs_concrete = false;
auto &block_taint_entry = block_taint_cache.at(curr_block_details.block_addr);
auto &instr_taint_entry = block_taint_entry.block_instrs_taint_data_map.at(instr.instr_addr);
// Save values of registers not modified from start of block till instruction
auto instr_concrete_regs_it = block_instr_concrete_regs.find(instr.instr_addr);
if (instr_concrete_regs_it == block_instr_concrete_regs.end()) {
// No entry for current instruction in list of concrete regs => all registers were concrete
// An entry was not added because no symbolic taint was present to propagate
all_dep_regs_concrete = true;
}
for (auto &dependency: instr_taint_entry.unmodified_dep_regs) {
if (!is_valid_dependency_register(dependency.first) ||
(!all_dep_regs_concrete && instr_concrete_regs_it->second.count(dependency.first) == 0)) {
// Register is not a valid dependency or was not concrete before instruction was executed. Do not save value.
continue;
}
auto reg_offset = dependency.first;
auto reg_size = dependency.second;
auto reg_val = block_start_reg_values.at(reg_offset);
reg_val.size = reg_size;
instr.reg_deps.insert(reg_val);
}
// List of instructions modifying a register dependency. Their slice needs to be computed.
for (auto &dep_reg_modifier: instr_taint_entry.dep_reg_modifier_addr) {
if (!all_dep_regs_concrete && instr_concrete_regs_it->second.count(dep_reg_modifier.first) == 0) {
// Register was not concrete before instruction was executed. Do not compute slice.
continue;
}
instrs_to_process.emplace(dep_reg_modifier.second);
}
// List of instructions modifying a VEX temp dependency. Their slice needs to be computed.
for (auto &dependency: instr_taint_entry.dependencies.at(TAINT_ENTITY_TMP)) {
auto vex_temp_deps_entry = block_taint_entry.vex_temp_deps.find(dependency);
if (vex_temp_deps_entry == block_taint_entry.vex_temp_deps.end()) {
// No dependency entries for this VEX temp
continue;
}
address_t vex_setter_instr = vex_temp_deps_entry->second.first;
if ((vex_setter_instr != instr.instr_addr) && !is_symbolic_temp(dependency.tmp_id)) {
instrs_to_process.emplace(vex_setter_instr);
}
}
for (auto &instr_to_process_addr: instrs_to_process) {
auto &instr_to_process_taint_entry = block_taint_entry.block_instrs_taint_data_map.at(instr_to_process_addr);
instr_details_t instr_details = compute_instr_details(instr_to_process_addr, instr_to_process_taint_entry);
compute_slice_of_instr(instr_details);
instr.reg_deps.insert(instr_details.reg_deps.begin(), instr_details.reg_deps.end());
instr.instr_deps.insert(instr_details.instr_deps.begin(), instr_details.instr_deps.end());
instr_details.reg_deps.clear();
instr_details.instr_deps.clear();
instr.instr_deps.insert(instr_details);
}
return;
}
void State::process_vex_block(IRSB *vex_block, address_t address) {
block_taint_entry_t block_taint_entry;
instruction_taint_entry_t instruction_taint_entry;
bool started_processing_instructions;
address_t curr_instr_addr;
std::unordered_map<vex_reg_offset_t, address_t> last_reg_modifier_instr;
std::unordered_set<vex_reg_offset_t> modified_regs;
started_processing_instructions = false;
block_taint_entry.has_unsupported_stmt_or_expr_type = false;
for (auto i = 0; i < vex_block->stmts_used; i++) {
auto stmt = vex_block->stmts[i];
switch (stmt->tag) {
case Ist_Put:
{
taint_entity_t sink;
std::unordered_set<taint_entity_t> srcs;
sink.entity_type = TAINT_ENTITY_REG;
sink.instr_addr = curr_instr_addr;
sink.reg_offset = stmt->Ist.Put.offset;
auto result = process_vex_expr(stmt->Ist.Put.data, vex_block->tyenv, curr_instr_addr, false);
if (result.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = result.unsupported_expr_stop_reason;
break;
}
sink.value_size = result.value_size;
// Flatten list of taint sources and also save them as dependencies of instruction
// TODO: Should we not save dependencies if sink is an artificial register?
for (auto &entry: result.taint_sources) {
srcs.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
instruction_taint_entry.taint_sink_src_map.emplace_back(sink, srcs);
instruction_taint_entry.mem_read_size += result.mem_read_size;
instruction_taint_entry.has_memory_read |= (result.mem_read_size != 0);
// Store ITE condition entities. Also, store them as dependencies of instruction.
for (auto &entry: result.ite_cond_entities) {
instruction_taint_entry.ite_cond_entity_list.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
// Mark this register as modified by this instruction for updating register setter later
modified_regs.emplace(sink.reg_offset);
break;
}
case Ist_WrTmp:
{
taint_entity_t sink;
std::unordered_set<taint_entity_t> srcs;
sink.entity_type = TAINT_ENTITY_TMP;
sink.instr_addr = curr_instr_addr;
sink.tmp_id = stmt->Ist.WrTmp.tmp;
auto sink_type = vex_block->tyenv->types[sink.tmp_id];
if (sink_type == Ity_I1) {
sink.value_size = 0;
}
else {
sink.value_size = sizeofIRType(sink_type);
}
auto result = process_vex_expr(stmt->Ist.WrTmp.data, vex_block->tyenv, curr_instr_addr, false);
if (result.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = result.unsupported_expr_stop_reason;
break;
}
// Store VEX temp dependencies details
auto vex_temp_dep_data = std::make_pair(curr_instr_addr, result.taint_sources.at(TAINT_ENTITY_TMP));
auto &vex_temp_ite_deps = result.ite_cond_entities.at(TAINT_ENTITY_TMP);
vex_temp_dep_data.second.insert(vex_temp_ite_deps.begin(), vex_temp_ite_deps.end());
for (auto &mem_taint_source: result.taint_sources.at(TAINT_ENTITY_MEM)) {
for (auto &mem_ref_entity: mem_taint_source.mem_ref_entity_list) {
instruction_taint_entry.dependencies.at(mem_ref_entity.entity_type).emplace(mem_ref_entity);
if (mem_ref_entity.entity_type ==TAINT_ENTITY_TMP) {
vex_temp_dep_data.second.emplace(mem_ref_entity);
}
}
}
block_taint_entry.vex_temp_deps.emplace(sink, vex_temp_dep_data);
// Flatten list of taint sources and also save them as dependencies of instruction
for (auto &entry: result.taint_sources) {
srcs.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
instruction_taint_entry.taint_sink_src_map.emplace_back(sink, srcs);
instruction_taint_entry.mem_read_size += result.mem_read_size;
instruction_taint_entry.has_memory_read |= (result.mem_read_size != 0);
// Store ITE condition entities. Also, store them as dependencies of instruction.
for (auto &entry: result.ite_cond_entities) {
instruction_taint_entry.ite_cond_entity_list.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
break;
}
case Ist_Store:
{
taint_entity_t sink;
std::unordered_set<taint_entity_t> srcs;
sink.entity_type = TAINT_ENTITY_MEM;
sink.instr_addr = curr_instr_addr;
instruction_taint_entry.has_memory_write = true;
auto result = process_vex_expr(stmt->Ist.Store.addr, vex_block->tyenv, curr_instr_addr, false);
if (result.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = result.unsupported_expr_stop_reason;
break;
}
// TODO: What if memory addresses have ITE expressions in them?
for (auto &entry: result.taint_sources) {
sink.mem_ref_entity_list.insert(sink.mem_ref_entity_list.end(), entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
instruction_taint_entry.mem_read_size += result.mem_read_size;
instruction_taint_entry.has_memory_read |= (result.mem_read_size != 0);
result = process_vex_expr(stmt->Ist.Store.data, vex_block->tyenv, curr_instr_addr, false);
if (result.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = result.unsupported_expr_stop_reason;
break;
}
sink.value_size = result.value_size;
// Flatten list of taint sources and also save them as dependencies of instruction
for (auto &entry: result.taint_sources) {
srcs.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
instruction_taint_entry.taint_sink_src_map.emplace_back(sink, srcs);
instruction_taint_entry.mem_read_size += result.mem_read_size;
instruction_taint_entry.has_memory_read |= (result.mem_read_size != 0);
// Store ITE condition entities. Also, store them as dependencies of instruction.
for (auto &entry: result.ite_cond_entities) {
instruction_taint_entry.ite_cond_entity_list.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
break;
}
case Ist_Exit:
{
auto result = process_vex_expr(stmt->Ist.Exit.guard, vex_block->tyenv, curr_instr_addr, true);
if (result.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = result.unsupported_expr_stop_reason;
break;
}
for (auto &entry: result.taint_sources) {
block_taint_entry.exit_stmt_guard_expr_deps.insert(entry.second.begin(), entry.second.end());
}
block_taint_entry.exit_stmt_instr_addr = curr_instr_addr;
instruction_taint_entry.mem_read_size += result.mem_read_size;
instruction_taint_entry.has_memory_read |= (result.mem_read_size != 0);
break;
}
case Ist_IMark:
{
// Save dependencies of previous instruction and clear it
if (started_processing_instructions) {
for (auto &dep: instruction_taint_entry.dependencies.at(TAINT_ENTITY_REG)) {
auto entry = last_reg_modifier_instr.find(dep.reg_offset);
if (entry != last_reg_modifier_instr.end()) {
instruction_taint_entry.dep_reg_modifier_addr.emplace(dep.reg_offset, entry->second);
}
else {
instruction_taint_entry.unmodified_dep_regs.emplace(dep.reg_offset, dep.value_size);
}
}
// Update last modified instruction address for registers modified by this instruction
for (auto &modified_reg: modified_regs) {
auto last_modifier_entry = last_reg_modifier_instr.find(modified_reg);
if (last_modifier_entry == last_reg_modifier_instr.end()) {
last_reg_modifier_instr.emplace(modified_reg, curr_instr_addr);
}
else {
last_modifier_entry->second = curr_instr_addr;
}
}
modified_regs.clear();
// TODO: Many instructions will not have dependencies. Can we save memory by not storing info for them?
block_taint_entry.block_instrs_taint_data_map.emplace(curr_instr_addr, instruction_taint_entry);
}
instruction_taint_entry.reset();
curr_instr_addr = stmt->Ist.IMark.addr;
started_processing_instructions = true;
break;
}
case Ist_PutI:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_PUTI;
break;
}
case Ist_StoreG:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_STOREG;
break;
}
case Ist_LoadG:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_LOADG;
break;
}
case Ist_CAS:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_CAS;
break;
}
case Ist_LLSC:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_LLSC;
break;
}
case Ist_Dirty:
{
// TODO
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_DIRTY;
if (strcasestr(stmt->Ist.Dirty.details->cee->name, "cpuid")) {
block_taint_entry.has_cpuid_instr = true;
}
break;
}
case Ist_MBE:
case Ist_NoOp:
case Ist_AbiHint:
break;
default:
{
fprintf(stderr, "[sim_unicorn] Unsupported statement type encountered: ");
fprintf(stderr, "Block: 0x%zx, statement index: %d, statement type: %u\n", address, i, stmt->tag);
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = STOP_UNSUPPORTED_STMT_UNKNOWN;
break;
}
}
}
// Process block default exit target
auto block_next_taint_sources = process_vex_expr(vex_block->next, vex_block->tyenv, curr_instr_addr, false);
if (block_next_taint_sources.has_unsupported_expr) {
block_taint_entry.has_unsupported_stmt_or_expr_type = true;
block_taint_entry.unsupported_stmt_stop_reason = block_next_taint_sources.unsupported_expr_stop_reason;
}
else {
for (auto &entry: block_next_taint_sources.taint_sources) {
block_taint_entry.block_next_entities.insert(entry.second.begin(), entry.second.end());
instruction_taint_entry.dependencies.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
instruction_taint_entry.mem_read_size += block_next_taint_sources.mem_read_size;
instruction_taint_entry.has_memory_read |= (block_next_taint_sources.mem_read_size != 0);
}
// Save last instruction's entry
block_taint_entry.block_instrs_taint_data_map.emplace(curr_instr_addr, instruction_taint_entry);
block_taint_cache.emplace(address, block_taint_entry);
return;
}
std::set<instr_details_t> State::get_list_of_dep_instrs(const instr_details_t &instr) const {
std::set<instr_details_t> instrs;
for (auto &dep_instr: instr.instr_deps) {
auto result = get_list_of_dep_instrs(dep_instr);
instrs.insert(result.begin(), result.end());
instrs.insert(dep_instr);
}
return instrs;
}
void State::get_register_value(uint64_t vex_reg_offset, uint8_t *out_reg_value) const {
uint64_t reg_value;
if (cpu_flags_register != -1) {
// Check if VEX register is actually a CPU flag
auto cpu_flags_entry = cpu_flags.find(vex_reg_offset);
if (cpu_flags_entry != cpu_flags.end()) {
uc_reg_read(uc, cpu_flags_register, ®_value);
if ((reg_value & cpu_flags_entry->second) == 1) {
// This hack assumes that a flag register is not MAX_REGISTER_BYTE_SIZE bytes long
// so that it works on both big and little endian registers.
out_reg_value[0] = 1;
out_reg_value[MAX_REGISTER_BYTE_SIZE - 1] = 1;
}
return;
}
}
uc_reg_read(uc, vex_to_unicorn_map.at(vex_reg_offset), out_reg_value);
return;
}
// Returns a pair (taint sources, list of taint entities in ITE condition expression)
processed_vex_expr_t State::process_vex_expr(IRExpr *expr, IRTypeEnv *vex_block_tyenv, address_t instr_addr, bool is_exit_stmt) {
processed_vex_expr_t result;
result.reset();
switch (expr->tag) {
case Iex_RdTmp:
{
taint_entity_t taint_entity;
taint_entity.entity_type = TAINT_ENTITY_TMP;
taint_entity.tmp_id = expr->Iex.RdTmp.tmp;
taint_entity.instr_addr = instr_addr;
taint_entity.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
result.taint_sources.at(TAINT_ENTITY_TMP).emplace(taint_entity);
result.value_size = taint_entity.value_size;
break;
}
case Iex_Get:
{
taint_entity_t taint_entity;
taint_entity.entity_type = TAINT_ENTITY_REG;
taint_entity.reg_offset = expr->Iex.Get.offset;
taint_entity.instr_addr = instr_addr;
taint_entity.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
result.taint_sources.at(TAINT_ENTITY_REG).emplace(taint_entity);
result.value_size = taint_entity.value_size;
break;
}
case Iex_Unop:
{
auto temp = process_vex_expr(expr->Iex.Unop.arg, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);;
break;
}
case Iex_Binop:
{
auto temp = process_vex_expr(expr->Iex.Binop.arg1, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Binop.arg2, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);;
break;
}
case Iex_Triop:
{
auto temp = process_vex_expr(expr->Iex.Triop.details->arg1, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Triop.details->arg2, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Triop.details->arg3, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_Qop:
{
auto temp = process_vex_expr(expr->Iex.Qop.details->arg1, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Qop.details->arg2, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Qop.details->arg3, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.Qop.details->arg4, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_ITE:
{
// We store the taint entities in the condition for ITE separately in order to check
// if condition is symbolic and stop concrete execution if it is. However for VEX
// exit statement, we don't need to store it separately since we process only the
// guard condition for Exit statements
auto temp = process_vex_expr(expr->Iex.ITE.cond, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
if (is_exit_stmt) {
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
}
else {
for (auto &entry: temp.taint_sources) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.ITE.iffalse, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
temp = process_vex_expr(expr->Iex.ITE.iftrue, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_CCall:
{
IRExpr **ccall_args = expr->Iex.CCall.args;
for (auto i = 0; ccall_args[i]; i++) {
auto temp = process_vex_expr(ccall_args[i], vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
for (auto &entry: temp.taint_sources) {
result.taint_sources.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
for (auto &entry: temp.ite_cond_entities) {
result.ite_cond_entities.at(entry.first).insert(entry.second.begin(), entry.second.end());
}
result.mem_read_size += temp.mem_read_size;
}
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_Load:
{
auto temp = process_vex_expr(expr->Iex.Load.addr, vex_block_tyenv, instr_addr, false);
if (temp.has_unsupported_expr) {
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = temp.unsupported_expr_stop_reason;
break;
}
// TODO: What if memory addresses have ITE expressions in them?
taint_entity_t source;
source.entity_type = TAINT_ENTITY_MEM;
for (auto &entry: temp.taint_sources) {
source.mem_ref_entity_list.insert(source.mem_ref_entity_list.end(), entry.second.begin(), entry.second.end());
}
source.instr_addr = instr_addr;
result.taint_sources.at(TAINT_ENTITY_MEM).emplace(source);
// Calculate number of bytes read. unicorn sometimes triggers read hook multiple times for the same read
result.mem_read_size += temp.mem_read_size;
// TODO: Will there be a 1 bit read from memory?
auto load_size = sizeofIRType(expr->Iex.Load.ty);
result.mem_read_size += load_size;
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_GetI:
{
// TODO
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = STOP_UNSUPPORTED_EXPR_GETI;
break;
}
case Iex_Const:
{
result.value_size = get_vex_expr_result_size(expr, vex_block_tyenv);
break;
}
case Iex_VECRET:
case Iex_GSPTR:
case Iex_Binder:
break;
default:
{
fprintf(stderr, "[sim_unicorn] Unsupported expression type encountered: %u\n", expr->tag);
result.has_unsupported_expr = true;
result.unsupported_expr_stop_reason = STOP_UNSUPPORTED_EXPR_UNKNOWN;
break;
}
}
return result;
}
// Determine cumulative result of taint statuses of a set of taint entities
// EG: This is useful to determine the taint status of a taint sink given it's taint sources
taint_status_result_t State::get_final_taint_status(const std::unordered_set<taint_entity_t> &taint_sources) const {
bool is_symbolic = false;
for (auto &taint_source: taint_sources) {
if (taint_source.entity_type == TAINT_ENTITY_NONE) {
continue;
}
else if ((taint_source.entity_type == TAINT_ENTITY_REG) &&
(is_symbolic_register(taint_source.reg_offset, taint_source.value_size))) {
// Register is symbolic. Continue checking for read from symbolic address
is_symbolic = true;
}
else if ((taint_source.entity_type == TAINT_ENTITY_TMP) && (is_symbolic_temp(taint_source.tmp_id))) {
// Temp is symbolic. Continue checking for read from a symbolic address
is_symbolic = true;
}
else if (taint_source.entity_type == TAINT_ENTITY_MEM) {
// Check if the memory address being read from is symbolic
auto mem_address_status = get_final_taint_status(taint_source.mem_ref_entity_list);
if (mem_address_status == TAINT_STATUS_SYMBOLIC) {
// Address is symbolic. We have to stop concrete execution and so can stop analysing
return TAINT_STATUS_DEPENDS_ON_READ_FROM_SYMBOLIC_ADDR;
}
else {
// Address is concrete so we check result of the memory read
mem_read_result_t mem_read_result;
try {
mem_read_result = block_mem_reads_map.at(taint_source.instr_addr);
}
catch (std::out_of_range const&) {
assert(false && "[sim_unicorn] Taint sink depends on a read not executed yet! This should not happen!");
}
is_symbolic = mem_read_result.is_mem_read_symbolic;
}
}
}
if (is_symbolic) {
return TAINT_STATUS_SYMBOLIC;
}
return TAINT_STATUS_CONCRETE;
}
// A vector version of get_final_taint_status for checking mem_ref_entity_list which can't be an
// unordered_set
taint_status_result_t State::get_final_taint_status(const std::vector<taint_entity_t> &taint_sources) const {
std::unordered_set<taint_entity_t> taint_sources_set(taint_sources.begin(), taint_sources.end());
return get_final_taint_status(taint_sources_set);
}
int32_t State::get_vex_expr_result_size(IRExpr *expr, IRTypeEnv* tyenv) const {
auto expr_type = typeOfIRExpr(tyenv, expr);
if (expr_type == Ity_I1) {
return 0;
}
return sizeofIRType(expr_type);
}
bool State::is_cpuid_in_block(address_t block_address, int32_t block_size) {
bool found_cpuid_bytes = false;
bool has_cpuid_instr = false;
int32_t real_size;
int32_t i;
const uint8_t cpuid_bytes[] = {0xf, 0xa2};
auto block_entry = block_taint_cache.find(block_address);
if (block_entry != block_taint_cache.end()) {
// VEX statements of block have been processed already.
return block_entry->second.has_cpuid_instr;
}
// Assume block size is MAX_BB_SIZE if block size is report as 0.
// See State::step
real_size = block_size == 0 ? MAX_BB_SIZE : block_size;
std::unique_ptr<uint8_t[]> instructions(new uint8_t[real_size]);
uc_mem_read(this->uc, block_address, instructions.get(), real_size);
// Test 1: Look for bytes corresponding to the cpuid instruction(0fa2) in the block. Naive linear search for two
// byte pattern
i = 0;
while (i < real_size) {
if (instructions[i] == cpuid_bytes[0]) {
if (instructions[i + 1] == cpuid_bytes[1]) {
found_cpuid_bytes = true;
break;
}
i ++;
}
i++;
}
if (!found_cpuid_bytes) {
return false;
}
// Test 2: Verify using VEX statements of the block. If we reached here, then block is certainly not already lifted
// to VEX. Let's process them.
auto vex_lift_result = lift_block(block_address, real_size);
if ((vex_lift_result == NULL) || (vex_lift_result->size == 0)) {
// Since VEX lift failed, we cannot verify if cpuid is present. Assume it could exit and stop emulation.
stop(STOP_VEX_LIFT_FAILED);
return true;
}
process_vex_block(vex_lift_result->irsb, block_address);
block_entry = block_taint_cache.find(block_address);
has_cpuid_instr = block_entry->second.has_cpuid_instr;
if (block_size == 0) {
// Remove block from block taint cache since size reported by unicorn is 0
block_taint_cache.erase(block_entry);
}
return has_cpuid_instr;
}
VEXLiftResult* State::lift_block(address_t block_address, int32_t block_size) {
VexRegisterUpdates pxControl = VexRegUpdUnwindregsAtMemAccess;
std::unique_ptr<uint8_t[]> instructions(new uint8_t[block_size]);
address_t lift_address;
if ((arch == UC_ARCH_ARM) && is_thumb_mode()) {
lift_address = block_address | 1;
}
else {
lift_address = block_address;
}
uc_mem_read(this->uc, lift_address, instructions.get(), block_size);
return vex_lift(vex_guest, vex_archinfo, instructions.get(), lift_address, 99, block_size, 1, 0, 1, 1, 0,
pxControl, 0);
}
void State::mark_register_symbolic(vex_reg_offset_t reg_offset, int64_t reg_size) {
// Mark register as symbolic in the state in current block
if (is_blacklisted_register(reg_offset)) {
return;
}
else if (cpu_flags.find(reg_offset) != cpu_flags.end()) {
block_symbolic_registers.emplace(reg_offset);
block_concrete_registers.erase(reg_offset);
}
else {
for (auto i = 0; i < reg_size; i++) {
block_symbolic_registers.emplace(reg_offset + i);
block_concrete_registers.erase(reg_offset + i);
}
}
return;
}
void State::mark_temp_symbolic(vex_tmp_id_t temp_id) {
// Mark VEX temp as symbolic in current block
block_symbolic_temps.emplace(temp_id);
return;
}
void State::mark_register_concrete(vex_reg_offset_t reg_offset, int64_t reg_size) {
// Mark register as concrete in the current block
if (is_blacklisted_register(reg_offset)) {
return;
}
else if (cpu_flags.find(reg_offset) != cpu_flags.end()) {
block_symbolic_registers.erase(reg_offset);
block_concrete_registers.emplace(reg_offset);
}
else {
for (auto i = 0; i < reg_size; i++) {
block_symbolic_registers.erase(reg_offset + i);
block_concrete_registers.emplace(reg_offset + i);
}
}
return;
}
bool State::is_symbolic_register(vex_reg_offset_t reg_offset, int64_t reg_size) const {
// We check if this register is symbolic or concrete in the block level taint statuses since
// those are more recent. If not found in either, check the state's symbolic register list.
// TODO: Is checking only first byte of artificial and blacklisted registers to determine if they are symbolic fine
// or should all be checked?
if ((cpu_flags.find(reg_offset) != cpu_flags.end()) || (artificial_vex_registers.count(reg_offset) > 0)
|| (blacklisted_registers.count(reg_offset) > 0)) {
if (block_symbolic_registers.count(reg_offset) > 0) {
return true;
}
else if (block_concrete_registers.count(reg_offset) > 0) {
return false;
}
else if (symbolic_registers.count(reg_offset) > 0) {
return true;
}
return false;
}
// The register is not a CPU flag and so we check every byte of the register
for (auto i = 0; i < reg_size; i++) {
// If any of the register's bytes are symbolic, we deem the register to be symbolic
if (block_symbolic_registers.count(reg_offset + i) > 0) {
return true;
}
}
bool is_concrete = true;
for (auto i = 0; i < reg_size; i++) {
if (block_concrete_registers.count(reg_offset) == 0) {
is_concrete = false;
break;
}
}
if (is_concrete) {
// All bytes of register are concrete and so the register is concrete
return false;
}
// If we reach here, it means that the register is not marked symbolic or concrete in the block
// level taint status tracker. We check the state's symbolic register list.
for (auto i = 0; i < reg_size; i++) {
if (symbolic_registers.count(reg_offset + i) > 0) {
return true;
}
}
return false;
}
bool State::is_symbolic_temp(vex_tmp_id_t temp_id) const {
return (block_symbolic_temps.count(temp_id) > 0);
}
void State::propagate_taints() {
if (is_symbolic_tracking_disabled()) {
// We're not checking symbolic registers so no need to propagate taints
return;
}
auto& block_taint_entry = this->block_taint_cache.at(curr_block_details.block_addr);
if (((symbolic_registers.size() > 0) || (block_symbolic_registers.size() > 0))
&& block_taint_entry.has_unsupported_stmt_or_expr_type) {
// There are symbolic registers and VEX statements in block for which taint propagation
// is not supported. Stop concrete execution.
stop(block_taint_entry.unsupported_stmt_stop_reason);
return;
}
// Resume propagating taints using symbolic_registers and symbolic_temps from where we paused
auto instr_taint_data_entries_it = block_taint_entry.block_instrs_taint_data_map.find(taint_engine_next_instr_address);
auto instr_taint_data_stop_it = block_taint_entry.block_instrs_taint_data_map.end();
// We continue propagating taint until we encounter 1) a memory read, 2) end of block or
// 3) a stop state for concrete execution
for (; instr_taint_data_entries_it != instr_taint_data_stop_it && !stopped; ++instr_taint_data_entries_it) {
address_t curr_instr_addr = instr_taint_data_entries_it->first;
auto& curr_instr_taint_entry = instr_taint_data_entries_it->second;
std::unordered_map<vex_reg_offset_t, int64_t> concrete_reg_deps;
// Save list of register dependencies of current instruction which are concrete for slice computation later
for (auto ®_dep: curr_instr_taint_entry.dependencies.at(TAINT_ENTITY_REG)) {
if (!is_symbolic_register(reg_dep.reg_offset, reg_dep.value_size)) {
concrete_reg_deps.emplace(std::make_pair(reg_dep.reg_offset, reg_dep.value_size));
}
}
block_instr_concrete_regs.emplace(curr_instr_addr, concrete_reg_deps);
if (curr_instr_taint_entry.has_memory_read) {
// Pause taint propagation to process the memory read and continue from instruction
// after the memory read.
taint_engine_stop_mem_read_instruction = curr_instr_addr;
taint_engine_stop_mem_read_size = instr_taint_data_entries_it->second.mem_read_size;
taint_engine_next_instr_address = std::next(instr_taint_data_entries_it)->first;
return;
}
if ((symbolic_registers.size() == 0) && (block_symbolic_registers.size() == 0) && (block_symbolic_temps.size() == 0)) {
// There are no symbolic registers so no taint to propagate. Mark any memory writes
// as concrete and update slice of registers.
if (curr_instr_taint_entry.has_memory_write) {
mem_writes_taint_map.emplace(curr_instr_addr, false);
}
continue;
}
propagate_taint_of_one_instr(curr_instr_addr, curr_instr_taint_entry);
}
// If we reached here, execution has reached the end of the block
if (!stopped) {
if (curr_block_details.vex_lift_failed && ((symbolic_registers.size() > 0) || (block_symbolic_registers.size() > 0))) {
// There are symbolic registers but VEX lift failed so we can't determine
// status of guard condition
stop(STOP_VEX_LIFT_FAILED);
return;
}
else if (is_block_exit_guard_symbolic()) {
stop(STOP_SYMBOLIC_BLOCK_EXIT_CONDITION);
}
else if (is_block_next_target_symbolic()) {
stop(STOP_SYMBOLIC_BLOCK_EXIT_TARGET);
}
}
return;
}
void State::propagate_taint_of_mem_read_instr_and_continue(address_t read_address, int read_size) {
memory_value_t memory_read_value;
address_t curr_instr_addr;
auto tainted = find_tainted(read_address, read_size);
if (is_symbolic_tracking_disabled()) {
if (tainted != -1) {
// Symbolic register tracking is disabled but memory location has symbolic data.
// We switch to VEX engine then.
stop(STOP_SYMBOLIC_READ_SYMBOLIC_TRACKING_DISABLED);
return;
}
// We're not checking symbolic registers so no need to propagate taints
return;
}
// Save info about the memory read
memory_read_value.reset();
memory_read_value.address = read_address;
memory_read_value.size = read_size;
if (tainted != -1) {
memory_read_value.is_value_symbolic = true;
}
else {
memory_read_value.is_value_symbolic = false;
read_memory_value(read_address, read_size, memory_read_value.value, MAX_MEM_ACCESS_SIZE);
}
if (!memory_read_value.is_value_symbolic && !symbolic_read_in_progress && (symbolic_registers.size() == 0) &&
(block_symbolic_registers.size() == 0) && (block_symbolic_temps.size() == 0)) {
// The value read from memory is concrete and there are no symbolic registers or VEX temps. No need to propagate
// taint. Since we cannot rely on the unicorn engine to find out current instruction correctly, we simply save
// the memory read value in a list for now and rebuild the map later if needed using instruction info from VEX
// block
block_mem_reads_data.emplace_back(memory_read_value);
return;
}
if (block_taint_cache.find(curr_block_details.block_addr) == block_taint_cache.end()) {
// The VEX statements of current block has not been processed yet. This means symbolic taint is being introduced
// by this memory read. Let's process the block, rebuild its memory reads map and find the current instruction
// address
curr_block_details.vex_lift_result = lift_block(curr_block_details.block_addr, curr_block_details.block_size);
if ((curr_block_details.vex_lift_result == NULL) || (curr_block_details.vex_lift_result->size == 0)) {
// Failed to lift block to VEX.
if (memory_read_value.is_value_symbolic) {
// Since we are processing VEX block for the first time, there are no symbolic registers/VEX temps.
// Thus, it is sufficient to check if the value read from memory is symbolic.
stop(STOP_VEX_LIFT_FAILED);
}
else {
// There are no symbolic registers so let's attempt to execute the block.
curr_block_details.vex_lift_failed = true;
}
return;
}
process_vex_block(curr_block_details.vex_lift_result->irsb, curr_block_details.block_addr);
}
auto& block_taint_entry = block_taint_cache.at(curr_block_details.block_addr);
if (taint_engine_stop_mem_read_instruction != 0) {
// Taint has been propagated and so we can rely on information from taint engine to find current instruction
// address and hence update the block's memory reads map
curr_instr_addr = taint_engine_stop_mem_read_instruction;
}
else {
// Symbolic taint is being introduced by this memory read so we cannot rely on taint engine to find current
// instruction address
std::map<address_t, instruction_taint_entry_t>::iterator instr_entry_it = block_taint_entry.block_instrs_taint_data_map.begin();
if (block_mem_reads_data.size() > 0) {
// There are previous reads that need to be insert into block's memory reads map
while (instr_entry_it != block_taint_entry.block_instrs_taint_data_map.end()) {
if (instr_entry_it->second.has_memory_read) {
mem_read_result_t mem_read_result;
while (block_mem_reads_data.size() != 0) {
auto &next_mem_read = block_mem_reads_data.front();
mem_read_result.memory_values.emplace_back(next_mem_read);
mem_read_result.is_mem_read_symbolic |= next_mem_read.is_value_symbolic;
mem_read_result.read_size += next_mem_read.size;
block_mem_reads_data.erase(block_mem_reads_data.begin());
if (mem_read_result.read_size == instr_entry_it->second.mem_read_size) {
block_mem_reads_map.emplace(instr_entry_it->first, mem_read_result);
break;
}
}
if (block_mem_reads_data.size() == 0) {
// All pending reads have been processed and inserted into the map
if (block_mem_reads_map.at(instr_entry_it->first).read_size == instr_entry_it->second.mem_read_size) {
// Update iterator since all reads for current instruction have been processed. We should
// start searching for next instruction with memory read from successor of this instruction.
instr_entry_it++;
}
else {
// There are still more reads pending for this instruction. Insert partial result value into the
// block's memory reads map
block_mem_reads_map.emplace(instr_entry_it->first, mem_read_result);
}
break;
}
}
instr_entry_it++;
}
if ((block_mem_reads_data.size() != 0) && (instr_entry_it == block_taint_entry.block_instrs_taint_data_map.end())) {
// There are still some pending reads but all instructions in the block have been processed. Something
// is wrong.
assert(false && "There are pending memory reads to process but full block has been processed. This should not happen!");
}
}
// Find next instruction with memory read
while (!instr_entry_it->second.has_memory_read) {
instr_entry_it++;
if (instr_entry_it == block_taint_entry.block_instrs_taint_data_map.end()) {
// Current read does not belong to any possible instruction in current block. This should not happen!
assert(false && "Unable to identify instruction for current memory read. This should not happen!");
}
}
curr_instr_addr = instr_entry_it->first;
taint_engine_stop_mem_read_instruction = curr_instr_addr;
taint_engine_stop_mem_read_size = instr_entry_it->second.mem_read_size;
taint_engine_next_instr_address = std::next(instr_entry_it)->first;
}
auto mem_reads_map_entry = block_mem_reads_map.find(curr_instr_addr);
if (mem_reads_map_entry == block_mem_reads_map.end()) {
mem_read_result_t mem_read_result;
mem_read_result.memory_values.emplace_back(memory_read_value);
mem_read_result.is_mem_read_symbolic = memory_read_value.is_value_symbolic;
mem_read_result.read_size = read_size;
block_mem_reads_map.emplace(curr_instr_addr, mem_read_result);
}
else {
auto &mem_read_entry = block_mem_reads_map.at(curr_instr_addr);
mem_read_entry.memory_values.emplace_back(memory_read_value);
mem_read_entry.is_mem_read_symbolic |= memory_read_value.is_value_symbolic;
mem_read_entry.read_size += read_size;
}
// At this point the block's memory reads map has been rebuilt and we can propagate taint as before
auto &mem_read_result = block_mem_reads_map.at(curr_instr_addr);
if (curr_block_details.vex_lift_failed) {
if (mem_read_result.is_mem_read_symbolic || (symbolic_registers.size() > 0)
|| (block_symbolic_registers.size() > 0) || (block_symbolic_temps.size() > 0)) {
// Either the memory value is symbolic or there are symbolic registers: thus, taint
// status of registers could change. But since VEX lift failed, the taint relations
// are not known and so we can't propagate taint. Stop concrete execution.
stop(STOP_VEX_LIFT_FAILED);
return;
}
else {
// We cannot propagate taint since VEX lift failed and so we stop here. But, since
// there are no symbolic values, we do need need to propagate taint.
return;
}
}
if (mem_read_result.read_size < taint_engine_stop_mem_read_size) {
// There are more bytes to be read by this instruction. We do not propagate taint until bytes are read
// Sometimes reads are split across multiple reads hooks in unicorn.
// Also, remember that a symbolic value has been partially read from memory so that even if the rest of the
// bytes to be read are concrete, taint will be propagated.
symbolic_read_in_progress = true;
return;
}
else if (mem_read_result.read_size > taint_engine_stop_mem_read_size) {
// Somehow the read result has read more bytes than read operation should according to the VEX statements.
// Likely a bug.
assert(false && "Memory read operation has read more bytes than expected. This should not happen!");
}
// Mark read as complete
symbolic_read_in_progress = false;
// There are no more pending reads at this instruction. Now we can propagate taint.
// This allows us to also handle cases when only some of the memory reads are symbolic: we treat all as symbolic
// and overtaint.
auto& instr_taint_data_entry = block_taint_entry.block_instrs_taint_data_map.at(curr_instr_addr);
if (mem_read_result.is_mem_read_symbolic || (symbolic_registers.size() > 0) || (block_symbolic_registers.size() > 0) ||
block_symbolic_temps.size() > 0) {
if (block_taint_entry.has_unsupported_stmt_or_expr_type) {
// There are symbolic registers and/or memory read was symbolic and there are VEX
// statements in block for which taint propagation is not supported.
stop(block_taint_entry.unsupported_stmt_stop_reason);
return;
}
propagate_taint_of_one_instr(curr_instr_addr, instr_taint_data_entry);
}
if (!stopped) {
continue_propagating_taint();
}
return;
}
void State::propagate_taint_of_one_instr(address_t instr_addr, const instruction_taint_entry_t &instr_taint_entry) {
instr_details_t instr_details;
bool is_instr_symbolic;
is_instr_symbolic = false;
instr_details = compute_instr_details(instr_addr, instr_taint_entry);
if (instr_details.has_symbolic_memory_dep) {
is_instr_symbolic = true;
}
for (auto &taint_data_entry: instr_taint_entry.taint_sink_src_map) {
taint_entity_t taint_sink = taint_data_entry.first;
std::unordered_set<taint_entity_t> taint_srcs = taint_data_entry.second;
if (taint_sink.entity_type == TAINT_ENTITY_MEM) {
auto addr_taint_status = get_final_taint_status(taint_sink.mem_ref_entity_list);
// Check if address written to is symbolic or is read from memory
if (addr_taint_status != TAINT_STATUS_CONCRETE) {
stop(STOP_SYMBOLIC_WRITE_ADDR);
return;
}
auto sink_taint_status = get_final_taint_status(taint_srcs);
if (sink_taint_status == TAINT_STATUS_DEPENDS_ON_READ_FROM_SYMBOLIC_ADDR) {
stop(STOP_SYMBOLIC_READ_ADDR);
return;
}
if (sink_taint_status == TAINT_STATUS_SYMBOLIC) {
// Save the memory location written to be marked as symbolic in write hook
// If memory write already exists, we overtaint and mark all writes as symbolic
mem_writes_taint_map[taint_sink.instr_addr] = true;
// Mark instruction as needing symbolic execution
is_instr_symbolic = true;
}
else {
// Save the memory location(s) written to be marked as concrete in the write
// hook only if it is not a previously seen write
mem_writes_taint_map.emplace(taint_sink.instr_addr, false);
}
}
else if (taint_sink.entity_type != TAINT_ENTITY_NONE) {
taint_status_result_t final_taint_status = get_final_taint_status(taint_srcs);
if (final_taint_status == TAINT_STATUS_DEPENDS_ON_READ_FROM_SYMBOLIC_ADDR) {
stop(STOP_SYMBOLIC_READ_ADDR);
return;
}
else if (final_taint_status == TAINT_STATUS_SYMBOLIC) {
if ((taint_sink.entity_type == TAINT_ENTITY_REG) && (taint_sink.reg_offset == arch_pc_reg_vex_offset())) {
stop(STOP_SYMBOLIC_PC);
return;
}
// Mark instruction as needing symbolic execution
is_instr_symbolic = true;
// Mark sink as symbolic
if (taint_sink.entity_type == TAINT_ENTITY_REG) {
mark_register_symbolic(taint_sink.reg_offset, taint_sink.value_size);
}
else {
mark_temp_symbolic(taint_sink.tmp_id);
}
}
else if ((taint_sink.entity_type == TAINT_ENTITY_REG) && (taint_sink.reg_offset != arch_pc_reg_vex_offset())) {
// Mark register as concrete since none of it's dependencies are symbolic.
mark_register_concrete(taint_sink.reg_offset, taint_sink.value_size);
}
}
auto ite_cond_taint_status = get_final_taint_status(instr_taint_entry.ite_cond_entity_list);
if (ite_cond_taint_status != TAINT_STATUS_CONCRETE) {
stop(STOP_SYMBOLIC_CONDITION);
return;
}
}
if (is_instr_symbolic) {
if (instr_details.has_symbolic_memory_dep) {
for (auto &mem_value: block_mem_reads_map.at(instr_addr).memory_values) {
if (mem_value.is_value_symbolic) {
instr_details.symbolic_mem_deps.emplace_back(std::make_pair(mem_value.address, mem_value.size));
}
}
}
curr_block_details.symbolic_instrs.emplace_back(instr_details);
}
return;
}
instr_details_t State::compute_instr_details(address_t instr_addr, const instruction_taint_entry_t &instr_taint_entry) {
instr_details_t instr_details;
instr_details.instr_addr = instr_addr;
if (instr_taint_entry.has_memory_read) {
auto mem_read_result = block_mem_reads_map.at(instr_addr);
if (!mem_read_result.is_mem_read_symbolic) {
instr_details.has_concrete_memory_dep = true;
instr_details.has_symbolic_memory_dep = false;
}
else {
instr_details.has_concrete_memory_dep = false;
instr_details.has_symbolic_memory_dep = true;
}
}
else {
instr_details.has_concrete_memory_dep = false;
instr_details.has_symbolic_memory_dep = false;
}
return instr_details;
}
void State::read_memory_value(address_t address, uint64_t size, uint8_t *result, size_t result_size) const {
memset(result, 0, result_size);
uc_mem_read(uc, address, result, size);
return;
}
void State::start_propagating_taint(address_t block_address, int32_t block_size) {
curr_block_details.block_addr = block_address;
curr_block_details.block_size = block_size;
if (is_symbolic_tracking_disabled()) {
// We're not checking symbolic registers so no need to propagate taints
return;
}
if ((arch == UC_ARCH_ARM) && (block_taint_cache.find(block_address) == block_taint_cache.end())) {
// Block was not lifted and processed before. So it could end in syscall
curr_block_details.vex_lift_result = lift_block(block_address, block_size);
if ((curr_block_details.vex_lift_result == NULL) || (curr_block_details.vex_lift_result->size == 0)) {
// Failed to lift block to VEX. We don't execute the block because it could end in a syscall.
stop(STOP_VEX_LIFT_FAILED);
return;
}
if (curr_block_details.vex_lift_result->irsb->jumpkind == Ijk_Sys_syscall) {
// This block invokes a syscall. For now, such blocks are handled by VEX engine.
stop(STOP_SYSCALL_ARM);
return;
}
}
if ((arch == UC_ARCH_X86) && is_cpuid_in_block(block_address, block_size)) {
// Check if emulation was stopped; could be if VEX lift failed
if (!stopped) {
stop(STOP_X86_CPUID);
}
return;
}
block_symbolic_temps.clear();
block_start_reg_values.clear();
// Save value of all registers in case some instruction touches symbolic data and needs to be re-executed
for (auto ®_offset: vex_to_unicorn_map) {
register_value_t reg_value;
reg_value.offset = reg_offset.first;
memset(reg_value.value, 0, MAX_REGISTER_BYTE_SIZE);
get_register_value(reg_value.offset, reg_value.value);
block_start_reg_values.emplace(reg_value.offset, reg_value);
}
for (auto &cpu_flag: cpu_flags) {
register_value_t flag_value;
flag_value.offset = cpu_flag.first;
memset(flag_value.value, 0, MAX_REGISTER_BYTE_SIZE);
get_register_value(cpu_flag.first, flag_value.value);
block_start_reg_values.emplace(flag_value.offset, flag_value);
}
if (symbolic_registers.size() != 0) {
if (block_taint_cache.find(block_address) == block_taint_cache.end()) {
// Compute and cache taint sink-source relations for this block since there are symbolic registers.
if (curr_block_details.vex_lift_result == NULL) {
curr_block_details.vex_lift_result = lift_block(block_address, block_size);
if ((curr_block_details.vex_lift_result == NULL) || (curr_block_details.vex_lift_result->size == 0)) {
// Failed to lift block to VEX.
if (symbolic_registers.size() > 0) {
// There are symbolic registers but VEX lift failed so we can't propagate taint
stop(STOP_VEX_LIFT_FAILED);
}
else {
// There are no symbolic registers so let's attempt to execute the block.
curr_block_details.vex_lift_failed = true;
}
return;
}
}
process_vex_block(curr_block_details.vex_lift_result->irsb, block_address);
}
taint_engine_next_instr_address = block_address;
propagate_taints();
}
return;
}
void State::continue_propagating_taint() {
if (is_symbolic_tracking_disabled()) {
// We're not checking symbolic registers so no need to propagate taints
return;
}
if (curr_block_details.vex_lift_failed) {
if ((symbolic_registers.size() > 0) || (block_symbolic_registers.size() > 0)) {
// There are symbolic registers but VEX lift failed so we can't propagate taint
stop(STOP_VEX_LIFT_FAILED);
return;
}
}
else {
propagate_taints();
}
return;
}
void State::save_concrete_memory_deps(instr_details_t &instr) {
if (instr.has_concrete_memory_dep) {
archived_memory_values.emplace_back(block_mem_reads_map.at(instr.instr_addr).memory_values);
instr.memory_values = &(archived_memory_values.back()[0]);
instr.memory_values_count = archived_memory_values.back().size();
}
std::queue<std::set<instr_details_t>::iterator> instrs_to_process;
for (auto it = instr.instr_deps.begin(); it != instr.instr_deps.end(); it++) {
instrs_to_process.push(it);
}
while (!instrs_to_process.empty()) {
auto &curr_instr = instrs_to_process.front();
if (curr_instr->has_concrete_memory_dep) {
archived_memory_values.emplace_back(block_mem_reads_map.at(curr_instr->instr_addr).memory_values);
curr_instr->memory_values = &(archived_memory_values.back()[0]);
curr_instr->memory_values_count = archived_memory_values.back().size();
}
instrs_to_process.pop();
for (auto it = curr_instr->instr_deps.begin(); it != curr_instr->instr_deps.end(); *it++) {
instrs_to_process.push(it);
}
}
return;
}
bool State::is_block_exit_guard_symbolic() const {
auto& block_taint_entry = block_taint_cache.at(curr_block_details.block_addr);
auto block_exit_guard_taint_status = get_final_taint_status(block_taint_entry.exit_stmt_guard_expr_deps);
return (block_exit_guard_taint_status != TAINT_STATUS_CONCRETE);
}
bool State::is_block_next_target_symbolic() const {
auto& block_taint_entry = block_taint_cache.at(curr_block_details.block_addr);
auto block_next_target_taint_status = get_final_taint_status(block_taint_entry.block_next_entities);
return (block_next_target_taint_status != TAINT_STATUS_CONCRETE);
}
bool State::check_symbolic_stack_mem_dependencies_liveness() const {
// Stop concrete execution if a stack frame was deallocated and if any symbolic memory dependencies were present
// on that stack frame.
address_t curr_stack_top_addr = get_stack_pointer();
if (curr_stack_top_addr <= prev_stack_top_addr) {
// No change in stack frame and so no need to perform a liveness check.
// TODO: What is stack growth direction is different?
return true;
}
for (auto &block: blocks_with_symbolic_instrs) {
for (auto &symbolic_instr: block.symbolic_instrs) {
for (auto &symbolic_mem_dep: symbolic_instr.symbolic_mem_deps) {
if ((curr_stack_top_addr > symbolic_mem_dep.first) && (symbolic_mem_dep.first > prev_stack_top_addr)) {
// A symbolic memory value that this symbolic instruction depends on is no longer on the stack
// and could be overwritten by future code. We stop concrete execution here to avoid that.
return false;
}
}
}
}
return true;
}
address_t State::get_instruction_pointer() const {
address_t out = 0;
int reg = arch_pc_reg();
if (reg == -1) {
out = 0;
} else {
uc_reg_read(uc, reg, &out);
}
return out;
}
address_t State::get_stack_pointer() const {
address_t out = 0;
int reg = arch_sp_reg();
if (reg == -1) {
out = 0;
} else {
uc_reg_read(uc, reg, &out);
}
return out;
}
static void hook_mem_read(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) {
// uc_mem_read(uc, address, &value, size);
// //LOG_D("mem_read [%#lx, %#lx] = %#lx", address, address + size);
//LOG_D("mem_read [%#lx, %#lx]", address, address + size);
State *state = (State *)user_data;
state->propagate_taint_of_mem_read_instr_and_continue(address, size);
return;
}
/*
* the goal of hooking memory write is to determine the exact
* positions of dirty bytes to writing chaneges back to angr
* state. However if the hook is hit before mapping requested
* page (as writable), we cannot find the bitmap for this page.
* In this case, just mark all the position as clean (before
* this access).
*/
static void hook_mem_write(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) {
//LOG_D("mem_write [%#lx, %#lx]", address, address + size);
State *state = (State *)user_data;
if (state->ignore_next_selfmod) {
// ...the self-modification gets repeated for internal qemu reasons
state->ignore_next_selfmod = false;
} else if ((address >= state->cur_address && address < state->cur_address + state->cur_size) ||
// CODE IS SELF-MODIFYING: qemu will restart this basic block at this address.
// discard the next block hook
(state->cur_address >= address && state->cur_address < address + size)) {
state->ignore_next_block = true;
}
state->handle_write(address, size, false);
}
static void hook_block(uc_engine *uc, uint64_t address, int32_t size, void *user_data) {
//LOG_I("block [%#lx, %#lx]", address, address + size);
State *state = (State *)user_data;
if (state->ignore_next_block) {
state->ignore_next_block = false;
state->ignore_next_selfmod = true;
return;
}
if (!state->check_symbolic_stack_mem_dependencies_liveness()) {
state->stop(STOP_SYMBOLIC_MEM_DEP_NOT_LIVE, true);
return;
}
state->commit();
state->update_previous_stack_top();
state->step(address, size);
if (!state->stopped) {
state->start_propagating_taint(address, size);
}
return;
}
static void hook_intr(uc_engine *uc, uint32_t intno, void *user_data) {
State *state = (State *)user_data;
state->interrupt_handled = false;
if (state->arch == UC_ARCH_X86 && intno == 0x80) {
// this is the ultimate hack for cgc -- it must be enabled by explitly setting the transmit sysno from python
// basically an implementation of the cgc transmit syscall
for (auto sr : state->symbolic_registers) {
// eax,ecx,edx,ebx,esi
if ((sr >= 8 && sr <= 23) || (sr >= 32 && sr <= 35)) return;
}
uint32_t sysno;
uc_reg_read(uc, UC_X86_REG_EAX, &sysno);
//printf("SYSCALL: %d\n", sysno);
if (sysno == state->transmit_sysno) {
//printf(".. TRANSMIT!\n");
uint32_t fd, buf, count, tx_bytes;
uc_reg_read(uc, UC_X86_REG_EBX, &fd);
if (fd == 2) {
// we won't try to handle fd 2 prints here, they are uncommon.
return;
} else if (fd == 0 || fd == 1) {
uc_reg_read(uc, UC_X86_REG_ECX, &buf);
uc_reg_read(uc, UC_X86_REG_EDX, &count);
uc_reg_read(uc, UC_X86_REG_ESI, &tx_bytes);
// ensure that the memory we're sending is not tainted
// TODO: Can transmit also work with symbolic bytes?
void *dup_buf = malloc(count);
uint32_t tmp_tx;
if (uc_mem_read(uc, buf, dup_buf, count) != UC_ERR_OK)
{
//printf("... fault on buf\n");
free(dup_buf);
return;
}
if (tx_bytes != 0 && uc_mem_read(uc, tx_bytes, &tmp_tx, 4) != UC_ERR_OK)
{
//printf("... fault on tx\n");
free(dup_buf);
return;
}
if (state->find_tainted(buf, count) != -1)
{
//printf("... symbolic data\n");
free(dup_buf);
return;
}
state->step(state->transmit_bbl_addr, 0, false);
state->commit();
if (state->stopped)
{
//printf("... stopped after step()\n");
free(dup_buf);
return;
}
uc_err err = uc_mem_write(uc, tx_bytes, &count, 4);
if (tx_bytes != 0) state->handle_write(tx_bytes, 4, true);
if (state->stopped) {
return;
}
state->transmit_records.push_back({dup_buf, count});
int result = 0;
uc_reg_write(uc, UC_X86_REG_EAX, &result);
state->symbolic_registers.erase(8);
state->symbolic_registers.erase(9);
state->symbolic_registers.erase(10);
state->symbolic_registers.erase(11);
state->interrupt_handled = true;
state->syscall_count++;
return;
}
}
}
}
static bool hook_mem_unmapped(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) {
State *state = (State *)user_data;
uint64_t start = address & ~0xFFFULL;
uint64_t end = (address + size - 1) & ~0xFFFULL;
// only hook nonwritable pages
if (type != UC_MEM_WRITE_UNMAPPED && state->map_cache(start, 0x1000) && (start == end || state->map_cache(end, 0x1000))) {
//LOG_D("handle unmapped page natively");
return true;
}
return false;
}
static bool hook_mem_prot(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) {
State *state = (State *)user_data;
//printf("Segfault data: %d %#llx %d %#llx\n", type, address, size, value);
state->stop(STOP_SEGFAULT);
return true;
}
/*
* C style bindings makes it simple and dirty
*/
extern "C"
State *simunicorn_alloc(uc_engine *uc, uint64_t cache_key) {
State *state = new State(uc, cache_key);
return state;
}
extern "C"
void simunicorn_dealloc(State *state) {
delete state;
}
extern "C"
uint64_t *simunicorn_bbl_addrs(State *state) {
return &(state->bbl_addrs[0]);
}
extern "C"
uint64_t *simunicorn_stack_pointers(State *state) {
return &(state->stack_pointers[0]);
}
extern "C"
uint64_t simunicorn_bbl_addr_count(State *state) {
return state->bbl_addrs.size();
}
extern "C"
uint64_t simunicorn_syscall_count(State *state) {
return state->syscall_count;
}
extern "C"
void simunicorn_hook(State *state) {
state->hook();
}
extern "C"
void simunicorn_unhook(State *state) {
state->unhook();
}
extern "C"
uc_err simunicorn_start(State *state, uint64_t pc, uint64_t step) {
return state->start(pc, step);
}
extern "C"
void simunicorn_stop(State *state, stop_t reason) {
state->stop(reason);
}
extern "C"
mem_update_t *simunicorn_sync(State *state) {
return state->sync();
}
extern "C"
uint64_t simunicorn_step(State *state) {
return state->cur_steps;
}
extern "C"
void simunicorn_set_stops(State *state, uint64_t count, uint64_t *stops)
{
state->set_stops(count, stops);
}
extern "C"
void simunicorn_activate_page(State *state, uint64_t address, uint8_t *taint, uint8_t *data) {
state->page_activate(address, taint, data);
}
extern "C"
uint64_t simunicorn_executed_pages(State *state) { // this is HORRIBLE
if (state->executed_pages_iterator == NULL) {
state->executed_pages_iterator = new std::unordered_set<address_t>::iterator;
*state->executed_pages_iterator = state->executed_pages.begin();
}
if (*state->executed_pages_iterator == state->executed_pages.end()) {
delete state->executed_pages_iterator;
state->executed_pages_iterator = NULL;
return -1;
}
uint64_t out = **state->executed_pages_iterator;
(*state->executed_pages_iterator)++;
return out;
}
//
// Stop analysis
//
extern "C"
stop_details_t simunicorn_get_stop_details(State *state) {
return state->stop_details;
}
//
// Symbolic register tracking
//
extern "C"
void simunicorn_symbolic_register_data(State *state, uint64_t count, uint64_t *offsets)
{
state->symbolic_registers.clear();
for (auto i = 0; i < count; i++) {
state->symbolic_registers.insert(offsets[i]);
}
}
extern "C"
uint64_t simunicorn_get_symbolic_registers(State *state, uint64_t *output)
{
int i = 0;
for (auto r : state->symbolic_registers) {
output[i] = r;
i++;
}
return i;
}
extern "C"
void simunicorn_enable_symbolic_reg_tracking(State *state, VexArch guest, VexArchInfo archinfo) {
state->vex_guest = guest;
state->vex_archinfo = archinfo;
}
extern "C"
void simunicorn_disable_symbolic_reg_tracking(State *state) {
state->vex_guest = VexArch_INVALID;
}
//
// Concrete transmits
//
extern "C"
bool simunicorn_is_interrupt_handled(State *state) {
return state->interrupt_handled;
}
extern "C"
void simunicorn_set_transmit_sysno(State *state, uint32_t sysno, uint64_t bbl_addr) {
state->transmit_sysno = sysno;
state->transmit_bbl_addr = bbl_addr;
}
extern "C"
transmit_record_t *simunicorn_process_transmit(State *state, uint32_t num) {
if (num >= state->transmit_records.size()) {
for (auto record_iter = state->transmit_records.begin();
record_iter != state->transmit_records.end();
record_iter++) {
free(record_iter->data);
}
state->transmit_records.clear();
return NULL;
} else {
transmit_record_t *out = &state->transmit_records[num];
return out;
}
}
/*
* Page cache
*/
extern "C"
bool simunicorn_cache_page(State *state, uint64_t address, uint64_t length, char *bytes, uint64_t permissions) {
//LOG_I("caching [%#lx, %#lx]", address, address + length);
auto actual = state->cache_page(address, length, bytes, permissions);
if (!state->map_cache(actual.first, actual.second)) {
return false;
}
return true;
}
extern "C"
void simunicorn_uncache_pages_touching_region(State *state, uint64_t address, uint64_t length) {
state->uncache_pages_touching_region(address, length);
}
extern "C"
void simunicorn_clear_page_cache(State *state) {
state->clear_page_cache();
}
// Tracking settings
extern "C"
void simunicorn_set_tracking(State *state, bool track_bbls, bool track_stack) {
state->track_bbls = track_bbls;
state->track_stack = track_stack;
}
extern "C"
bool simunicorn_in_cache(State *state, uint64_t address) {
return state->in_cache(address);
}
extern "C"
void simunicorn_set_map_callback(State *state, uc_cb_eventmem_t cb) {
state->py_mem_callback = cb;
}
// VEX artificial registers list
extern "C"
void simunicorn_set_artificial_registers(State *state, uint64_t *offsets, uint64_t count) {
state->artificial_vex_registers.clear();
for (auto i = 0; i < count; i++) {
state->artificial_vex_registers.emplace(offsets[i]);
}
return;
}
// VEX register offsets to unicorn register ID mappings
extern "C"
void simunicorn_set_vex_to_unicorn_reg_mappings(State *state, uint64_t *vex_offsets, uint64_t *unicorn_ids, uint64_t count) {
state->vex_to_unicorn_map.clear();
for (auto i = 0; i < count; i++) {
state->vex_to_unicorn_map.emplace(vex_offsets[i], unicorn_ids[i]);
}
return;
}
// Mapping details for flags registers
extern "C"
void simunicorn_set_cpu_flags_details(State *state, uint64_t *flag_vex_id, uint64_t *bitmasks, uint64_t count) {
state->cpu_flags.clear();
for (auto i = 0; i < count; i++) {
state->cpu_flags.emplace(flag_vex_id[i], bitmasks[i]);
}
return;
}
// Flag register ID in unicorn
extern "C"
void simunicorn_set_unicorn_flags_register_id(State *state, int64_t reg_id) {
state->cpu_flags_register = reg_id;
return;
}
extern "C"
void simunicorn_set_register_blacklist(State *state, uint64_t *reg_list, uint64_t count) {
state->blacklisted_registers.clear();
for (auto i = 0; i < count; i++) {
state->blacklisted_registers.emplace(reg_list[i]);
}
return;
}
// VEX re-execution data
extern "C"
uint64_t simunicorn_get_count_of_blocks_with_symbolic_instrs(State *state) {
return state->block_details_to_return.size();
}
extern "C"
void simunicorn_get_details_of_blocks_with_symbolic_instrs(State *state, sym_block_details_ret_t *ret_block_details) {
for (auto i = 0; i < state->block_details_to_return.size(); i++) {
ret_block_details[i].block_addr = state->block_details_to_return[i].block_addr;
ret_block_details[i].block_size = state->block_details_to_return[i].block_size;
ret_block_details[i].symbolic_instrs = &(state->block_details_to_return[i].symbolic_instrs[0]);
ret_block_details[i].symbolic_instrs_count = state->block_details_to_return[i].symbolic_instrs.size();
ret_block_details[i].register_values = &(state->block_details_to_return[i].register_values[0]);
ret_block_details[i].register_values_count = state->block_details_to_return[i].register_values.size();
}
return;
}
| 94,900
| 38,469
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_ACCEPT_CHANNEL_RESPONSE_HPP
#define COH_ACCEPT_CHANNEL_RESPONSE_HPP
#include "private/coherence/component/net/extend/AbstractPofResponse.hpp"
COH_OPEN_NAMESPACE5(coherence,component,net,extend,protocol)
using coherence::component::net::extend::AbstractPofResponse;
/**
* This Request is used to accept a Channel that was spawned by a peer.
*
* @authore nsa 2008.03.17
*/
class COH_EXPORT AcceptChannelResponse
: public class_spec<AcceptChannelResponse,
extends<AbstractPofResponse> >
{
friend class factory<AcceptChannelResponse>;
// ----- constructors ---------------------------------------------------
protected:
/**
* Create a new NamedCacheProtocol instance.
*/
AcceptChannelResponse();
private:
/**
* Blocked copy constructor.
*/
AcceptChannelResponse(const AcceptChannelResponse&);
// ----- Message interface ----------------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual int32_t getTypeId() const;
/**
* {@inheritDoc}
*/
virtual void run();
// ----- constants ------------------------------------------------------
public:
/**
* The type identifier of this Message class.
*/
static const int32_t type_id = 14;
};
COH_CLOSE_NAMESPACE5
#endif // COH_ACCEPT_CHANNEL_RESPONSE_HPP
| 1,625
| 504
|