text
stringlengths
5
1.04M
#include <2DGameSDK/scene/entity/definitions/DynamicEntity.h> namespace game { DynamicEntity::DynamicEntity(int type, GameBase* game, RenderStrategy* renderer, std::vector<Shape<DynamicShapePhysics>*> shapes, bool isCollidable) : Entity(type, game), mRenderer(renderer), mIsCollidable(isCollidable), mShapes(shapes) { mBody = cpSpaceAddBody(game->GetPhysicalWorld(), cpBodyNew(0, 0)); cpBodySetUserData(mBody, new CollisionTarget(this, ObjectType::Entity)); auto space = getGame()->GetPhysicalWorld(); for(auto shape : mShapes) { shape->AttachToBody(space, mBody); } } DynamicEntity::~DynamicEntity() { auto space = getGame()->GetPhysicalWorld(); for(auto shape : mShapes) { helpers::safeDelete(shape); } cpSpaceRemoveBody(space, mBody); cpBodyFree(mBody); } cpVect DynamicEntity::GetVelocity() { return cpBodyGetVelocity(mBody); } cpVect DynamicEntity::GetForce() { return cpBodyGetForce(mBody); } bool DynamicEntity::IsKinematic() { return false; } bool DynamicEntity::IsCollidable() { return mIsCollidable; } sf::Transform DynamicEntity::GetTransform() { auto pos = cpBodyGetPosition(mBody); auto rot = GraphicTools::RadToDeg(cpBodyGetAngle(mBody)); return sf::Transform().translate(pos.x, pos.y).rotate(rot); } sf::Transform DynamicEntity::GetAccumulatedTransform() { return constants::SF_TRANSFORM_I; } sf::Transform DynamicEntity::GetCombinedTransform() { return GetTransform(); } RenderStrategy* DynamicEntity::GetRenderer() { return mRenderer; } void DynamicEntity::SetMass(float mass) { cpBodySetMass(mBody, mass); } void DynamicEntity::SetMoment(float moment) { cpBodySetMoment(mBody, moment); } void DynamicEntity::SetVelocity(cpVect velocity) { cpBodySetVelocity(mBody, velocity); } void DynamicEntity::SetForce(cpVect force) { cpBodySetForce(mBody, force); } void DynamicEntity::SetAngularVelocity(float angularVelocity) { cpBodySetAngularVelocity(mBody, angularVelocity); } void DynamicEntity::SetTorque(float torque) { cpBodySetTorque(mBody, torque); } void DynamicEntity::OnRender(sf::RenderTarget* target, sf::RenderStates states) { if(mRenderer && mRenderer->IsRenderEnabled()) { auto physPose = Pose<cpVect>{ cpBodyGetPosition(mBody), (float)cpBodyGetAngle(mBody)}; auto visPose = getGame()->GetPoseConverter()->GetVisualPose(physPose); LOGD("Pos: (" << visPose.origin.x << ", " << visPose.origin.y << "), Angle:" << visPose.angle); states.transform = states.transform * sf::Transform().translate(visPose.origin).rotate(visPose.angle); mRenderer->OnRender(target, states); } auto options = getGame()->GetOptions(); if(!(options.RenderCollisionMask || options.RenderAABB)) return; for(auto shape : mShapes) { if(options.RenderCollisionMask) shape->Render(target, sf::Color::Red, 1.0 / options.InitialZoom); if(options.RenderAABB) shape->RenderAABB(target, sf::Color::Magenta, 1.0 / options.InitialZoom); } } int DynamicEntity::OnCollision(CollisionEventType, Entity*, cpArbiter*) { return 1; } int DynamicEntity::OnWorldCollision(CollisionEventType, Tile*, cpArbiter*) { return 1; } bool DynamicEntity::setTransform(sf::Transform transform) { auto pose = getGame()->GetPoseConverter()->GetPhysicalPose(transform); LOGD("Body Pos: (" << pose.origin.x << ", " << pose.origin.y << "), angle: " << pose.angle); cpBodySetPosition(mBody, pose.origin); cpBodySetAngle(mBody, pose.angle); cpSpaceReindexShapesForBody(getGame()->GetPhysicalWorld(), mBody); return true; } } // namespace game
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_INPUT_JOYPAD_FF_CONDITION_FWD_HPP_INCLUDED #define SGE_INPUT_JOYPAD_FF_CONDITION_FWD_HPP_INCLUDED namespace sge::input::joypad::ff { class condition; } #endif
/*! * Copyright (c) 2015 by Contributors * \file regression_output.cc * \brief regression output operator */ #include "./regression_output-inl.h" #include "./mshadow_op.h" namespace mxnet { namespace op { template<> Operator *CreateRegressionOutputOp<cpu>(reg_enum::RegressionOutputType type, RegressionOutputParam param) { switch (type) { case reg_enum::kLinear: return new RegressionOutputOp<cpu, mshadow::op::identity, mshadow::op::minus>(param); case reg_enum::kLogistic: return new RegressionOutputOp<cpu, mshadow_op::sigmoid, mshadow::op::minus>(param); case reg_enum::kMAE: return new RegressionOutputOp<cpu, mshadow::op::identity, mshadow_op::minus_sign>(param); default: LOG(FATAL) << "unknown activation type " << type; } return nullptr; } // DO_BIND_DISPATCH comes from operator_common.h template<reg_enum::RegressionOutputType type> Operator *RegressionOutputProp<type>::CreateOperator(Context ctx) const { DO_BIND_DISPATCH(CreateRegressionOutputOp, type, param_); } DMLC_REGISTER_PARAMETER(RegressionOutputParam); MXNET_REGISTER_OP_PROPERTY(LinearRegressionOutput, RegressionOutputProp<reg_enum::kLinear>) .describe("Use linear regression for final output, this is used on final output of a net.") .add_argument("data", "Symbol", "Input data to function.") .add_argument("label", "Symbol", "Input label to function.") .add_arguments(RegressionOutputParam::__FIELDS__()); MXNET_REGISTER_OP_PROPERTY(MAERegressionOutput, RegressionOutputProp<reg_enum::kMAE>) .describe("Use mean absolute error regression for final output, " "this is used on final output of a net.") .add_argument("data", "Symbol", "Input data to function.") .add_argument("label", "Symbol", "Input label to function.") .add_arguments(RegressionOutputParam::__FIELDS__()); MXNET_REGISTER_OP_PROPERTY(LogisticRegressionOutput, RegressionOutputProp<reg_enum::kLogistic>) .describe("Use Logistic regression for final output, this is used on final output of a net.\n" "Logistic regression is suitable for binary classification " "or probability prediction tasks.") .add_argument("data", "Symbol", "Input data to function.") .add_argument("label", "Symbol", "Input label to function.") .add_arguments(RegressionOutputParam::__FIELDS__()); } // namespace op } // namespace mxnet
/* * Copyright (c) 2010-2013 OTClient <https://github.com/edubart/otclient> * * 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 "lightview.h" #include "mapview.h" #include <framework/graphics/framebuffer.h> #include <framework/graphics/framebuffermanager.h> #include <framework/graphics/painter.h> #include <framework/graphics/image.h> enum { MAX_LIGHT_INTENSITY = 8, MAX_AMBIENT_LIGHT_INTENSITY = 255 }; LightView::LightView() { m_lightbuffer = g_framebuffers.createFrameBuffer(); m_lightTexture = generateLightBubble(0.1f); m_blendEquation = Painter::BlendEquation_Add; reset(); } TexturePtr LightView::generateLightBubble(float centerFactor) { int bubbleRadius = 256; int centerRadius = bubbleRadius * centerFactor; int bubbleDiameter = bubbleRadius * 2; ImagePtr lightImage = ImagePtr(new Image(Size(bubbleDiameter, bubbleDiameter))); for(int x = 0; x < bubbleDiameter; x++) { for(int y = 0; y < bubbleDiameter; y++) { float radius = std::sqrt((bubbleRadius - x)*(bubbleRadius - x) + (bubbleRadius - y)*(bubbleRadius - y)); float intensity = std::max(std::min((bubbleRadius-radius)/(float)(bubbleRadius-centerRadius), 1.0f), 0.0f); // light intensity varies inversely with the square of the distance intensity = intensity * intensity; uint8_t colorByte = intensity * 0xff; uint8_t pixel[4] = {colorByte,colorByte,colorByte,0xff}; lightImage->setPixel(x, y, pixel); } } TexturePtr tex = TexturePtr(new Texture(lightImage, true)); tex->setSmooth(true); return tex; } void LightView::reset() { m_lightMap.clear(); } void LightView::setGlobalLight(const Light& light) { m_globalLight = light; } void LightView::addLightSource(const Point& center, float scaleFactor, const Light& light) { int intensity = std::min<int>(light.intensity, MAX_LIGHT_INTENSITY); int radius = intensity * Otc::TILE_PIXELS * scaleFactor; Color color = Color::from8bit(light.color); float brightness = 0.5f + (intensity/(float)MAX_LIGHT_INTENSITY)*0.5f; color.setRed(color.rF() * brightness); color.setGreen(color.gF() * brightness); color.setBlue(color.bF() * brightness); if(m_blendEquation == Painter::BlendEquation_Add && m_lightMap.size() > 0) { LightSource prevSource = m_lightMap.back(); if(prevSource.center == center && prevSource.color == color && prevSource.radius == radius) return; } LightSource source; source.center = center; source.color = color; source.radius = radius; m_lightMap.push_back(source); } void LightView::drawGlobalLight(const Light& light) { Color color = Color::from8bit(light.color); float brightness = light.intensity / (float)MAX_AMBIENT_LIGHT_INTENSITY; color.setRed(color.rF() * brightness); color.setGreen(color.gF() * brightness); color.setBlue(color.bF() * brightness); g_painter->setColor(color); g_painter->drawFilledRect(Rect(0,0,m_lightbuffer->getSize())); } void LightView::drawLightSource(const Point& center, const Color& color, int radius) { // debug draw //radius /= 16; Rect dest = Rect(center - Point(radius, radius), Size(radius*2,radius*2)); g_painter->setColor(color); g_painter->drawTexturedRect(dest, m_lightTexture); } void LightView::resize(const Size& size) { m_lightbuffer->resize(size); } void LightView::draw(const Rect& dest, const Rect& src) { g_painter->saveAndResetState(); m_lightbuffer->bind(); g_painter->setCompositionMode(Painter::CompositionMode_Replace); drawGlobalLight(m_globalLight); g_painter->setBlendEquation(m_blendEquation); g_painter->setCompositionMode(Painter::CompositionMode_Add); for(const LightSource& source : m_lightMap) drawLightSource(source.center, source.color, source.radius); m_lightbuffer->release(); g_painter->setCompositionMode(Painter::CompositionMode_Light); m_lightbuffer->draw(dest, src); g_painter->restoreSavedState(); }
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 <WCDB/column_def.hpp> #include <WCDB/constraint_table.hpp> #include <WCDB/module_argument.hpp> namespace WCDB { ModuleArgument::ModuleArgument(const TableConstraint &tableConstraint) : Describable(tableConstraint.getDescription()) { } ModuleArgument::ModuleArgument(const ColumnDef &columnDef) : Describable(columnDef.getDescription()) { } ModuleArgument::ModuleArgument(const std::string &left, const std::string &right) : Describable(left + "=" + right) { } } //namespace WCDB
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #include <JuceHeader.h> #include "../../../Assets/DemoUtilities.h" #include "JUCEDemos.h" #include "../../../Assets/AudioLiveScrollingDisplay.h" //============================================================================== #include "../../../GUI/AnimationAppDemo.h" #include "../../../GUI/AnimationDemo.h" #include "../../../GUI/BouncingBallWavetableDemo.h" #if JUCE_USE_CAMERA && ! JUCE_LINUX #include "../../../GUI/CameraDemo.h" #endif #if ! JUCE_ANDROID #include "../../../GUI/CodeEditorDemo.h" #endif #include "../../../GUI/ComponentDemo.h" #include "../../../GUI/ComponentTransformsDemo.h" #include "../../../GUI/DialogsDemo.h" #include "../../../GUI/FlexBoxDemo.h" #include "../../../GUI/FontsDemo.h" #include "../../../GUI/GraphicsDemo.h" #if JUCE_HAS_CONSTEXPR #include "../../../GUI/GridDemo.h" #endif #include "../../../GUI/ImagesDemo.h" #include "../../../GUI/KeyMappingsDemo.h" #include "../../../GUI/LookAndFeelDemo.h" #include "../../../GUI/MDIDemo.h" #include "../../../GUI/MenusDemo.h" #include "../../../GUI/MultiTouchDemo.h" #if JUCE_OPENGL #include "../../../GUI/OpenGLAppDemo.h" #include "../../../GUI/OpenGLDemo.h" #include "../../../GUI/OpenGLDemo2D.h" #endif #include "../../../GUI/PropertiesDemo.h" #if ! JUCE_LINUX // #include "../../../GUI/VideoDemo.h" #endif // #include "../../../GUI/WebBrowserDemo.h" #include "../../../GUI/WidgetsDemo.h" #include "../../../GUI/WindowsDemo.h" void registerDemos_Two() noexcept { REGISTER_DEMO (AnimationAppDemo, GUI, false) REGISTER_DEMO (AnimationDemo, GUI, false) REGISTER_DEMO (BouncingBallWavetableDemo, GUI, false) #if JUCE_USE_CAMERA && ! JUCE_LINUX REGISTER_DEMO (CameraDemo, GUI, true) #endif #if ! JUCE_ANDROID REGISTER_DEMO (CodeEditorDemo, GUI, false) #endif REGISTER_DEMO (ComponentDemo, GUI, false) REGISTER_DEMO (ComponentTransformsDemo, GUI, false) REGISTER_DEMO (DialogsDemo, GUI, false) REGISTER_DEMO (FlexBoxDemo, GUI, false) REGISTER_DEMO (FontsDemo, GUI, false) REGISTER_DEMO (GraphicsDemo, GUI, false) #if JUCE_HAS_CONSTEXPR REGISTER_DEMO (GridDemo, GUI, false) #endif REGISTER_DEMO (ImagesDemo, GUI, false) REGISTER_DEMO (KeyMappingsDemo, GUI, false) REGISTER_DEMO (LookAndFeelDemo, GUI, false) REGISTER_DEMO (MDIDemo, GUI, false) REGISTER_DEMO (MenusDemo, GUI, false) REGISTER_DEMO (MultiTouchDemo, GUI, false) #if JUCE_OPENGL // REGISTER_DEMO (OpenGLAppDemo, GUI, true) // REGISTER_DEMO (OpenGLDemo2D, GUI, true) // REGISTER_DEMO (OpenGLDemo, GUI, true) #endif REGISTER_DEMO (PropertiesDemo, GUI, false) #if ! JUCE_LINUX // REGISTER_DEMO (VideoDemo, GUI, true) #endif // REGISTER_DEMO (WebBrowserDemo, GUI, true) REGISTER_DEMO (WidgetsDemo, GUI, false) REGISTER_DEMO (WindowsDemo, GUI, false) } CodeEditorComponent::ColourScheme getDarkColourScheme() { return getDarkCodeEditorColourScheme(); } CodeEditorComponent::ColourScheme getLightColourScheme() { return getLightCodeEditorColourScheme(); }
#include "config.h" #include "cpu/gdt.h" #include "std/stdout.h" GlobalDescriptorTable::GlobalDescriptorTablePointer gdt_pointer; uint16_t codeSegmentSelectortemp; uint16_t dataSegmentSelectortemp; size_t kernelCodeSegmentSelectorindex = 1; size_t kernelDataSegmentSelectorindex = 2; GlobalDescriptorTable::GlobalDescriptorTable() { nullSegmentSelector.setValues(0,0,0); codeSegmentSelector.setValues(0,KERNELCODE_SEGMENTSELECTOR,0x9A); dataSegmentSelector.setValues(0,KERNELDATA_SEGMENTSELECTOR,0x92); gdt_table[0] = nullSegmentSelector; gdt_table[kernelCodeSegmentSelectorindex] = codeSegmentSelector; gdt_table[kernelDataSegmentSelectorindex] = dataSegmentSelector; gdt_pointer.limit = sizeof(GlobalDescriptorTable::SegmentDescriptor)*GDT_TABLE_SIZE - 1; gdt_pointer.base = (uint32_t)gdt_table; } void GlobalDescriptorTable::flushGDT(){ codeSegmentSelectortemp = CodeSegmentSelector(); dataSegmentSelectortemp = DataSegmentSelector(); load_gdt((uint32_t)(&gdt_pointer)); #ifdef DEBUG print("GDT loaded "); printint((uint32_t)this); print(" Code Segment Selector: "); printint(CodeSegmentSelector()); print(" Data Segment Selector: "); printint(DataSegmentSelector()); ln(); #endif } GlobalDescriptorTable::~GlobalDescriptorTable(){} uint16_t GlobalDescriptorTable::DataSegmentSelector(){ return (uint8_t*)&gdt_table[kernelDataSegmentSelectorindex] - (uint8_t*)gdt_table; } uint16_t GlobalDescriptorTable::CodeSegmentSelector(){ return (uint8_t*)&gdt_table[kernelCodeSegmentSelectorindex] - (uint8_t*)gdt_table; } void GlobalDescriptorTable::SegmentDescriptor::setValues(uint32_t base,uint32_t limit,uint8_t flags){ uint8_t* target = (uint8_t*)this; if(limit <= 65536){ target[6] = 0x40; }else{ if((limit & 0xFFF) != 0xFFF) limit = (limit >> 12)-1; else limit = limit >> 12; target[6] = 0xC0; } target[0] = limit & 0xFF; target[1] = (limit >> 8) & 0xFF; target[6] |= (limit >> 16) & 0xF; target[2] = base & 0xFF; target[3] = (base >> 8) & 0xFF; target[4] = (base >> 16) & 0xFF; target[7] = (base >> 24) & 0xFF; target[5] = flags; } uint32_t GlobalDescriptorTable::SegmentDescriptor::Base(){ uint8_t* target = (uint8_t*)this; uint32_t result = target[7]; result = (result << 8) + target[4]; result = (result << 8) + target[3]; result = (result << 8) + target[2]; return result; }
#include "button_volume.h" static constexpr int minVolume = 0; static constexpr int maxVolume = 200; Button_Volume::Button_Volume(const Button::CtorData &d) : Button_UserRelated(d) { step = (d.action == "cz.danol.discordmixer.volumeup" ? 1 : -1) * 5; repeatTimer.setInterval(100); repeatTimer.callOnTimeout([this] { if(repeatSkip-- <= 0) trigger(); }); } VoiceState *Button_Volume::voiceState() { const int ix = effectiveIx(); if(ix < 0 || ix >= device.voiceStates.size()) return nullptr; return &device.voiceStates[device.voiceStates.keys()[ix]]; } void Button_Volume::update() { VoiceState *s = voiceState(); const int targetState = s ? (step < 0 && s->volume <= minVolume) || (step > 0 && s->volume >= maxVolume) : 1; if(state == targetState) return; state = targetState; device.plugin.deck.setState(targetState, context); } void Button_Volume::onPressed() { /// Ignore first 300 ms repeatSkip = 3; trigger(); repeatTimer.start(); } void Button_Volume::onReleased() { repeatTimer.stop(); state = -1; update(); } void Button_Volume::trigger() { VoiceState *s = voiceState(); if(!s) return; const int newVolume = static_cast<int>(qRound(static_cast<float>(qBound(minVolume, s->volume + step, maxVolume)) / step) * step); if(newVolume == s->volume) return; s->volume = newVolume; s->muted = false; state = -1; device.plugin.discord.sendCommand("SET_USER_VOICE_SETTINGS", { {"user_id", s->userID}, {"volume", QDiscord::uiToIPCVolume(newVolume)}, {"mute", false} }); device.plugin.updateButtons(); }
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/c_api_internal.h" #include "tensorflow/c/eager/abstract_function.h" #include "tensorflow/c/tf_tensor_internal.h" #include "tensorflow/core/common_runtime/eager/context.h" #include "tensorflow/core/common_runtime/eager/eager_operation.h" #include "tensorflow/core/common_runtime/eager/execute.h" #include "tensorflow/core/common_runtime/eager/placement_utils.h" #include "tensorflow/core/common_runtime/eager/tensor_handle.h" #include "tensorflow/core/platform/errors.h" namespace { bool IsCPU(tensorflow::VariantDevice variant) { if (VariantDeviceIsCustom(variant)) { return false; } tensorflow::Device* d = absl::get<tensorflow::Device*>(variant); return d == nullptr || d->tensorflow_gpu_device_info() == nullptr; } } // namespace namespace tensorflow { // TODO(b/152902651): This should not depend on EagerContext. This can be // resolved by storing ctx->HostCPU() in the TensorHandle class. AbstractTensorInterface* TensorHandle::Resolve(Status* status) { if (VariantDeviceIsCustom(device())) { auto* custom_device = absl::get<CustomDevice*>(device()); TensorHandle* copy; *status = custom_device->CopyTensorFromDevice( this, "/job:localhost/replica:0/task:0/device:CPU:0", &copy); if (status->ok()) { auto result = copy->Resolve(status); copy->Unref(); return result; } else { return nullptr; } } if (Type() == REMOTE) { const tensorflow::Tensor* t = nullptr; TensorHandle* h_cpu = nullptr; *status = EagerCopyToDevice(this, ctx_, &ctx_->Executor(), ctx_->HostCPU(), false, &h_cpu); if (!status->ok()) { return nullptr; } *status = h_cpu->Tensor(&t); if (!status->ok()) { h_cpu->Unref(); return nullptr; } // TODO(b/153052876): Change TF_TensorFromTensor to just return an // AbstractTensorInterface TF_Tensor* tf_tensor = TF_TensorFromTensor(*t, status); AbstractTensorInterface* retval = tf_tensor->tensor; h_cpu->Unref(); delete tf_tensor; return retval; } else if (Type() == LOCAL) { tensorflow::Tensor tensor; if (IsCPU(device()) || HasLocalMirror(nullptr)) { const tensorflow::Tensor* src = nullptr; if (HasLocalMirror(nullptr)) { *status = TensorFromDevice(nullptr, &src); } else { *status = Tensor(&src); } if (!status->ok()) return nullptr; tensor = *src; } else { *status = CopyToDevice(*ctx_, ctx_->HostCPU(), &tensor); if (!status->ok()) return nullptr; tensorflow::Tensor mirror = tensor; *status = AddLocalMirror(std::move(mirror), nullptr); if (!status->ok()) { // If a mirror was added since we called HasLocalMirror then drop the // newly copied tensor and use the previously added mirror. if (status->code() != error::Code::ALREADY_EXISTS) { return nullptr; } const tensorflow::Tensor* src = nullptr; *status = TensorFromDevice(nullptr, &src); if (!status->ok()) return nullptr; tensor = *src; } } // TODO(b/153052876): Change TF_TensorFromTensor to just return an // AbstractTensorInterface TF_Tensor* tf_tensor = TF_TensorFromTensor(tensor, status); AbstractTensorInterface* retval = tf_tensor->tensor; delete tf_tensor; return retval; } else { *status = errors::InvalidArgument( "Resolve() is not supoorted on packed TensorHandles."); return nullptr; } } ImmediateExecutionTensorHandle* EagerContext::CopyTensorHandleToDevice( ImmediateExecutionTensorHandle* handle, const char* device_name, Status* status) { TensorHandle* input = TensorHandleFromInterface(handle); TensorHandle* result = nullptr; Device* device; *status = this->FindDeviceFromName(device_name, &device); if (!status->ok()) { tensorflow::CustomDevice* dev; if (this->FindCustomDeviceFromName(device_name, &dev)) { *status = dev->CopyTensorToDevice(input, &result); if (status->ok()) { return result; } } else { *status = tensorflow::errors::InvalidArgument(device_name, " unknown device."); } return nullptr; } // Handle tensor handles currently in custom devices const char* handle_device_name = input->DeviceName(status); if (!status->ok()) { return nullptr; } tensorflow::CustomDevice* dev; if (this->FindCustomDeviceFromName(handle_device_name, &dev)) { *status = dev->CopyTensorFromDevice(input, device_name, &result); if (status->ok()) { return result; } return nullptr; } // Handle regular case. *status = EagerCopyToDevice(input, this, &this->Executor(), device, false, &result); if (status->ok()) { return result; } return nullptr; } // TODO(b/152902651): We unfortunately need to put this EagerContext function // here to a circular BUILD dep issue. If we move this to context.cc, then we // will have the circular dependency of: // context -> tensor_handle -> remote_tensor_handle_data -> context ImmediateExecutionTensorHandle* EagerContext::CreateLocalHandle( AbstractTensorInterface* t) { Tensor tensor = TensorFromInterface(t); return TensorHandle::CreateLocalHandle(std::move(tensor), /*d=*/HostCPU(), /*op_device=*/nullptr, this); } // TODO(b/152902651): We have to keep this function here since EagerOperation // depends on EagerContext. Thus, the context build target can't depend on // EagerOperation. ImmediateExecutionOperation* EagerContext::CreateOperation() { return new EagerOperation(this); } Status EagerContext::RegisterFunction(AbstractFunction* f) { FunctionDef* fdef; TF_RETURN_IF_ERROR(f->GetFunctionDef(&fdef)); if (!fdef) { return errors::InvalidArgument("GetFunctionDef returned nullptr."); } return AddFunctionDef(*fdef); } // TODO(b/152902651): Once we move many execute.cc functions into // eager_operation.cc we can avoid a circular dependency between them. Status EagerOperation::Execute(absl::Span<AbstractTensorHandle*> retvals, int* num_retvals) { for (int i = 0; i < Inputs().size(); ++i) { TF_RETURN_IF_ERROR(Inputs()[i]->WaitUnknownDevice()); } // Run eager placement logic. VariantDevice device; TF_RETURN_IF_ERROR(eager::MaybePinToCustomDevice(&device, *this)); if (device == kVariantDeviceNull) { TF_RETURN_IF_ERROR(eager::MaybePinToResourceDevice(&device, *this)); } if (device == kVariantDeviceNull && ctx_.PinSmallOpsToCPU()) { bool pin_to_cpu; TF_RETURN_IF_ERROR(eager::MaybePinSmallOpsToCpu( &pin_to_cpu, Name(), GetInputs(), ctx_.HostCPU()->name())); if (pin_to_cpu) { device = ctx_.HostCPU(); } } if (device != kVariantDeviceNull) { SetDevice(device); } return EagerExecute( this, reinterpret_cast<tensorflow::TensorHandle**>(retvals.data()), num_retvals); } } // namespace tensorflow
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <armnn/BackendRegistry.hpp> #include <armnn/Exceptions.hpp> #include <ProfilingService.hpp> namespace armnn { BackendRegistry& BackendRegistryInstance() { static BackendRegistry instance; return instance; } void BackendRegistry::Register(const BackendId& id, BackendRegistry::FactoryFunction factory) { if (m_Factories.find(id) != m_Factories.end()) { throw InvalidArgumentException( std::string(id) + " already registered as IBackend factory", CHECK_LOCATION()); } m_Factories[id] = factory; if (m_ProfilingService.has_value()) { if (m_ProfilingService.has_value() && m_ProfilingService.value().IsProfilingEnabled()) { m_ProfilingService.value().IncrementCounterValue(armnn::profiling::REGISTERED_BACKENDS); } } } void BackendRegistry::Deregister(const BackendId& id) { m_Factories.erase(id); if (m_ProfilingService.has_value() && m_ProfilingService.value().IsProfilingEnabled()) { m_ProfilingService.value().IncrementCounterValue(armnn::profiling::UNREGISTERED_BACKENDS); } } bool BackendRegistry::IsBackendRegistered(const BackendId& id) const { return (m_Factories.find(id) != m_Factories.end()); } BackendRegistry::FactoryFunction BackendRegistry::GetFactory(const BackendId& id) const { auto it = m_Factories.find(id); if (it == m_Factories.end()) { throw InvalidArgumentException( std::string(id) + " has no IBackend factory registered", CHECK_LOCATION()); } return it->second; } size_t BackendRegistry::Size() const { return m_Factories.size(); } BackendIdSet BackendRegistry::GetBackendIds() const { BackendIdSet result; for (const auto& it : m_Factories) { result.insert(it.first); } return result; } std::string BackendRegistry::GetBackendIdsAsString() const { static const std::string delimitator = ", "; std::stringstream output; for (auto& backendId : GetBackendIds()) { if (output.tellp() != std::streampos(0)) { output << delimitator; } output << backendId; } return output.str(); } void BackendRegistry::Swap(BackendRegistry& instance, BackendRegistry::FactoryStorage& other) { std::swap(instance.m_Factories, other); } void BackendRegistry::SetProfilingService(armnn::Optional<profiling::ProfilingService&> profilingService) { m_ProfilingService = profilingService; } } // namespace armnn
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <set> #include <string> #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/string_util.h" #include "net/base/net_errors.h" #include "net/dns/mock_host_resolver.h" #include "net/http/http_auth.h" #include "net/http/http_auth_filter.h" #include "net/http/http_auth_handler.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_handler_mock.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" #include "net/http/mock_allow_url_security_manager.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { HttpAuthHandlerMock* CreateMockHandler(bool connection_based) { HttpAuthHandlerMock* auth_handler = new HttpAuthHandlerMock(); auth_handler->set_connection_based(connection_based); std::string challenge_text = "Basic"; HttpAuth::ChallengeTokenizer challenge(challenge_text.begin(), challenge_text.end()); GURL origin("www.example.com"); EXPECT_TRUE(auth_handler->InitFromChallenge(&challenge, HttpAuth::AUTH_SERVER, origin, BoundNetLog())); return auth_handler; } HttpResponseHeaders* HeadersFromResponseText(const std::string& response) { return new HttpResponseHeaders( HttpUtil::AssembleRawHeaders(response.c_str(), response.length())); } HttpAuth::AuthorizationResult HandleChallengeResponse( bool connection_based, const std::string& headers_text, std::string* challenge_used) { scoped_ptr<HttpAuthHandlerMock> mock_handler( CreateMockHandler(connection_based)); std::set<HttpAuth::Scheme> disabled_schemes; scoped_refptr<HttpResponseHeaders> headers( HeadersFromResponseText(headers_text)); return HttpAuth::HandleChallengeResponse( mock_handler.get(), headers.get(), HttpAuth::AUTH_SERVER, disabled_schemes, challenge_used); } } // namespace TEST(HttpAuthTest, ChooseBestChallenge) { static const struct { const char* headers; HttpAuth::Scheme challenge_scheme; const char* challenge_realm; } tests[] = { { // Basic is the only challenge type, pick it. "Y: Digest realm=\"X\", nonce=\"aaaaaaaaaa\"\n" "www-authenticate: Basic realm=\"BasicRealm\"\n", HttpAuth::AUTH_SCHEME_BASIC, "BasicRealm", }, { // Fake is the only challenge type, but it is unsupported. "Y: Digest realm=\"FooBar\", nonce=\"aaaaaaaaaa\"\n" "www-authenticate: Fake realm=\"FooBar\"\n", HttpAuth::AUTH_SCHEME_MAX, "", }, { // Pick Digest over Basic. "www-authenticate: Basic realm=\"FooBar\"\n" "www-authenticate: Fake realm=\"FooBar\"\n" "www-authenticate: nonce=\"aaaaaaaaaa\"\n" "www-authenticate: Digest realm=\"DigestRealm\", nonce=\"aaaaaaaaaa\"\n", HttpAuth::AUTH_SCHEME_DIGEST, "DigestRealm", }, { // Handle an empty header correctly. "Y: Digest realm=\"X\", nonce=\"aaaaaaaaaa\"\n" "www-authenticate:\n", HttpAuth::AUTH_SCHEME_MAX, "", }, { "WWW-Authenticate: Negotiate\n" "WWW-Authenticate: NTLM\n", #if defined(USE_KERBEROS) // Choose Negotiate over NTLM on all platforms. // TODO(ahendrickson): This may be flaky on Linux and OSX as it // relies on being able to load one of the known .so files // for gssapi. HttpAuth::AUTH_SCHEME_NEGOTIATE, #else // On systems that don't use Kerberos fall back to NTLM. HttpAuth::AUTH_SCHEME_NTLM, #endif // defined(USE_KERBEROS) "", } }; GURL origin("http://www.example.com"); std::set<HttpAuth::Scheme> disabled_schemes; MockAllowURLSecurityManager url_security_manager; scoped_ptr<HostResolver> host_resolver(new MockHostResolver()); scoped_ptr<HttpAuthHandlerRegistryFactory> http_auth_handler_factory( HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); http_auth_handler_factory->SetURLSecurityManager( "negotiate", &url_security_manager); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { // Make a HttpResponseHeaders object. std::string headers_with_status_line("HTTP/1.1 401 Unauthorized\n"); headers_with_status_line += tests[i].headers; scoped_refptr<HttpResponseHeaders> headers( HeadersFromResponseText(headers_with_status_line)); scoped_ptr<HttpAuthHandler> handler; HttpAuth::ChooseBestChallenge(http_auth_handler_factory.get(), headers.get(), HttpAuth::AUTH_SERVER, origin, disabled_schemes, BoundNetLog(), &handler); if (handler.get()) { EXPECT_EQ(tests[i].challenge_scheme, handler->auth_scheme()); EXPECT_STREQ(tests[i].challenge_realm, handler->realm().c_str()); } else { EXPECT_EQ(HttpAuth::AUTH_SCHEME_MAX, tests[i].challenge_scheme); EXPECT_STREQ("", tests[i].challenge_realm); } } } TEST(HttpAuthTest, HandleChallengeResponse) { std::string challenge_used; const char* const kMockChallenge = "HTTP/1.1 401 Unauthorized\n" "WWW-Authenticate: Mock token_here\n"; const char* const kBasicChallenge = "HTTP/1.1 401 Unauthorized\n" "WWW-Authenticate: Basic realm=\"happy\"\n"; const char* const kMissingChallenge = "HTTP/1.1 401 Unauthorized\n"; const char* const kEmptyChallenge = "HTTP/1.1 401 Unauthorized\n" "WWW-Authenticate: \n"; const char* const kBasicAndMockChallenges = "HTTP/1.1 401 Unauthorized\n" "WWW-Authenticate: Basic realm=\"happy\"\n" "WWW-Authenticate: Mock token_here\n"; const char* const kTwoMockChallenges = "HTTP/1.1 401 Unauthorized\n" "WWW-Authenticate: Mock token_a\n" "WWW-Authenticate: Mock token_b\n"; // Request based schemes should treat any new challenges as rejections of the // previous authentication attempt. (There is a slight exception for digest // authentication and the stale parameter, but that is covered in the // http_auth_handler_digest_unittests). EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kMockChallenge, &challenge_used)); EXPECT_EQ("Mock token_here", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kBasicChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kMissingChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kEmptyChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kBasicAndMockChallenges, &challenge_used)); EXPECT_EQ("Mock token_here", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(false, kTwoMockChallenges, &challenge_used)); EXPECT_EQ("Mock token_a", challenge_used); // Connection based schemes will treat new auth challenges for the same scheme // as acceptance (and continuance) of the current approach. If there are // no auth challenges for the same scheme, the response will be treated as // a rejection. EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_ACCEPT, HandleChallengeResponse(true, kMockChallenge, &challenge_used)); EXPECT_EQ("Mock token_here", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(true, kBasicChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(true, kMissingChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_REJECT, HandleChallengeResponse(true, kEmptyChallenge, &challenge_used)); EXPECT_EQ("", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_ACCEPT, HandleChallengeResponse(true, kBasicAndMockChallenges, &challenge_used)); EXPECT_EQ("Mock token_here", challenge_used); EXPECT_EQ( HttpAuth::AUTHORIZATION_RESULT_ACCEPT, HandleChallengeResponse(true, kTwoMockChallenges, &challenge_used)); EXPECT_EQ("Mock token_a", challenge_used); } TEST(HttpAuthTest, ChallengeTokenizer) { std::string challenge_str = "Basic realm=\"foobar\""; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Basic"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("foobar"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use a name=value property with no quote marks. TEST(HttpAuthTest, ChallengeTokenizerNoQuotes) { std::string challenge_str = "Basic realm=foobar@baz.com"; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Basic"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("foobar@baz.com"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use a name=value property with mismatching quote marks. TEST(HttpAuthTest, ChallengeTokenizerMismatchedQuotes) { std::string challenge_str = "Basic realm=\"foobar@baz.com"; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Basic"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("foobar@baz.com"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use a name= property without a value and with mismatching quote marks. TEST(HttpAuthTest, ChallengeTokenizerMismatchedQuotesNoValue) { std::string challenge_str = "Basic realm=\""; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Basic"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string(), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use a name=value property with mismatching quote marks and spaces in the // value. TEST(HttpAuthTest, ChallengeTokenizerMismatchedQuotesSpaces) { std::string challenge_str = "Basic realm=\"foo bar"; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Basic"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("foo bar"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use multiple name=value properties with mismatching quote marks in the last // value. TEST(HttpAuthTest, ChallengeTokenizerMismatchedQuotesMultiple) { std::string challenge_str = "Digest qop=auth-int, algorithm=md5, realm=\"foo"; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Digest"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("qop"), parameters.name()); EXPECT_EQ(std::string("auth-int"), parameters.value()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("algorithm"), parameters.name()); EXPECT_EQ(std::string("md5"), parameters.value()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("foo"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); } // Use a name= property which has no value. TEST(HttpAuthTest, ChallengeTokenizerNoValue) { std::string challenge_str = "Digest qop="; HttpAuth::ChallengeTokenizer challenge( challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Digest"), challenge.scheme()); EXPECT_FALSE(parameters.GetNext()); EXPECT_FALSE(parameters.valid()); } // Specify multiple properties, comma separated. TEST(HttpAuthTest, ChallengeTokenizerMultiple) { std::string challenge_str = "Digest algorithm=md5, realm=\"Oblivion\", qop=auth-int"; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("Digest"), challenge.scheme()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("algorithm"), parameters.name()); EXPECT_EQ(std::string("md5"), parameters.value()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("realm"), parameters.name()); EXPECT_EQ(std::string("Oblivion"), parameters.value()); EXPECT_TRUE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("qop"), parameters.name()); EXPECT_EQ(std::string("auth-int"), parameters.value()); EXPECT_FALSE(parameters.GetNext()); EXPECT_TRUE(parameters.valid()); } // Use a challenge which has no property. TEST(HttpAuthTest, ChallengeTokenizerNoProperty) { std::string challenge_str = "NTLM"; HttpAuth::ChallengeTokenizer challenge( challenge_str.begin(), challenge_str.end()); HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs(); EXPECT_TRUE(parameters.valid()); EXPECT_EQ(std::string("NTLM"), challenge.scheme()); EXPECT_FALSE(parameters.GetNext()); } // Use a challenge with Base64 encoded token. TEST(HttpAuthTest, ChallengeTokenizerBase64) { std::string challenge_str = "NTLM SGVsbG8sIFdvcmxkCg==="; HttpAuth::ChallengeTokenizer challenge(challenge_str.begin(), challenge_str.end()); EXPECT_EQ(std::string("NTLM"), challenge.scheme()); // Notice the two equal statements below due to padding removal. EXPECT_EQ(std::string("SGVsbG8sIFdvcmxkCg=="), challenge.base64_param()); } TEST(HttpAuthTest, GetChallengeHeaderName) { std::string name; name = HttpAuth::GetChallengeHeaderName(HttpAuth::AUTH_SERVER); EXPECT_STREQ("WWW-Authenticate", name.c_str()); name = HttpAuth::GetChallengeHeaderName(HttpAuth::AUTH_PROXY); EXPECT_STREQ("Proxy-Authenticate", name.c_str()); } TEST(HttpAuthTest, GetAuthorizationHeaderName) { std::string name; name = HttpAuth::GetAuthorizationHeaderName(HttpAuth::AUTH_SERVER); EXPECT_STREQ("Authorization", name.c_str()); name = HttpAuth::GetAuthorizationHeaderName(HttpAuth::AUTH_PROXY); EXPECT_STREQ("Proxy-Authorization", name.c_str()); } } // namespace net
#include "Assert.h" #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <assert.h> #define assert_custom(_Expression, _Message, _File, _Line) (void)( (!!(_Expression)) || (__assert(_Message, _File, _Line), 0) ) #ifdef __cplusplus extern "C" { #endif void __OnAssert(const char* file, unsigned line, const char* description) { printf("Requirement (%ws) failed in file %ws line %u\r\n", description, file, line); assert_custom(0, description, file, line); } #ifdef __cplusplus } #endif
#include "neural/feature_fn.h" #include "util/includes.h" #include "data/globals.h" namespace vectorbook { namespace { // Indicates the identity of the author of the *action*. class ActionAuthorFeature : public FeatureExtractor<Action> { public: string FeatureName() const override { return "action_author"; } string EmbeddingGroup() const { return "user"; } Unique<string> ExtractValue(const Action &t) const override { return new string(t.user()); } }; // Indicates the identity of the author of the *broadcast*. class PostAuthorFeature : public FeatureExtractor<Action> { public: string FeatureName() const override { return "post_author"; } string EmbeddingGroup() const { return "user"; } Unique<string> ExtractValue(const Action &t) const override { return new string(t.author()); } }; FeatureExtractor<Action> *FromName(const string &name) { if (name == "action_author") { return new ActionAuthorFeature(); } if (name == "post_author") { return new PostAuthorFeature(); } return nullptr; } } // namespace FeatureExtractorList<Action> GetActionFeatures(const RepeatedPtrField<FeatureSpec>& feature_specs) { vector<unique_ptr<FeatureExtractor<Action>>> buffer; for (const auto &spec : feature_specs) { buffer.push_back(unique_ptr<FeatureExtractor<Action>>(FromName(spec.name()))); } return FeatureExtractorList<Action>(std::move(buffer)); } } // namespace vectorbook
#pragma once #include "render.hpp" #include <colex/colex.hpp> #include <glm/glm.hpp> #include <iostream> #include <vector> using namespace colex; namespace draw::line { /** * Returns how many elements each vertex has */ size_t vertex_size(); /** * Base class for line shapes */ template<typename T> class Base { /** * Returns how many vertices that must be drawn */ [[nodiscard]] size_t vertices_count() const { return static_cast<const T &>(*this).vertices_count(); } /** * Returns how many elements that must be drawn */ [[nodiscard]] size_t indices_count() const { return static_cast<const T &>(*this).indices_count(); } /** * Builds the line into a drawable shape */ [[nodiscard]] render::Line build(float width) const { return static_cast<const T &>(*this).build(width); } /** * Fills `vertices` and `indices` with the line. `v0` is the index * of the first vertex. */ void fill(float *vertices, unsigned int *indices, unsigned int v0) const { return static_cast<const T &>(*this).fill(vertices, indices, v0); } }; /** * A multi-segmented line as described in `theory/` */ class Line : public Base<Line> { public: /** * Creates a line from an initializer list */ Line(std::initializer_list<glm::vec2> points); /** * Creates a line from a vector */ explicit Line(std::vector<glm::vec2> points); /** * Creates a single segmented line from (x1, y1) to (x2, y2) */ Line(float x1, float y1, float x2, float y2); /** * Creates a line from an iterator */ template<typename I> explicit Line(iterator::Iterator<I> &&points) : points(std::move(points) | collect<std::vector>()) {} [[nodiscard]] size_t vertices_count() const; [[nodiscard]] size_t indices_count() const; [[nodiscard]] render::Line build(float width) const; void fill(float *vertices, unsigned int *indices, unsigned int v0) const; private: [[nodiscard]] size_t segments_count() const; [[nodiscard]] size_t intersections_count() const; std::vector<glm::vec2> points; }; /** * A composition of shapes. The composed elements * can be lines or previously composed lines. Hence, * arbitrarily complex line-shapes can be created */ template<typename L, typename R> class Composition : public Base<Composition<L, R>> { public: Composition(Base<L> &&a, Base<R> &&b) : a(static_cast<L &&>(a)) , b(static_cast<R &&>(b)) {} [[nodiscard]] size_t vertices_count() const { return a.vertices_count() + b.vertices_count(); } [[nodiscard]] size_t indices_count() const { return a.indices_count() + b.indices_count(); } void fill(float *vertices, unsigned int *indices, unsigned int v0) const { a.fill(vertices, indices, v0); b.fill(vertices + vertex_size() * a.vertices_count(), indices + a.indices_count(), v0 + a.vertices_count()); } [[nodiscard]] render::Line build(float width) const { std::vector<float> vertices(vertex_size() * vertices_count()); std::vector<unsigned int> indices(indices_count()); fill(vertices.data(), indices.data(), 0); return render::Line(std::move(vertices), std::move(indices), width); } private: L a; R b; }; /** * Composes two shapes through the `&` operator */ template<typename L, typename R> Composition<L, R> operator&(Base<L> &&a, Base<R> &&b) { return Composition<L, R>(std::move(a), std::move(b)); } } // namespace draw::line
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uritests.h" #include "guiutil.h" #include "walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?label=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString("Some Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=100&label=Some Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("nomadic://D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address", &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000&label=Some Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("nomadic:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000.0&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iotvideoindustry/v20201201/model/ModifySubscriptionStatusRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Iotvideoindustry::V20201201::Model; using namespace std; ModifySubscriptionStatusRequest::ModifySubscriptionStatusRequest() : m_deviceIdHasBeenSet(false), m_statusHasBeenSet(false), m_subscriptionItemHasBeenSet(false) { } string ModifySubscriptionStatusRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_deviceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeviceId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_deviceId.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_status, allocator); } if (m_subscriptionItemHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SubscriptionItem"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_subscriptionItem.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string ModifySubscriptionStatusRequest::GetDeviceId() const { return m_deviceId; } void ModifySubscriptionStatusRequest::SetDeviceId(const string& _deviceId) { m_deviceId = _deviceId; m_deviceIdHasBeenSet = true; } bool ModifySubscriptionStatusRequest::DeviceIdHasBeenSet() const { return m_deviceIdHasBeenSet; } int64_t ModifySubscriptionStatusRequest::GetStatus() const { return m_status; } void ModifySubscriptionStatusRequest::SetStatus(const int64_t& _status) { m_status = _status; m_statusHasBeenSet = true; } bool ModifySubscriptionStatusRequest::StatusHasBeenSet() const { return m_statusHasBeenSet; } string ModifySubscriptionStatusRequest::GetSubscriptionItem() const { return m_subscriptionItem; } void ModifySubscriptionStatusRequest::SetSubscriptionItem(const string& _subscriptionItem) { m_subscriptionItem = _subscriptionItem; m_subscriptionItemHasBeenSet = true; } bool ModifySubscriptionStatusRequest::SubscriptionItemHasBeenSet() const { return m_subscriptionItemHasBeenSet; }
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a valid gamertip address")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a valid gamertip address")); ui->signatureIn_VM->setPlaceholderText(tr("Enter gamertip signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::gamertipAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::gamertipAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CgamertipAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CgamertipAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CgamertipAddress(key.GetPubKey().GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
//****************************************************************** // // Copyright 2015 Samsung Electronics 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 "UnitTestHelper.h" #include "SceneList.h" #include "RCSResourceObject.h" #include "RCSRemoteResourceObject.h" #include "SceneCommons.h" #include "OCPlatform.h" #include <condition_variable> #include <mutex> #include <iostream> using namespace std; using namespace OIC::Service; using namespace OC; typedef std::function<void (int)> ExecuteCallback; constexpr char RESOURCE_URI[]{ "/a/light" }; constexpr char RESOURCE_TYPE[]{ "core.light" }; constexpr char RESOURCE_URI2[]{ "/a/fan" }; constexpr char RESOURCE_TYPE2[]{ "core.fan" }; constexpr char KEY[]{ "power" }; constexpr char VALUE[]{ "off" }; constexpr char KEY_2[]{ "state" }; constexpr char VALUE_2[]{ "100" }; class SceneTest: public TestWithMock { protected: void SetUp() { TestWithMock::SetUp(); pSceneList = SceneList::getInstance(); } void waitForCb(int watingTime) { std::unique_lock< std::mutex > lock{ mutex }; cond.wait_for(lock, std::chrono::milliseconds{ watingTime }); } void proceed() { cond.notify_all(); } void createSceneCollection() { pSceneCollection = pSceneList->addNewSceneCollection(); } void createScene() { pScene1 = pSceneCollection->addNewScene("SceneTestName_1"); pScene2 = pSceneCollection->addNewScene("SceneTestName_2"); } void createServer(const std::string& resourceUri1, const std::string& resourceUri2) { auto pResource1 = RCSResourceObject::Builder( resourceUri1, RESOURCE_TYPE, DEFAULT_INTERFACE).build(); pResource1->setAttribute(KEY, VALUE); auto ocResourcePtr = OC::OCPlatform::constructResourceObject( "coap://" + SceneUtils::getNetAddress(), resourceUri1, OCConnectivityType::CT_ADAPTER_IP, false, pResource1->getTypes(), pResource1->getInterfaces()); pRemoteResource1 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr); auto pResource2 = RCSResourceObject::Builder( resourceUri2, RESOURCE_TYPE2, DEFAULT_INTERFACE).build(); pResource2->setAttribute(KEY_2, VALUE_2); ocResourcePtr = OC::OCPlatform::constructResourceObject( "coap://" + SceneUtils::getNetAddress(), resourceUri2, OCConnectivityType::CT_ADAPTER_IP, false, pResource2->getTypes(), pResource2->getInterfaces()); pRemoteResource2 = RCSRemoteResourceObject::fromOCResource(ocResourcePtr); } public: SceneList* pSceneList; shared_ptr<SceneCollection> pSceneCollection; shared_ptr<Scene> pScene1; shared_ptr<Scene> pScene2; RCSRemoteResourceObject::Ptr pRemoteResource1; RCSRemoteResourceObject::Ptr pRemoteResource2; private: std::condition_variable cond; std::mutex mutex; }; void executeCallback(int /*code*/) {}; TEST_F(SceneTest, createSceneInstance) { createSceneCollection(); createScene(); ASSERT_EQ("SceneTestName_1", pScene1->getName()); ASSERT_EQ("SceneTestName_2", pScene2->getName()); } TEST_F(SceneTest, createSceneInstanceByEmptyName) { createSceneCollection(); ASSERT_THROW(pSceneCollection->addNewScene(""), RCSInvalidParameterException); } TEST_F(SceneTest, getSceneInstanceBySceneName) { createSceneCollection(); createScene(); auto scene = pSceneCollection->getScene("SceneTestName_2"); EXPECT_EQ("SceneTestName_2", scene->getName()); } TEST_F(SceneTest, getAllSceneInstance) { createSceneCollection(); createScene(); vector<string> sceneNames{"SceneTestName_1", "SceneTestName_2"}; auto scenes = pSceneCollection->getScenes(); int count = 0; for(const auto &it : scenes) { for (const auto &name : sceneNames) { if(it.first == name) { count++; break; } } } ASSERT_EQ(count, 2); } TEST_F(SceneTest, getSceneActionUsingRemoteResource) { createServer(RESOURCE_URI, RESOURCE_URI2); createSceneCollection(); createScene(); auto pSceneAction1 = pScene1->addNewSceneAction(pRemoteResource1, KEY, VALUE); pSceneAction1->resetExecutionParameter(KEY_2, VALUE_2); ASSERT_EQ(pScene1->getSceneAction(pRemoteResource1)->getExecutionParameter(), pSceneAction1->getExecutionParameter()); } TEST_F(SceneTest, getSceneActions) { createServer("/a/testuri1_1", "/a/testuri1_2"); createSceneCollection(); createScene(); auto pSceneAction1 = pScene1->addNewSceneAction(pRemoteResource1, KEY, VALUE); auto pSceneAction2 = pScene1->addNewSceneAction(pRemoteResource2, KEY, VALUE); for(const auto & it : pScene1->getSceneActions()) { ASSERT_EQ(it->getExecutionParameter(), pSceneAction1->getExecutionParameter()); } } TEST_F(SceneTest, executeScene) { mocks.ExpectCallFunc(executeCallback).Do([this](int){ proceed(); }); createServer("/a/testuri2_1", "/a/testuri2_2"); createSceneCollection(); createScene(); pScene1->addNewSceneAction(pRemoteResource1, KEY, "on"); pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2); pScene1->execute(executeCallback); waitForCb(3000); } TEST_F(SceneTest, executeSceneUsingEmptyCallback) { createServer("/a/testuri3_1", "/a/testuri3_2"); createSceneCollection(); createScene(); pScene1->addNewSceneAction(pRemoteResource1, KEY, "on"); pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2); ASSERT_THROW(pScene1->execute(nullptr), RCSInvalidParameterException); }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef HERMESVM_SERIALIZE #include "hermes/ADT/CompactArray.h" #include "hermes/VM/Deserializer.h" #include "hermes/VM/GCPointer-inline.h" #include "hermes/VM/GCPointer.h" #include "hermes/VM/JSArrayBuffer.h" #include "hermes/VM/JSDataView.h" #include "hermes/VM/JSNativeFunctions.h" #include "hermes/VM/JSTypedArray.h" #include "hermes/VM/JSWeakMapImpl.h" #include "hermes/VM/PrimitiveBox.h" #include "hermes/VM/Runtime.h" #include "JSLib/JSLibInternal.h" #include "llvm/Support/Debug.h" #define DEBUG_TYPE "serialize" namespace hermes { namespace vm { using DeserializeCallBack = void(Deserializer &d, CellKind kind); static DeserializeCallBack *deserializeImpl[] = { #define CELL_KIND(name) name##Deserialize, #include "hermes/VM/CellKinds.def" #undef CELL_KIND }; void Deserializer::deserializeCell(uint8_t kind) { assert( (CellKind)kind != CellKind::ArrayStorageKind && "ArrayStorage should be serialized/deserialized with its owner."); deserializeImpl[kind](*this, (CellKind)kind); } void Deserializer::deserializeCompactTable(CompactTable &table) { auto size = readInt<uint32_t>(); auto scale = (CompactArray::Scale)readInt<uint8_t>(); CompactArray tmp(size, scale); for (uint32_t idx = 0; idx < size; ++idx) tmp.set(idx, readInt<uint32_t>()); table.asArray().swap(tmp); } void Deserializer::flushRelocationQueue() { while (!relocationQueue_.empty()) { auto entry = relocationQueue_.front(); relocationQueue_.pop_front(); assert(entry.id < objectTable_.size() && "invalid relocation id"); void *ptr = objectTable_[entry.id]; assert(ptr && "pointer relocation cannot be resolved"); updateAddress(entry.address, ptr, entry.kind); } } void Deserializer::init( ExternalPointersVectorFunction *externalPointersVectorCallBack) { // Do the sanity check of the header first. readHeader(); // Relocation table size and string buffers are all at the end of the // MemoryBuffer. Let's start reading from the back. const char *ptr = buffer_->getBufferEnd(); uint32_t size; // Read map size and resize relocation table. size = readBackwards(ptr); objectTable_.resize(size); // Read size of char16Buf_. // Note this is the total size of the buffer and may include padding. size = readBackwards(ptr); // Move ptr to the beginning of char16Buf_. ptr -= size; if (size > 0) { // Has char16Buf_, reconstruct the buffer here. assert(ptr >= buffer_->getBufferStart() && "wrong char16Buf_ size"); // size is buffer size in bytes. Let's calculate the end first before // casting to char16_t *. // Ensure we are aligned. uint32_t aligningOffset = llvm::alignTo(size, alignof(char16_t)) - size; assert(aligningOffset <= size && "aligning offset should not exceed size"); assert( (intptr_t)(ptr + aligningOffset) % alignof(char16_t) == 0 && "Pointer should be aligned for char16"); char16Buf_ = ArrayRef<char16_t>( (const char16_t *)(ptr + aligningOffset), (const char16_t *)(ptr + size - aligningOffset)); } // Read size of charBuf_. size = readBackwards(ptr); // Move ptr to the beginning of charBuf_. ptr -= size; if (size > 0) { // Has charBuf_, reconstruct the buffer here. assert(ptr >= buffer_->getBufferStart() && "wrong charBuf_ size"); charBuf_ = ArrayRef<char>(ptr, size); } // Map nullptr to 0. objectTable_[0] = 0; // Populate relocation table for native functions and constructors. size_t idx = 1; #define NATIVE_FUNCTION(func) \ assert(!objectTable_[idx]); \ objectTable_[idx] = (void *)func; \ LLVM_DEBUG( \ llvm::dbgs() << idx << ", " << #func << ", " << (void *)func << "\n"); \ idx++; #define NATIVE_FUNCTION_TYPED(func, type) \ assert(!objectTable_[idx]); \ objectTable_[idx] = (void *)func<type>; \ LLVM_DEBUG( \ llvm::dbgs() << idx << ", " << #func << "<" << #type << ">, " \ << (void *)func<type> << "\n"); \ idx++; #define NATIVE_FUNCTION_TYPED_2(func, type, type2) \ assert(!objectTable_[idx]); \ objectTable_[idx] = (void *)func<type, type2>; \ LLVM_DEBUG( \ llvm::dbgs() << idx << ", " << #func << "<" << #type << ", " << #type2 \ << ">, " << ((void *)func<type, type2>) << "\n"); \ idx++; NativeConstructor::CreatorFunction *funcPtr; #define NATIVE_CONSTRUCTOR(func) \ funcPtr = func; \ assert(!objectTable_[idx]); \ objectTable_[idx] = (void *)funcPtr; \ LLVM_DEBUG( \ llvm::dbgs() << idx << ", " << #func << ", " << (void *)funcPtr \ << "\n"); \ idx++; #define NATIVE_CONSTRUCTOR_TYPED(classname, type, type2, func) \ funcPtr = func<classname<type, type2>>; \ assert(!objectTable_[idx]); \ objectTable_[idx] = (void *)funcPtr; \ LLVM_DEBUG( \ llvm::dbgs() << idx << ", " << #func << "<" << #classname << "<" \ << #type << ", " << #type2 << ">>" \ << ", " << (void *)funcPtr << "\n"); \ idx++; #include "hermes/VM/NativeFunctions.def" #undef NATIVE_CONSTRUCTOR // Map external function pointers. for (auto *ptr : externalPointersVectorCallBack()) { assert(!objectTable_[idx] && "External pointer should only be mapped once"); objectTable_[idx] = ptr; idx++; } } void Deserializer::readHeader() { SerializeHeader readHeader; readData(&readHeader, sizeof(SerializeHeader)); if (readHeader.magic != SD_MAGIC) { hermes_fatal("Not a serialize file or endianness do not match"); } if (readHeader.version != SD_HEADER_VERSION) { hermes_fatal("Serialize header versions do not match"); } if (readHeader.nativeFunctionTableVersion != NATIVE_FUNCTION_VERSION) { hermes_fatal("Native function table versions do not match"); } if (runtime_->getHeap().size() < readHeader.heapSize) { hermes_fatal( (llvm::Twine("Deserialize heap size less than Serialize heap size(") + llvm::StringRef(std::to_string(readHeader.heapSize)) + llvm::Twine(" bytes), try increase initial heap size")) .str()); } #define CHECK_HEADER_SET(header, field) \ if (!header.field) { \ hermes_fatal("Serialize/Deserialize configs do not match"); \ } #define CHECK_HEADER_UNSET(header, field) \ if (header.field) { \ hermes_fatal("Serialize/Deserialize configs do not match"); \ } #ifndef NDEBUG CHECK_HEADER_SET(readHeader, isDebug); // isDebug #else CHECK_HEADER_UNSET(readHeader, isDebug); #endif #ifdef HERMES_ENABLE_DEBUGGER CHECK_HEADER_SET(readHeader, isEnableDebugger); // isEnableDebugger. #else CHECK_HEADER_UNSET(readHeader, isEnableDebugger); #endif runtime_->checkHeaderRuntimeConfig(readHeader); } void Deserializer::readAndCheckOffset() { size_t currentOffset = offset_; size_t bytes = readInt<size_t>(); if (currentOffset != bytes) { hermes_fatal("Deserializer sanity check failed: offset don't match"); } } void Deserializer::updateAddress( void *address, void *ptrVal, RelocationKind kind) { switch (kind) { case RelocationKind::NativePointer: *(void **)address = ptrVal; return; case RelocationKind::GCPointer: ((GCPointerBase *)address)->set(runtime_, ptrVal, &runtime_->getHeap()); return; case RelocationKind::HermesValue: ((HermesValue *)address)->unsafeUpdatePointer(ptrVal); return; } llvm_unreachable("Invalid relocation kind"); } } // namespace vm } // namespace hermes #endif
/*ckwg +29 * Copyright 2011-2018 by Kitware, 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 name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file collate_process.cxx * * \brief Implementation of the collate process. */ #include "collate_process.h" #include <sprokit/pipeline/datum.h> #include <sprokit/pipeline/edge.h> #include <sprokit/pipeline/process_exception.h> #include <sprokit/pipeline/stamp.h> #include <vital/util/string.h> #include <map> #include <string> namespace sprokit { /** * \class collate_process * * \brief A process for collating input data from multiple input edges. * * \note Edges for a \portvar{tag} may \em only be connected after the * \port{status/\portvar{tag}} is connected to. Before this connection happens, * the other ports to not exist and will cause errors. In short: The first * connection for any \portvar{tag} must be \port{status/\portvar{tag}}. * * \process Collate incoming data into a single stream. A collation * operation reads input from a set of input ports and serializes that * data to a single output port. This collation process can handle * multiple collation operations. Each set of collation ports is * identified by a unique \b tag. * * \iports * * \iport{status/\portvar{tag}} The status of the result \portvar{tag}. * \iport{coll/\portvar{tag}/\portvar{item}} A port to collate data for * \portvar{tag} from. Data is * collated from ports in * ASCII-betical order. * * \oports * * \oport{res/\portvar{tag}} The collated result \portvar{tag}. * * \reqs * * \req Each input port \port{status/\portvar{tag}} must be connected. * \req Each \portvar{tag} must have at least two inputs to collate. * \req Each output port \port{res/\portvar{tag}} must be connected. * * The status port is used to signal upstream status about the collate * set. Only complete and flush packet types are handled. Regular data * packets are ignored on that port. * * This process automatically makes the input and output types for * each \b tag the same based on the type of the port that is first * connected. * * \note * It is not immediately apparent how the input ports become sorted in * ASCII-betical order on "item" order. * * \code process collate :: collate_process # -- Connect collate set "input1" # status port connect foo.p1_stat to collate.status/input1 # actual data ports connect foo_1.out to collate.coll/input1/A connect foo_2.out to collate.coll/input1/B connect collate.res/input1 to bar.input # -- Connect collate set "input2" # status port can feed multiple groups connect foo.p1_stat to collate.status/input2 # actual data ports connect foo_1.out to collate.coll/input2/A connect foo_2.out to collate.coll/input2/B connect foo_3.out to collate.coll/input2/C connect collate.res/input2 to bar.other * \endcode * * \todo Add configuration to allow forcing a number of inputs for a result. * \todo Add configuration to allow same number of sources for all results. * * \ingroup process_flow */ class collate_process::priv { public: priv(); ~priv(); typedef port_t tag_t; // This class stores info for each tag. class tag_info { public: tag_info(); ~tag_info(); ports_t ports; // list of port names ports_t::const_iterator cur_port; }; typedef std::map<tag_t, tag_info> tag_data_t; tag_data_t tag_data; // tag table tag_t tag_for_coll_port(port_t const& port) const; static port_t const res_sep; static port_t const port_res_prefix; static port_t const port_status_prefix; static port_t const port_coll_prefix; }; process::port_t const collate_process::priv::res_sep = port_t("/"); process::port_t const collate_process::priv::port_res_prefix = port_t("res") + res_sep; process::port_t const collate_process::priv::port_status_prefix = port_t("status") + res_sep; process::port_t const collate_process::priv::port_coll_prefix = port_t("coll") + res_sep; /** * \internal * * Ports on the \ref distribute_process are broken down as follows: * * \portvar{type}/\portvar{tag}[/\portvar{item}] * * The port name is broken down as follows: * * <dl> * \term{\portvar{type}} * \termdef{The type of the port. This must be one of \type{res}, * \type{status}, or \type{coll}.} * \term{\portvar{tag}} * \termdef{The name of the stream the port is associated with.} * \term{\portvar{item}} * \termdef{Only required for \type{coll}-type ports. Data from the same * \portvar{tag} stream from its \type{res} port is collected in sorted order * over all of the \type{coll} ports.} * </dl> * * The available port types are: * * <dl> * \term{\type{status}} * \termdef{This is the trigger port for the associated tagged stream. When * this port for the given tag is connected to, the \type{res} and \type{coll} * ports for the tag will not cause errors.} * \term{\type{res}} * \termdef{This port for the given tag is where the data for a stream leaves * the process. The stamp from the \type{status} port for the \portvar{tag} is * applied.} * \term{\type{coll}} * \termdef{These ports for a given \portvar{tag} receive data from a set of * sources, likely made by the \ref distribute_process. Data is collected in * sorted ordef of the \type{item} name and sent out the \type{res} port for * the \portvar{tag}.} * </dl> */ collate_process ::collate_process(kwiver::vital::config_block_sptr const& config) : process(config) , d(new priv) { // This process manages its own inputs. this->set_data_checking_level(check_none); } collate_process ::~collate_process() { } // ------------------------------------------------------------------ // Post connection processing void collate_process ::_init() { for (priv::tag_data_t::value_type& tag_data : d->tag_data) { priv::tag_t const& tag = tag_data.first; priv::tag_info& info = tag_data.second; ports_t const& ports = info.ports; // list of port names if (ports.size() < 2) { std::string const reason = "There must be at least two ports to collate " "to for the \"" + tag + "\" result data"; VITAL_THROW( invalid_configuration_exception, name(), reason); } // Now here's some port frequency magic frequency_component_t const ratio = ports.size(); port_frequency_t const freq = port_frequency_t(1, ratio); // Set port frequency for all input ports. for (port_t const& port : ports) { set_input_port_frequency(port, freq); } // Set iterator to start of list. info.cur_port = ports.begin(); } process::_init(); } // ------------------------------------------------------------------ void collate_process ::_reset() { for (priv::tag_data_t::value_type const& tag_data : d->tag_data) { priv::tag_t const& tag = tag_data.first; port_t const output_port = priv::port_res_prefix + tag; port_t const status_port = priv::port_status_prefix + tag; priv::tag_info const& info = tag_data.second; ports_t const& ports = info.ports; for (port_t const& port : ports) { remove_input_port(port); } remove_input_port(status_port); remove_output_port(output_port); } d->tag_data.clear(); process::_reset(); } // ------------------------------------------------------------------ void collate_process ::_step() { ports_t complete_ports; // Loop over all tags (input groups) for (priv::tag_data_t::value_type& tag_data : d->tag_data) { priv::tag_t const& tag = tag_data.first; port_t const output_port = priv::port_res_prefix + tag; port_t const status_port = priv::port_status_prefix + tag; priv::tag_info& info = tag_data.second; // Check status input port. This will give us information on the // upstream process. edge_datum_t const status_edat = grab_from_port(status_port); datum_t const& status_dat = status_edat.datum; datum::type_t const status_type = status_dat->type(); // Test to see if complete. bool const is_complete = (status_type == datum::complete); if (is_complete || (status_type == datum::flush)) { // echo the input to the output port push_to_port(output_port, status_edat); // Flush this set of inputs for (port_t const& port : info.ports) { (void)grab_from_port(port); } // If the upstream process is done, then mark this tag as done. if (is_complete) { complete_ports.push_back(tag); continue; } } else { // There is real data on the input ports. Grab data from the // current input port and push to the output. edge_datum_t const coll_dat = grab_from_port(*info.cur_port); push_to_port(output_port, coll_dat); } // Advance to next port in the group, and wrap at the end. ++info.cur_port; if (info.cur_port == info.ports.end()) { info.cur_port = info.ports.begin(); } } // end foreach // Process all ports/tags that have completed. When a status port // reports complete on a tag, that tag is erased from the local // map. When that map is empty, then we are all done and can complete. for (port_t const& port : complete_ports) { d->tag_data.erase(port); } if (d->tag_data.empty()) { mark_process_as_complete(); } process::_step(); } // ------------------------------------------------------------------ process::properties_t collate_process ::_properties() const { properties_t consts = process::_properties(); consts.insert(property_unsync_input); return consts; } // ------------------------------------------------------------------ // Intercept input port connection so we can create the requested port void collate_process ::input_port_undefined(port_t const& port) { // Is this a status port (starts with "status/") if (kwiver::vital::starts_with(port, priv::port_status_prefix)) { // Extract TAG sub-string from port name priv::tag_t const tag = port.substr(priv::port_status_prefix.size()); // If TAG does not exist if ( ! d->tag_data.count(tag) ) { // This is the first time the status port is being connected to. priv::tag_info info; d->tag_data[tag] = info; port_flags_t required; required.insert(flag_required); // Create input status port "tag" declare_input_port( port, type_none, required, port_description_t("The original status for the result " + tag + ".")); // Create output port "res/tag" declare_output_port( priv::port_res_prefix + tag, type_flow_dependent + tag, // note the tag magic on port type required, port_description_t("The output port for " + tag + ".")); } } // end status port // Get the canonical tag string from a "coll/xx" port name. // Note that this name will be empty for "status/xx" port names priv::tag_t const tag = d->tag_for_coll_port(port); // If the status port has already been created for this "coll/" port. if ( ! tag.empty() ) { // Get entry based on the tag string priv::tag_info& info = d->tag_data[tag]; // Add this port to the info list for this tag info.ports.push_back(port); port_flags_t required; required.insert(flag_required); // Open an input port for the name declare_input_port( port, type_flow_dependent + tag, // note the tag magic on port type required, port_description_t("An input for the " + tag + " data.")); } } // ------------------------------------------------------------------ collate_process::priv ::priv() : tag_data() { } collate_process::priv ::~priv() { } // ------------------------------------------------------------------ /* * @brief Find tag name that corresponds to the port name. * * This method looks through the list of current tags to see if the * supplied port is in that table. * * @param port Name of the port * * @return Tag name */ collate_process::priv::tag_t collate_process::priv ::tag_for_coll_port(port_t const& port) const { // Does this port start with "coll/" if (kwiver::vital::starts_with(port, priv::port_coll_prefix)) { // Get the part of the port name after the prefix // This could be "tag/item" port_t const no_prefix = port.substr(priv::port_coll_prefix.size()); // loop over all tags seen so far for (priv::tag_data_t::value_type const& data : tag_data) { tag_t const& tag = data.first; // tag string port_t const tag_prefix = tag + priv::res_sep; // If the port name without the prefix is "tag/*" then return // base tag string if (kwiver::vital::starts_with(no_prefix, tag_prefix)) { return tag; } } } return tag_t(); } // ------------------------------------------------------------------ collate_process::priv::tag_info ::tag_info() : ports() , cur_port() { } collate_process::priv::tag_info ::~tag_info() { } } // end namespace
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "FortniteCloneCharacter.h" #include "FortniteClonePlayerController.h" #include "FortniteClonePlayerState.h" #include "ThirdPersonAnimInstance.h" #include "ProjectileActor.h" #include "StormActor.h" #include "FortniteCloneHUD.h" #include "WeaponActor.h" #include "BuildingActor.h" #include "HealingActor.h" #include "AmmunitionActor.h" #include "Engine/Engine.h" #include "UnrealNetwork.h" #include "Engine/ActorChannel.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "Runtime/Engine/Classes/Kismet/GameplayStatics.h" #include "Runtime/Engine/Classes/Materials/Material.h" DEFINE_LOG_CATEGORY(LogFortniteCloneCharacter); ////////////////////////////////////////////////////////////////////////// // AFortniteCloneCharacter AFortniteCloneCharacter::AFortniteCloneCharacter() { bReplicates = true; // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // Set up capsule component for detecting overlap TriggerCapsule = CreateDefaultSubobject<UCapsuleComponent>(TEXT("Trigger Capsule")); TriggerCapsule->InitCapsuleSize(42.f, 96.0f);; TriggerCapsule->SetCollisionProfileName(TEXT("Trigger")); TriggerCapsule->SetupAttachment(RootComponent); TriggerCapsule->OnComponentBeginOverlap.AddDynamic(this, &AFortniteCloneCharacter::OnOverlapBegin); TriggerCapsule->OnComponentEndOverlap.AddDynamic(this, &AFortniteCloneCharacter::OnOverlapEnd); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm CurrentWeaponType = 0; CurrentHealingItemType = -1; CurrentBuildingMaterial = 0; BuildingPreview = nullptr; // Animinstance properties IsWalking = false; IsRunning = false; HoldingWeapon = false; AimedIn = false; HoldingWeaponType = 0; AimPitch = 0.0; AimYaw = 0.0; InterpSpeed = 15.0; //change this to set aim sensitivity WalkingX = 0; WalkingY = 0; RunningX = 0; RunningY = 0; InStorm = true; CurrentStructureId = 0; // Playerstate properties /*InBuildMode = false; BuildMode = FString("None"); HoldingWeapon = false; HoldingHealingItem = false; AimedIn = false; EquippedWeapons.Add(0); //pickaxe EquippedWeaponsAmmunition.Add(0); // pickaxe EquippedWeaponsAmmunition.Add(0); // assault rifle EquippedWeaponsAmmunition.Add(0); // shotgun EquippedWeaponsClips.Add(0); // pickaxe EquippedWeaponsClips.Add(0); // assault rifle EquippedWeaponsClips.Add(0); // shotgun MaterialCounts.Add(0); // wood MaterialCounts.Add(0); // stone MaterialCounts.Add(0); // steel CurrentWeapon = 0; JustShotRifle = false; JustShotShotgun = false; JustSwungPickaxe = false; JustUsedHealingItem = false; JustReloadedRifle = false; JustReloadedShotgun = false; KillCount = 0;*/ // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void AFortniteCloneCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AFortniteCloneCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AFortniteCloneCharacter::MoveRight); PlayerInputComponent->BindAxis("Sprint", this, &AFortniteCloneCharacter::Sprint); PlayerInputComponent->BindAction("Walk", IE_Pressed, this, &AFortniteCloneCharacter::StartWalking); PlayerInputComponent->BindAction("Walk", IE_Released, this, &AFortniteCloneCharacter::StopWalking); PlayerInputComponent->BindAction("PreviewWall", IE_Pressed, this, &AFortniteCloneCharacter::PreviewWall); PlayerInputComponent->BindAction("PreviewRamp", IE_Pressed, this, &AFortniteCloneCharacter::PreviewRamp); PlayerInputComponent->BindAction("PreviewFloor", IE_Pressed, this, &AFortniteCloneCharacter::PreviewFloor); PlayerInputComponent->BindAction("SwitchBuildingMaterial", IE_Pressed, this, &AFortniteCloneCharacter::SwitchBuildingMaterial); PlayerInputComponent->BindAction("ShootGun", IE_Pressed, this, &AFortniteCloneCharacter::ShootGun); PlayerInputComponent->BindAction("UseHealingItem", IE_Pressed, this, &AFortniteCloneCharacter::UseHealingItem); PlayerInputComponent->BindAction("Reload", IE_Pressed, this, &AFortniteCloneCharacter::Reload); PlayerInputComponent->BindAction("HoldPickaxe", IE_Pressed, this, &AFortniteCloneCharacter::HoldPickaxe); PlayerInputComponent->BindAction("HoldAssaultRifle", IE_Pressed, this, &AFortniteCloneCharacter::HoldAssaultRifle); PlayerInputComponent->BindAction("HoldShotgun", IE_Pressed, this, &AFortniteCloneCharacter::HoldShotgun); PlayerInputComponent->BindAction("HoldBandage", IE_Pressed, this, &AFortniteCloneCharacter::HoldBandage); PlayerInputComponent->BindAction("HoldPotion", IE_Pressed, this, &AFortniteCloneCharacter::HoldPotion); PlayerInputComponent->BindAction("Ironsights", IE_Pressed, this, &AFortniteCloneCharacter::AimGunIn); PlayerInputComponent->BindAction("Ironsights", IE_Released, this, &AFortniteCloneCharacter::AimGunOut); PlayerInputComponent->BindAction("OpenSettings", IE_Pressed, this, &AFortniteCloneCharacter::OpenSettingsMenu); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AFortniteCloneCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AFortniteCloneCharacter::LookUpAtRate); PlayerInputComponent->BindAxis("BuildStructure", this, &AFortniteCloneCharacter::BuildStructure); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AFortniteCloneCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AFortniteCloneCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AFortniteCloneCharacter::OnResetVR); } void AFortniteCloneCharacter::BeginPlay() { Super::BeginPlay(); //GetMesh()->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::OnlyTickPoseWhenRendered; //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Client ") + FString::FromInt(ENetMode::NM_Client) + FString(" server ") + FString::FromInt(ENetMode::NM_DedicatedServer)); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(GetNetMode())); /*if (GetNetMode() != ENetMode::NM_Client || GetNetMode() != ENetMode::NM_Standalone) { return; }*/ if (HasAuthority()) { if (WeaponClasses[CurrentWeaponType]) { // for some reason I can't call clientgetweapontransform here FName WeaponSocketName = TEXT("hand_right_socket_pickaxe"); FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget, EAttachmentRule::KeepRelative, EAttachmentRule::KeepWorld, true); FTransform SpawnTransform(GetActorRotation(), GetActorLocation()); CurrentWeapon = Cast<AWeaponActor>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, WeaponClasses[CurrentWeaponType], SpawnTransform)); if (CurrentWeapon != nullptr) { //spawnactor has no way of passing parameters so need to use begindeferredactorspawn and finishspawningactor CurrentWeapon->Holder = this; UGameplayStatics::FinishSpawningActor(CurrentWeapon, SpawnTransform); UStaticMeshComponent* WeaponStaticMeshComponent = Cast<UStaticMeshComponent>(CurrentWeapon->GetComponentByClass(UStaticMeshComponent::StaticClass())); WeaponStaticMeshComponent->AttachToComponent(this->GetMesh(), AttachmentRules, WeaponSocketName); HoldingWeapon = true; AimedIn = false; HoldingWeaponType = 1; } } // find the storm and keep a reference to it for damage purposes TArray<AActor*> StormActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStormActor::StaticClass(), StormActors); if (StormActors.Num() > 0) { if (StormActors[0] != nullptr) { CurrentStorm = Cast<AStormActor>(StormActors[0]); } } // set skin if (GetMesh()) { MaterialOrMaterialInstance = FMath::RandRange(0, 1); CurrentSkin = FMath::RandRange(0, 1); USkeletalMeshComponent* CharacterMesh = GetMesh(); if (MaterialOrMaterialInstance == 0) { // assign UMaterial CharacterMesh->SetMaterial(0, SkinMaterials[CurrentSkin]); } else { // assign UMaterialInstance CharacterMesh->SetMaterial(0, SkinMaterialInstances[CurrentSkin]); } SkinInitialized = true; } FTimerHandle StormDamageTimerHandle; GetWorldTimerManager().SetTimer(StormDamageTimerHandle, this, &AFortniteCloneCharacter::ServerApplyStormDamage, 1.0f, true); } } void AFortniteCloneCharacter::PostInitializeComponents() { Super::PostInitializeComponents(); if (HasAuthority()) { // Objects only replicate from server to client. If we didn't guard this // the client would create the object just fine but it would get replaced // by the server version (more accurately the property would be replaced to // point to the version from the server. The one the client allocated would // eventually be garbage collected. //AnimInstance = NewObject<UThirdPersonAnimInstance>(this); // NOTE: Very important, objects Outer must be our Actor! } } bool AFortniteCloneCharacter::ReplicateSubobjects(class UActorChannel *Channel, class FOutBunch *Bunch, FReplicationFlags *RepFlags) { bool WroteSomething = Super::ReplicateSubobjects(Channel, Bunch, RepFlags); /*if (AnimInstance != nullptr) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("replicated ") + FString::FromInt(GetNetMode())); WroteSomething |= Channel->ReplicateSubobject(AnimInstance, *Bunch, *RepFlags); } if (State != nullptr) { WroteSomething |= Channel->ReplicateSubobject(State, *Bunch, *RepFlags); } if (BuildingPreview != nullptr) { WroteSomething |= Channel->ReplicateSubobject(BuildingPreview, *Bunch, *RepFlags); }*/ return WroteSomething; } void AFortniteCloneCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AFortniteCloneCharacter, BuildingPreview); DOREPLIFETIME(AFortniteCloneCharacter, CurrentBuildingMaterial); DOREPLIFETIME(AFortniteCloneCharacter, CurrentHealingItem); DOREPLIFETIME(AFortniteCloneCharacter, CurrentHealingItemType); DOREPLIFETIME(AFortniteCloneCharacter, CurrentWeapon); DOREPLIFETIME(AFortniteCloneCharacter, CurrentStorm); DOREPLIFETIME(AFortniteCloneCharacter, CurrentWeaponType); DOREPLIFETIME(AFortniteCloneCharacter, Health); DOREPLIFETIME(AFortniteCloneCharacter, Shield); DOREPLIFETIME(AFortniteCloneCharacter, IsWalking); DOREPLIFETIME(AFortniteCloneCharacter, IsRunning); DOREPLIFETIME(AFortniteCloneCharacter, WalkingX); DOREPLIFETIME(AFortniteCloneCharacter, WalkingY); DOREPLIFETIME(AFortniteCloneCharacter, RunningX); DOREPLIFETIME(AFortniteCloneCharacter, RunningY); DOREPLIFETIME(AFortniteCloneCharacter, HoldingWeapon); DOREPLIFETIME(AFortniteCloneCharacter, HoldingWeaponType); DOREPLIFETIME(AFortniteCloneCharacter, AimedIn); DOREPLIFETIME(AFortniteCloneCharacter, AimPitch); DOREPLIFETIME(AFortniteCloneCharacter, AimYaw); DOREPLIFETIME(AFortniteCloneCharacter, InterpSpeed); DOREPLIFETIME(AFortniteCloneCharacter, InStorm); DOREPLIFETIME(AFortniteCloneCharacter, SkinInitialized); DOREPLIFETIME(AFortniteCloneCharacter, MaterialOrMaterialInstance); DOREPLIFETIME(AFortniteCloneCharacter, CurrentSkin); } void AFortniteCloneCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Tick mode ") + FString::FromInt(GetNetMode())); FVector DirectionVector = FVector(0, AimYaw, AimPitch); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Tick mode ") + FString::SanitizeFloat(DirectionVector.Z)); if (HasAuthority()) { // TODO: building preview should only be spawned client side if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); //destroy the last structure preview BuildingPreview = nullptr; } if (State->InBuildMode) { if (State->BuildMode == FString("Wall")) { FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(200.0, 50.0, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 2.0); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } //LogMsg = FString("Current building material ") + FString::FromInt(CurrentBuildingMaterial) + FString(" ") + FString::SanitizeFloat(GridRotationYaw) + FString(" ") + FString::SanitizeFloat(ProjectedRotation.Yaw); //UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg); if (CurrentBuildingMaterial >= 0 && CurrentBuildingMaterial <= 2) { if (WallPreviewClasses.IsValidIndex(CurrentBuildingMaterial)) { if (WallPreviewClasses[CurrentBuildingMaterial] != nullptr) { BuildingPreview = GetWorld()->SpawnActor<ABuildingActor>(WallPreviewClasses[CurrentBuildingMaterial], GridLocation, GridRotation); //set the new wall preview } } } } if (State->BuildMode == FString("Ramp")) { // TODO print out directionvector.z (looking straight forward vs up and down affects x value) // TODO check why the overlapping function when building is not working //original 400, 200, 2 FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(50.0, 6.25, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 1.5); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } /*LogMsg = FString("Current building material ") + FString::FromInt(CurrentBuildingMaterial) + FString(" ") + FString::SanitizeFloat(GridRotationYaw) + FString(" ") + FString::SanitizeFloat(ProjectedRotation.Yaw); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ if (CurrentBuildingMaterial >= 0 && CurrentBuildingMaterial <= 2) { if (RampPreviewClasses.IsValidIndex(CurrentBuildingMaterial)) { if (RampPreviewClasses[CurrentBuildingMaterial] != nullptr) { BuildingPreview = GetWorld()->SpawnActor<ABuildingActor>(RampPreviewClasses[CurrentBuildingMaterial], GridLocation, GridRotation); //set the new ramp preview } } } } if (State->BuildMode == FString("Floor")) { FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(100.0, 25.0, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 2.0); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } /*FString LogMsg = FString("Current building material ") + FString::FromInt(CurrentBuildingMaterial); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ if (CurrentBuildingMaterial >= 0 && CurrentBuildingMaterial <= 2) { if (FloorPreviewClasses.IsValidIndex(CurrentBuildingMaterial)) { if (FloorPreviewClasses[CurrentBuildingMaterial] != nullptr) { BuildingPreview = GetWorld()->SpawnActor<ABuildingActor>(FloorPreviewClasses[CurrentBuildingMaterial], GridLocation, GridRotation); //set the new floor preview } } } } } } } FRotator ControlRotation = GetControlRotation(); FRotator ActorRotation = GetActorRotation(); FRotator DeltaRotation = ControlRotation - ActorRotation; DeltaRotation.Normalize(); FRotator AimRotation = FRotator(AimPitch, AimYaw, 0); FRotator InterpolatedRotation = FMath::RInterpTo(AimRotation, DeltaRotation, DeltaTime, InterpSpeed); float NewPitch = FMath::ClampAngle(InterpolatedRotation.Pitch, -90, 90); float NewYaw = FMath::ClampAngle(InterpolatedRotation.Yaw, -90, 90); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(NewPitch).Append(FString::FromInt(NewYaw))); AimPitch = NewPitch; AimYaw = NewYaw; } } void AFortniteCloneCharacter::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (HasAuthority()) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("NetMode: ") + FString::FromInt(GetNetMode()) + FString(" Player overlapped with: ") + OtherActor->GetName()); if (OtherActor != nullptr && OtherActor != this) { if (CurrentWeapon != nullptr && OtherActor == (AActor*)CurrentWeapon) { // if the character is overlapping with its weapon, dont do anything about it return; } if (CurrentHealingItem != nullptr && OtherActor == (AActor*)CurrentHealingItem) { // if the character is overlapping with its healing item, dont do anything about it return; } if (OtherActor->IsA(AWeaponActor::StaticClass())) { AWeaponActor* WeaponActor = Cast<AWeaponActor>(OtherActor); if (WeaponActor->WeaponType == 0) { return; // do nothing if it's a pickaxe } if (WeaponActor->Holder != nullptr) { return; // do nothing if someone is holding the weapon } if (GetController()) { // pick up the item if the two conditions above are false AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->InBuildMode || State->JustShotRifle || State->JustShotShotgun || State->JustSwungPickaxe || State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun) { return; // can't pick up items while in build mode or if just shot rifle, shot shotgun, swung pickaxe, used healing item, or reloaded } // if the player already has a weapon of this type, do not equip it if (State->EquippedWeapons.Contains(WeaponActor->WeaponType)) { return; } // Destroy old weapon/healing item if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } // PICK UP WEAPON State->EquippedWeapons.Add(WeaponActor->WeaponType); State->EquippedWeaponsClips[WeaponActor->WeaponType] = WeaponActor->MagazineSize; // this has to be done before calling client method below //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("MagSize: ") + FString::FromInt(WeaponActor->MagazineSize)); ClientGetWeaponTransform(WeaponActor->WeaponType); WeaponActor->Destroy(); } } } else if (OtherActor->IsA(AHealingActor::StaticClass())) { //pick up the item AHealingActor* HealingActor = Cast<AHealingActor>(OtherActor); AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } if (State) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, OtherActor->GetName()); if (State->InBuildMode || State->JustShotRifle || State->JustShotShotgun || State->JustSwungPickaxe || State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun) { return; // can't pick up items while in build mode or if just shot rifle, shot shotgun, swung pickaxe, used healing item, or reloaded } //CurrentHealingItem = Cast<AHealingActor>(OtherActor); if (HealingActor->Holder != nullptr) { return; // do nothing if someone is holding the healing item } //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("didn't end early")); // Destroy old weapon if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } // pick up healing item State->HealingItemCounts[HealingActor->HealingType] += HealingActor->Count; ClientGetHealingItemTransform(HealingActor->HealingType); HealingActor->Destroy(); } } else if (OtherActor->IsA(AAmmunitionActor::StaticClass())) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); AAmmunitionActor* Ammo = Cast<AAmmunitionActor>(OtherActor); if (State) { // increment ammo count State->EquippedWeaponsAmmunition[Ammo->WeaponType] += Ammo->BulletCount; } Ammo->Destroy(); } } else if (OtherActor->IsA(AStormActor::StaticClass())) { /*FString LogMsg = FString("storm overlap begin ") + FString::FromInt(GetNetMode()); GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, LogMsg); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ InStorm = false; } //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, OtherActor->GetName()); } } } void AFortniteCloneCharacter::OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { if (HasAuthority()) { /*FString LogMsg = FString("storm overlap end ") + FString::FromInt(GetNetMode()); GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, LogMsg); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ if (OtherActor != nullptr) { if (OtherActor == this) { return; } if (OtherActor->IsA(AStormActor::StaticClass())) { InStorm = true; } } } } float AFortniteCloneCharacter::PlayAnimMontage(class UAnimMontage* AnimMontage, float InPlayRate, FName StartSectionName) { USkeletalMeshComponent* UseMesh = GetMesh(); if (AnimMontage && UseMesh && UseMesh->AnimScriptInstance) { return UseMesh->AnimScriptInstance->Montage_Play(AnimMontage, InPlayRate); } return 0.0f; } void AFortniteCloneCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AFortniteCloneCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AFortniteCloneCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AFortniteCloneCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AFortniteCloneCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AFortniteCloneCharacter::MoveForward(float Value) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("move forward ") + FString::FromInt(GetNetMode())); if ((Controller != nullptr) && (Value != 0.0f)) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(Controller->PlayerState); if (State) { if (State->JustUsedHealingItem) { return; } // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); if (AimedIn) { AddMovementInput(Direction, Value * 0.2); } else if (IsRunning) { AddMovementInput(Direction, Value * 0.9); } else if (IsWalking) { AddMovementInput(Direction, Value * 0.45); } } } /*UThirdPersonAnimInstance* Animation = Cast<UThirdPersonAnimInstance>(GetMesh()->GetAnimInstance()); if (Animation) { //set blend space variable Animation->WalkingY = Value * 90; Animation->RunningY = Value * 90; //Server_SetMovingVariables(); }*/ if (Value == 0) { ServerResetMovingForward(); } else if (Value > 0) { ServerSetMovingForwards(); } else { ServerSetMovingBackwards(); } } void AFortniteCloneCharacter::MoveRight(float Value) { if ((Controller != nullptr) && (Value != 0.0f)) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(Controller->PlayerState); if (State) { if (State->JustUsedHealingItem) { return; } } // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction if (AimedIn) { AddMovementInput(Direction, Value * 0.2); } else if (IsRunning) { AddMovementInput(Direction, Value * 0.9); } else if (IsWalking) { AddMovementInput(Direction, Value * 0.45); } } /*UThirdPersonAnimInstance* Animation = Cast<UThirdPersonAnimInstance>(GetMesh()->GetAnimInstance()); if (Animation) { //set blend space variable Animation->WalkingX = Value * 90; Animation->RunningX = Value * 90; //Server_SetMovingVariables(); }*/ if (Value == 0) { ServerResetMovingRight(); } else if (Value > 0) { ServerSetMovingRight(); } else { ServerSetMovingLeft(); } } void AFortniteCloneCharacter::Sprint(float Value) { APlayerController* LocalController = Cast<APlayerController>(GetController()); bool ADown = LocalController->IsInputKeyDown(EKeys::A); bool WDown = LocalController->IsInputKeyDown(EKeys::W); bool SDown = LocalController->IsInputKeyDown(EKeys::S); bool DDown = LocalController->IsInputKeyDown(EKeys::D); bool OnlyAOrDDown = !WDown && !SDown && (ADown || DDown); UThirdPersonAnimInstance* Animation = Cast<UThirdPersonAnimInstance>(GetMesh()->GetAnimInstance()); if (Animation) { if (Animation->AimedIn) { //ServerSetAimedInSpeed(); } else if (Value == 0) { //ServerSetWalkingSpeed(); ServerSetIsRunningFalse(); } else { // can only sprint if the w key is held down by itself or in combination with the a or d keys if (!(OnlyAOrDDown || SDown) && WDown) { //ServerSetRunningSpeed(); ServerSetIsRunningTrue(); } else { //ServerSetWalkingSpeed(); ServerSetIsRunningFalse(); } } } //Server_SetAnimationVariables(); } void AFortniteCloneCharacter::StartWalking() { ServerSetIsWalkingTrue(); } void AFortniteCloneCharacter::StopWalking() { //UThirdPersonAnimInstance* Animation = Cast<UThirdPersonAnimInstance>(GetMesh()->GetAnimInstance()); APlayerController* LocalController = Cast<APlayerController>(GetController()); bool ADown = LocalController->IsInputKeyDown(EKeys::A); bool WDown = LocalController->IsInputKeyDown(EKeys::W); bool SDown = LocalController->IsInputKeyDown(EKeys::S); bool DDown = LocalController->IsInputKeyDown(EKeys::D); bool NoWalkingKeysDown = !ADown && !WDown && !SDown && !DDown; if (NoWalkingKeysDown) { ServerSetIsWalkingFalse(); } //ServerSetAnimationVariables(); } TArray<float> AFortniteCloneCharacter::CalculateWalkingXY() { float X = 0; float Y = 0; APlayerController* LocalController = Cast<APlayerController>(GetController()); if (LocalController->IsInputKeyDown(EKeys::A)) { X -= 90; } if (LocalController->IsInputKeyDown(EKeys::D)) { X += 90; } if (LocalController->IsInputKeyDown(EKeys::W)) { Y += 90; } if (LocalController->IsInputKeyDown(EKeys::S)) { Y -= 90; } TArray<float> Coords; Coords.Add(X); Coords.Add(Y); return Coords; } void AFortniteCloneCharacter::PreviewWall() { ServerSetBuildModeWall(); } void AFortniteCloneCharacter::PreviewRamp() { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "c key pressed"); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "c key presse2d"); ServerSetBuildModeRamp(); } void AFortniteCloneCharacter::PreviewFloor() { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "f key pressed"); ServerSetBuildModeFloor(); } void AFortniteCloneCharacter::BuildStructure(float Value) { if (Value > 0) { // Build a structure on the client side first then run a server rpc that destroys that structure and respawns it if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { FVector DirectionVector = FVector(0, AimYaw, AimPitch); if (State->InBuildMode && State->BuildMode == FString("Wall") && State->MaterialCounts[CurrentBuildingMaterial] >= 10) { TArray<AActor*> OverlappingActors; FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(200.0, 50.0, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 2.0); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); /*FString LogMsg = FString("GridLocation X ") + FString::SanitizeFloat(GridLocation.X) + FString(" ProjectedLocation X") + FString::SanitizeFloat(ProjectedLocation.X); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ // to make the structures connect with each other, have to add an offset when in a different rotation if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } ABuildingActor* Wall = GetWorld()->SpawnActor<ABuildingActor>(WallClasses[CurrentBuildingMaterial], GridLocation, GridRotation); Wall->GetOverlappingActors(OverlappingActors); for (int i = 0; i < OverlappingActors.Num(); i++) { if (OverlappingActors[i] != nullptr) { if (OverlappingActors[i]->IsA(AFortniteCloneCharacter::StaticClass())) { //don't allow a player to build a structure that overlaps with another player Wall->Destroy(); return; } else if (OverlappingActors[i]->IsA(ABuildingActor::StaticClass())) { ABuildingActor* Structure = Cast<ABuildingActor>(OverlappingActors[i]); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Overlapped with another building?") + Structure->StructureType); if (Structure && !Structure->IsPreview && Structure->StructureType.Equals(Wall->StructureType) && FMath::Abs(FVector::Distance(Structure->GetTransform().GetLocation(), Wall->GetTransform().GetLocation())) < 1.f) { //don't allow a player to build a structure in the exact same spot that another structure of its same kind was already built //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Overlapped with another building?") + FString::SanitizeFloat(FMath::Abs(FVector::Distance(Structure->GetTransform().GetLocation(), Wall->GetTransform().GetLocation())))); Wall->Destroy(); return; } } } } Wall->Id = CurrentStructureId; CurrentStructureId += 1; ClientSpawnedStructures.Add(Wall); State->MaterialCounts[CurrentBuildingMaterial] -= 10; ServerBuildStructure(WallClasses[CurrentBuildingMaterial], GridLocation, GridRotation, Wall->Id); ServerSetMaterialCount(State->MaterialCounts[CurrentBuildingMaterial], CurrentBuildingMaterial); } else if (State->InBuildMode && State->BuildMode == FString("Ramp") && State->MaterialCounts[CurrentBuildingMaterial] >= 10) { TArray<AActor*> OverlappingActors; //original 400, 200, 2 FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(50.0, 6.25, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 1.5); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } ABuildingActor* Ramp = GetWorld()->SpawnActor<ABuildingActor>(RampClasses[CurrentBuildingMaterial], GridLocation, GridRotation); Ramp->GetOverlappingActors(OverlappingActors); for (int i = 0; i < OverlappingActors.Num(); i++) { if (OverlappingActors[i] != nullptr) { if (OverlappingActors[i]->IsA(AFortniteCloneCharacter::StaticClass())) { //don't allow a player to build a structure that overlaps with another player Ramp->Destroy(); return; } else if (OverlappingActors[i]->IsA(ABuildingActor::StaticClass())) { ABuildingActor* Structure = Cast<ABuildingActor>(OverlappingActors[i]); if (Structure && !Structure->IsPreview && Structure->StructureType.Equals(Ramp->StructureType) && FMath::Abs(FVector::Distance(Structure->GetTransform().GetLocation(), Ramp->GetTransform().GetLocation())) < 1.f) { //don't allow a player to build a structure in the exact same spot that another structure of its same kind was already built Ramp->Destroy(); return; } } } } Ramp->Id = CurrentStructureId; CurrentStructureId += 1; ClientSpawnedStructures.Add(Ramp); State->MaterialCounts[CurrentBuildingMaterial] -= 10; ServerBuildStructure(RampClasses[CurrentBuildingMaterial], GridLocation, GridRotation, Ramp->Id); ServerSetMaterialCount(State->MaterialCounts[CurrentBuildingMaterial], CurrentBuildingMaterial); } else if (State->InBuildMode && State->BuildMode == FString("Floor") && State->MaterialCounts[CurrentBuildingMaterial] >= 10) { TArray<AActor*> OverlappingActors; FVector ProjectedLocation = GetActorLocation() + (GetActorForwardVector() * FVector(100.0, 25.0, 1.0)) + (FVector(0, 0, DirectionVector.Z) * 2.0); // projected location before setting to grid using actor forward and direction (aim offset) vectors float GridLocationX = FMath::RoundHalfFromZero(ProjectedLocation.X / 480.00002) * 480; float GridLocationY = FMath::RoundHalfFromZero(ProjectedLocation.Y / 480.00002) * 480; float GridLocationZ = FMath::RoundHalfFromZero(ProjectedLocation.Z / 480.00002) * 480; FVector GridLocation = FVector(GridLocationX, GridLocationY, GridLocationZ); FRotator ProjectedRotation = GetActorRotation().Add(0, 90, 0); // projected rotation before setting to grid using the actor's rotation float GridRotationYaw = FMath::RoundHalfFromZero(ProjectedRotation.Yaw / 90.0) * 90; FRotator GridRotation = FRotator(0, GridRotationYaw, 0); if (FMath::Abs(GridRotationYaw) == 0) { GridLocation.Y -= 240.00001; if (ProjectedLocation.X < GridLocation.X) { GridLocation.X -= 240.00001; } else { GridLocation.X += 240.00001; } } if (FMath::Abs(GridRotationYaw) == 180) { GridLocation.Y += 240.00001; if (ProjectedLocation.X > GridLocation.X) { GridLocation.X += 240.00001; } else { GridLocation.X -= 240.00001; } } ABuildingActor* Floor = GetWorld()->SpawnActor<ABuildingActor>(FloorClasses[CurrentBuildingMaterial], GridLocation, GridRotation); Floor->GetOverlappingActors(OverlappingActors); for (int i = 0; i < OverlappingActors.Num(); i++) { if (OverlappingActors[i] != nullptr) { if (OverlappingActors[i]->IsA(AFortniteCloneCharacter::StaticClass())) { //don't allow a player to build a structure that overlaps with another player Floor->Destroy(); return; } else if (OverlappingActors[i]->IsA(ABuildingActor::StaticClass())) { ABuildingActor* Structure = Cast<ABuildingActor>(OverlappingActors[i]); if (Structure && !Structure->IsPreview && Structure->StructureType.Equals(Floor->StructureType) && FMath::Abs(FVector::Distance(Structure->GetTransform().GetLocation(), Floor->GetTransform().GetLocation())) < 1.f) { //don't allow a player to build a structure in the exact same spot that another structure of its same kind was already built //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("Overlapped with another building?") + FString::SanitizeFloat(FMath::Abs(FVector::Distance(Structure->GetTransform().GetLocation(), Floor->GetTransform().GetLocation())))); Floor->Destroy(); return; } } } } Floor->Id = CurrentStructureId; CurrentStructureId += 1; ClientSpawnedStructures.Add(Floor); State->MaterialCounts[CurrentBuildingMaterial] -= 10; ServerBuildStructure(FloorClasses[CurrentBuildingMaterial], GridLocation, GridRotation, Floor->Id); ServerSetMaterialCount(State->MaterialCounts[CurrentBuildingMaterial], CurrentBuildingMaterial); } } } } } void AFortniteCloneCharacter::SwitchBuildingMaterial() { ServerChangeBuildingMaterial(); } void AFortniteCloneCharacter::ShootGun() { ServerFireWeapon(); } void AFortniteCloneCharacter::UseHealingItem() { ServerUseHealingItem(CurrentHealingItemType); } void AFortniteCloneCharacter::Reload() { ServerReloadWeapons(); } void AFortniteCloneCharacter::AimGunIn() { ServerAimDownSights(); } void AFortniteCloneCharacter::AimGunOut() { ServerAimHipFire(); } void AFortniteCloneCharacter::PickaxeTimeOut() { ServerPickaxeTimeOut(); } void AFortniteCloneCharacter::RifleTimeOut() { ServerRifleTimeOut(); } void AFortniteCloneCharacter::ShotgunTimeOut() { ServerShotgunTimeOut(); } void AFortniteCloneCharacter::RifleReloadTimeOut() { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); State->JustReloadedRifle= false; } void AFortniteCloneCharacter::ShotgunReloadTimeOut() { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); State->JustReloadedShotgun = false; } void AFortniteCloneCharacter::HoldPickaxe() { ServerSwitchToPickaxe(); } void AFortniteCloneCharacter::HoldAssaultRifle() { ServerSwitchToRifle(); } void AFortniteCloneCharacter::HoldShotgun() { ServerSwitchToShotgun(); } void AFortniteCloneCharacter::HoldBandage() { ServerSwitchToHealingItem(0); } void AFortniteCloneCharacter::HoldPotion() { ServerSwitchToHealingItem(1); } float AFortniteCloneCharacter::GetHealth() { return Health; } float AFortniteCloneCharacter::GetShield() { return Shield; } int AFortniteCloneCharacter::GetWoodMaterialCount() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->MaterialCounts[0]; } else { return 0; } } else { return 0; } } int AFortniteCloneCharacter::GetStoneMaterialCount() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->MaterialCounts[1]; } else { return 0; } } else { return 0; } } int AFortniteCloneCharacter::GetSteelMaterialCount() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->MaterialCounts[2]; } else { return 0; } } else { return 0; } } int AFortniteCloneCharacter::GetAssaultRifleAmmoCount() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->EquippedWeaponsAmmunition[1] + State->EquippedWeaponsClips[1]; } else { return 0; } } else { return 0; } } int AFortniteCloneCharacter::GetShotgunAmmoCount() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->EquippedWeaponsAmmunition[2] + State->EquippedWeaponsClips[2]; } else { return 0; } } else { return 0; } } int AFortniteCloneCharacter::GetHealingItemCount(int HealingItemType) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { return State->HealingItemCounts[HealingItemType]; } else { return 0; } } else { return 0; } } void AFortniteCloneCharacter::OpenSettingsMenu() { if (GetController()) { APlayerController* PlayerController = Cast<APlayerController>(GetController()); if (PlayerController->GetHUD()) { AFortniteCloneHUD* FortniteCloneHUD = Cast<AFortniteCloneHUD>(PlayerController->GetHUD()); FortniteCloneHUD->DrawSettingsMenu(); } } } void AFortniteCloneCharacter::ServerSetIsWalkingTrue_Implementation() { IsWalking = true; } bool AFortniteCloneCharacter::ServerSetIsWalkingTrue_Validate() { return true; } void AFortniteCloneCharacter::ServerSetIsWalkingFalse_Implementation() { IsWalking = false; } bool AFortniteCloneCharacter::ServerSetIsWalkingFalse_Validate() { return true; } void AFortniteCloneCharacter::ServerSetIsRunningTrue_Implementation() { IsRunning = true; } bool AFortniteCloneCharacter::ServerSetIsRunningTrue_Validate() { return true; } void AFortniteCloneCharacter::ServerSetIsRunningFalse_Implementation() { IsRunning = false; } bool AFortniteCloneCharacter::ServerSetIsRunningFalse_Validate() { return true; } void AFortniteCloneCharacter::ServerSetWalkingSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 450.0; ClientSetWalkingSpeed(); } bool AFortniteCloneCharacter::ServerSetWalkingSpeed_Validate() { return true; } void AFortniteCloneCharacter::ClientSetWalkingSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 450.0; } void AFortniteCloneCharacter::ServerSetRunningSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 900.0; ClientSetRunningSpeed(); } bool AFortniteCloneCharacter::ServerSetRunningSpeed_Validate() { return true; } void AFortniteCloneCharacter::ClientSetRunningSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 900.0; } void AFortniteCloneCharacter::ServerSetAimedInSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 200.0; ClientSetAimedInSpeed(); } bool AFortniteCloneCharacter::ServerSetAimedInSpeed_Validate() { return true; } void AFortniteCloneCharacter::ClientSetAimedInSpeed_Implementation() { GetCharacterMovement()->MaxWalkSpeed = 200.0; } void AFortniteCloneCharacter::ServerSetMovingForwards_Implementation() { WalkingY = 90; RunningY = 90; } bool AFortniteCloneCharacter::ServerSetMovingForwards_Validate() { return true; } void AFortniteCloneCharacter::ServerSetMovingBackwards_Implementation() { WalkingY = -90; RunningY = -90; } bool AFortniteCloneCharacter::ServerSetMovingBackwards_Validate() { return true; } void AFortniteCloneCharacter::ServerSetMovingLeft_Implementation() { WalkingX = -90; RunningX = -90; } bool AFortniteCloneCharacter::ServerSetMovingLeft_Validate() { return true; } void AFortniteCloneCharacter::ServerSetMovingRight_Implementation() { WalkingX = 90; RunningX = 90; } bool AFortniteCloneCharacter::ServerSetMovingRight_Validate() { return true; } void AFortniteCloneCharacter::ServerResetMovingForward_Implementation() { WalkingY = 0; RunningY = 0; } bool AFortniteCloneCharacter::ServerResetMovingForward_Validate() { return true; } void AFortniteCloneCharacter::ServerResetMovingRight_Implementation() { WalkingX = 0; RunningX = 0; } bool AFortniteCloneCharacter::ServerResetMovingRight_Validate() { return true; } void AFortniteCloneCharacter::ServerSetMaterialCount_Implementation(int Count, int MaterialType) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->MaterialCounts[MaterialType] = Count; } } } bool AFortniteCloneCharacter::ServerSetMaterialCount_Validate(int Count, int MaterialType) { return true; } void AFortniteCloneCharacter::ServerBuildStructure_Implementation(TSubclassOf<ABuildingActor> StructureClass, FVector SpawnLocation, FRotator SpawnRotation, int StructureId) { if (StructureClass != nullptr) { GetWorld()->SpawnActor<ABuildingActor>(StructureClass, SpawnLocation, SpawnRotation); ClientDestroyStructure(StructureId); } } bool AFortniteCloneCharacter::ServerBuildStructure_Validate(TSubclassOf<ABuildingActor> StructureClass, FVector SpawnLocation, FRotator SpawnRotation, int StructureId) { return true; } void AFortniteCloneCharacter::ServerSetBuildModeWall_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun) { return; //currently healing or reloading } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (State->BuildMode == FString("Wall")) { // getting out of build mode State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } // equip weapon being held before if (CurrentWeaponType > -1 && CurrentWeaponType < 3) { ClientGetWeaponTransform(CurrentWeaponType); } else if (CurrentHealingItemType > -1 && CurrentHealingItemType < 2) { //equip healing item since current weapon was null ClientGetHealingItemTransform(CurrentHealingItemType); } } else if (State->InBuildMode) { // switching to a different build mode State->BuildMode = FString("Wall"); } else { // getting into build mode State->InBuildMode = true; State->BuildMode = FString("Wall"); State->HoldingWeapon = false; State->HoldingHealingItem = false; State->AimedIn = false; //animinstance properties HoldingWeapon = false; AimedIn = false; HoldingWeaponType = 0; // unequip weapon/healing item if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } } } } } bool AFortniteCloneCharacter::ServerSetBuildModeWall_Validate() { return true; } void AFortniteCloneCharacter::ServerSetBuildModeRamp_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun) { return; //currently healing or reloading } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (State->BuildMode == FString("Ramp")) { // getting out of build mode State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } // equip weapon being held before if (CurrentWeaponType > -1 && CurrentWeaponType < 3) { ClientGetWeaponTransform(CurrentWeaponType); } else if(CurrentHealingItemType > -1 && CurrentHealingItemType < 2){ //equip healing item since current weapon was null ClientGetHealingItemTransform(CurrentHealingItemType); } } else if (State->InBuildMode) { // switching to a different build mode State->BuildMode = FString("Ramp"); } else { // getting into build mode State->InBuildMode = true; State->BuildMode = FString("Ramp"); State->HoldingWeapon = false; State->HoldingHealingItem = false; State->AimedIn = false; //animinstance properties HoldingWeapon = false; AimedIn = false; HoldingWeaponType = 0; // unequip weapon/healing item if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } } } } } bool AFortniteCloneCharacter::ServerSetBuildModeRamp_Validate() { return true; } void AFortniteCloneCharacter::ServerSetBuildModeFloor_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun || State->JustSwungPickaxe) { return; //currently healing or reloading or swinging pickaxe } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (State->BuildMode == FString("Floor")) { // getting out of build mode State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } // equip weapon being held before if (CurrentWeaponType > -1 && CurrentWeaponType < 3) { ClientGetWeaponTransform(CurrentWeaponType); } else if (CurrentHealingItemType > -1 && CurrentHealingItemType < 2) { //equip healing item since current weapon was null ClientGetHealingItemTransform(CurrentHealingItemType); } } else if (State->InBuildMode) { // switching to a different build mode State->BuildMode = FString("Floor"); } else { // getting into build mode State->InBuildMode = true; State->BuildMode = FString("Floor"); State->HoldingWeapon = false; State->HoldingHealingItem = false; State->AimedIn = false; //animinstance properties HoldingWeapon = false; AimedIn = false; HoldingWeaponType = 0; // unequip weapon/healing item if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } } } } } bool AFortniteCloneCharacter::ServerSetBuildModeFloor_Validate() { return true; } void AFortniteCloneCharacter::ServerFireWeapon_Implementation() { if (CurrentWeapon != nullptr) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(GetNetMode()) + FString(" Current weapon ") + FString::FromInt(State->CurrentWeapon)); if (State->HoldingWeapon) { if (State->CurrentWeapon > 0 && State->CurrentWeapon < 3 && CurrentWeapon->CurrentBulletCount <= 0) { // no bullets in magazine, need to reload ServerReloadWeapons(); return; } if (State->JustReloadedRifle || State->JustReloadedShotgun) { return; //currently reloading } if (State->AimedIn) { if (State->CurrentWeapon == 1) { if (State->JustShotRifle) { return; } NetMulticastPlayShootRifleIronsightsAnimation(); CurrentWeapon->CurrentBulletCount--; State->EquippedWeaponsClips[CurrentWeaponType]--; State->JustShotRifle = true; FTimerHandle RifleTimerHandle; GetWorldTimerManager().SetTimer(RifleTimerHandle, this, &AFortniteCloneCharacter::ServerRifleTimeOut, 0.233f, false); } else if (State->CurrentWeapon == 2) { if (State->JustShotShotgun) { return; } NetMulticastPlayShootShotgunIronsightsAnimation(); CurrentWeapon->CurrentBulletCount--; State->EquippedWeaponsClips[CurrentWeaponType]--; State->JustShotShotgun = true; FTimerHandle ShotgunTimerHandle; GetWorldTimerManager().SetTimer(ShotgunTimerHandle, this, &AFortniteCloneCharacter::ServerShotgunTimeOut, 1.3f, false); } } else { if (State->CurrentWeapon == 0) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "pickaxe swung"); if (State->JustSwungPickaxe) { return; } NetMulticastPlayPickaxeSwingAnimation(); State->JustSwungPickaxe = true; FTimerHandle PickaxeTimerHandle; GetWorldTimerManager().SetTimer(PickaxeTimerHandle, this, &AFortniteCloneCharacter::ServerPickaxeTimeOut, 0.403f, false); } if (State->CurrentWeapon == 1) { if (State->JustShotRifle) { return; } NetMulticastPlayShootRifleAnimation(); CurrentWeapon->CurrentBulletCount--; State->EquippedWeaponsClips[CurrentWeaponType]--; State->JustShotRifle = true; FTimerHandle RifleTimerHandle; GetWorldTimerManager().SetTimer(RifleTimerHandle, this, &AFortniteCloneCharacter::ServerRifleTimeOut, 0.233f, false); } else if (State->CurrentWeapon == 2) { if (State->JustShotShotgun) { return; } NetMulticastPlayShootShotgunAnimation(); CurrentWeapon->CurrentBulletCount--; State->EquippedWeaponsClips[CurrentWeaponType]--; State->JustShotShotgun = true; FTimerHandle ShotgunTimerHandle; GetWorldTimerManager().SetTimer(ShotgunTimerHandle, this, &AFortniteCloneCharacter::ServerShotgunTimeOut, 1.3f, false); } } ClientGetBulletTransform(); } } } } } bool AFortniteCloneCharacter::ServerFireWeapon_Validate() { return true; } void AFortniteCloneCharacter::ServerUseHealingItem_Implementation(int HealingItemType) { if (HealingItemType == 0) { if (Health >= 100) { return; // player has full health } } else if (HealingItemType == 1) { if (Shield >= 100) { return; // player has full shield } } else { return; } if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State && State->HoldingHealingItem) { if (State->HealingItemCounts[HealingItemType] < 1) { return; // player has no healing items to use } if (State->JustUsedHealingItem) { return; } NetMulticastPlayUseHealingItemAnimation(); State->JustUsedHealingItem = true; State->HealingItemCounts[HealingItemType]--; FTimerHandle HealingItemTimerHandle; FTimerDelegate HealingItemTimerDelegate; HealingItemTimerDelegate.BindUFunction(this, FName("ServerHealingItemTimeOut"), HealingItemType); GetWorldTimerManager().SetTimer(HealingItemTimerHandle, HealingItemTimerDelegate, 3.321f, false); } } } bool AFortniteCloneCharacter::ServerUseHealingItem_Validate(int HealingItemType) { return true; } void AFortniteCloneCharacter::ServerReloadWeapons_Implementation() { // todo add current weapon null check if (CurrentWeapon != nullptr) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->CurrentWeapon > 2 || State->CurrentWeapon < 1) { return; // can only reload if holding a assault rifle or shotgun } if (State->JustShotRifle || State->JustShotShotgun || State->JustReloadedRifle || State->JustReloadedShotgun) { return; // currently reloading or just shot } if (State->AimedIn) { if (State->CurrentWeapon == 1) { if (State->JustShotRifle) { return; } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] <= 0) { return; // no ammo left } int BulletsNeeded = CurrentWeapon->MagazineSize - CurrentWeapon->CurrentBulletCount; if (BulletsNeeded == 0) { return; // magazine is full } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] < BulletsNeeded) { BulletsNeeded = State->EquippedWeaponsAmmunition[State->CurrentWeapon]; State->EquippedWeaponsAmmunition[State->CurrentWeapon] = 0; } else { State->EquippedWeaponsAmmunition[State->CurrentWeapon] -= BulletsNeeded; } NetMulticastPlayReloadRifleIronsightsAnimation(); CurrentWeapon->CurrentBulletCount += BulletsNeeded; State->EquippedWeaponsClips[State->CurrentWeapon] += BulletsNeeded; State->JustReloadedRifle = true; FTimerHandle RifleTimerHandle; GetWorldTimerManager().SetTimer(RifleTimerHandle, this, &AFortniteCloneCharacter::ServerRifleReloadTimeOut, 2.167f, false); } else if (State->CurrentWeapon == 2) { if (State->JustShotShotgun) { return; } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] <= 0) { return; // no ammo left } int BulletsNeeded = CurrentWeapon->MagazineSize - CurrentWeapon->CurrentBulletCount; if (BulletsNeeded == 0) { return; // magazine is full } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] < BulletsNeeded) { BulletsNeeded = State->EquippedWeaponsAmmunition[State->CurrentWeapon]; State->EquippedWeaponsAmmunition[State->CurrentWeapon] = 0; } else { State->EquippedWeaponsAmmunition[State->CurrentWeapon] -= BulletsNeeded; } NetMulticastPlayReloadShotgunIronsightsAnimation(); CurrentWeapon->CurrentBulletCount += BulletsNeeded; State->EquippedWeaponsClips[State->CurrentWeapon] += BulletsNeeded; State->JustReloadedShotgun = true; FTimerHandle ShotgunTimerHandle; GetWorldTimerManager().SetTimer(ShotgunTimerHandle, this, &AFortniteCloneCharacter::ServerShotgunReloadTimeOut, 4.3f, false); } } else { if (State->CurrentWeapon == 1) { if (State->JustShotRifle) { return; } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] <= 0) { return; // no ammo left } int BulletsNeeded = CurrentWeapon->MagazineSize - CurrentWeapon->CurrentBulletCount; if (BulletsNeeded == 0) { return; // magazine is full } //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(State->EquippedWeaponsAmmunition[State->CurrentWeapon])); if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] < BulletsNeeded) { BulletsNeeded = State->EquippedWeaponsAmmunition[State->CurrentWeapon]; State->EquippedWeaponsAmmunition[State->CurrentWeapon] = 0; } else { State->EquippedWeaponsAmmunition[State->CurrentWeapon] -= BulletsNeeded; } NetMulticastPlayReloadRifleAnimation(); CurrentWeapon->CurrentBulletCount += BulletsNeeded; State->EquippedWeaponsClips[State->CurrentWeapon] += BulletsNeeded; //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(CurrentWeapon->CurrentBulletCount)); State->JustReloadedRifle = true; FTimerHandle RifleTimerHandle; GetWorldTimerManager().SetTimer(RifleTimerHandle, this, &AFortniteCloneCharacter::ServerRifleReloadTimeOut, 2.167f, false); } else if (State->CurrentWeapon == 2) { if (State->JustShotShotgun) { return; } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] <= 0) { return; // no ammo left } int BulletsNeeded = CurrentWeapon->MagazineSize - CurrentWeapon->CurrentBulletCount; if (BulletsNeeded == 0) { return; // magazine is full } if (State->EquippedWeaponsAmmunition[State->CurrentWeapon] < BulletsNeeded) { BulletsNeeded = State->EquippedWeaponsAmmunition[State->CurrentWeapon]; State->EquippedWeaponsAmmunition[State->CurrentWeapon] = 0; } else { State->EquippedWeaponsAmmunition[State->CurrentWeapon] -= BulletsNeeded; } NetMulticastPlayReloadShotgunAnimation(); CurrentWeapon->CurrentBulletCount += BulletsNeeded; State->EquippedWeaponsClips[State->CurrentWeapon] += BulletsNeeded; State->JustReloadedShotgun = true; FTimerHandle ShotgunTimerHandle; GetWorldTimerManager().SetTimer(ShotgunTimerHandle, this, &AFortniteCloneCharacter::ServerShotgunReloadTimeOut, 4.3f, false); } } } } } } bool AFortniteCloneCharacter::ServerReloadWeapons_Validate() { return true; } void AFortniteCloneCharacter::ServerSwitchToPickaxe_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->CurrentWeapon == 0 && !State->InBuildMode) { return; // currently holding a pickaxe while not in build mode } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun || State->JustShotRifle || State->JustShotShotgun) { return; // currently healing or currently reloading or just shot a weapon } else { if (State->InBuildMode) { State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } } if (CurrentWeapon) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } ClientGetWeaponTransform(0); } } } } bool AFortniteCloneCharacter::ServerSwitchToPickaxe_Validate() { return true; } void AFortniteCloneCharacter::ServerSwitchToRifle_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->CurrentWeapon == 1 && !State->InBuildMode) { return; // currently holding a assault rifle while not in build mode } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (!State->EquippedWeapons.Contains(1) || State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun || State->JustSwungPickaxe || State->JustShotShotgun) { return; // already holding the assault rifle or doesn't have one or is currently healing or currently reloading or swinging pickaxe or shooting shotgun } else { if (State->InBuildMode) { State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } } if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } ClientGetWeaponTransform(1); } } } } bool AFortniteCloneCharacter::ServerSwitchToRifle_Validate() { return true; } void AFortniteCloneCharacter::ServerSwitchToShotgun_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->CurrentWeapon == 2 && !State->InBuildMode) { return; // currently holding a shotgun while not in build mode } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (!State->EquippedWeapons.Contains(2) || State->JustUsedHealingItem || State->JustReloadedRifle || State->JustReloadedShotgun || State->JustSwungPickaxe || State->JustShotRifle) { return; // already holding the pickaxe or doesn't have one or is currently healing or currently reloading or swinging pickaxe or just shot rifle } else { if (State->InBuildMode) { State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } } if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } ClientGetWeaponTransform(2); } } } } bool AFortniteCloneCharacter::ServerSwitchToShotgun_Validate() { return true; } void AFortniteCloneCharacter::ServerSwitchToHealingItem_Implementation(int HealingItemType) { /*FString LogMsg = FString("server switch to healing item Current healing item type ") + FString::FromInt(HealingItemType); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { if (State->JustReloadedRifle || State->JustReloadedShotgun || State->JustSwungPickaxe || State->JustShotRifle || State->JustShotShotgun) { return; //currently reloading weapons or swinging pickaxe } if (State->HoldingWeapon && State->AimedIn) { return; // currently aimed down sight } if (State->CurrentHealingItem == HealingItemType && !State->InBuildMode) { return; // already holding healing items while not in build mode } else { if (State->InBuildMode) { State->InBuildMode = false; State->BuildMode = FString("None"); if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } } //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::FromInt(CurrentWeaponType)); if (CurrentWeapon && CurrentWeaponType > 0 && CurrentWeaponType < 3) { State->EquippedWeaponsClips[CurrentWeaponType] = CurrentWeapon->CurrentBulletCount; } if (CurrentWeapon) { CurrentWeapon->Destroy(); CurrentWeapon = nullptr; } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); CurrentHealingItem = nullptr; } ClientGetHealingItemTransform(HealingItemType); } } } } bool AFortniteCloneCharacter::ServerSwitchToHealingItem_Validate(int HealingItemType) { return true; } void AFortniteCloneCharacter::ServerChangeBuildingMaterial_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State && State->InBuildMode) { if (CurrentBuildingMaterial == 2) { CurrentBuildingMaterial = 0; } else { CurrentBuildingMaterial++; } } } } bool AFortniteCloneCharacter::ServerChangeBuildingMaterial_Validate() { return true; } void AFortniteCloneCharacter::ServerAimDownSights_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State && State->HoldingWeapon && State->CurrentWeapon != 0) { AimedIn = true; HoldingWeaponType = 2; ClientCameraAimIn(); //ServerSetAimedInSpeed(); State->AimedIn = true; } } } bool AFortniteCloneCharacter::ServerAimDownSights_Validate() { return true; } void AFortniteCloneCharacter::ServerAimHipFire_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State && State->HoldingWeapon && State->CurrentWeapon != 0) { AimedIn = false; HoldingWeaponType = 1; ClientCameraAimOut(); //ServerSetWalkingSpeed(); State->AimedIn = false; } } } bool AFortniteCloneCharacter::ServerAimHipFire_Validate() { return true; } void AFortniteCloneCharacter::ServerPickaxeTimeOut_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustSwungPickaxe = false; } } } bool AFortniteCloneCharacter::ServerPickaxeTimeOut_Validate() { return true; } void AFortniteCloneCharacter::ServerRifleTimeOut_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustShotRifle = false; } } } bool AFortniteCloneCharacter::ServerRifleTimeOut_Validate() { return true; } void AFortniteCloneCharacter::ServerShotgunTimeOut_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustShotShotgun = false; } } } bool AFortniteCloneCharacter::ServerShotgunTimeOut_Validate() { return true; } void AFortniteCloneCharacter::ServerHealingItemTimeOut_Implementation(int HealingItemType) { if (HealingItemType == 0) { if (Health < 100) { if (Health + 15 > 100) { Health = 100; } else { Health += 15; } } } else if (HealingItemType == 1) { if (Shield < 100) { if (Shield + 20 > 100) { Shield = 100; } else { Shield += 20; } } } if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustUsedHealingItem = false; } } } bool AFortniteCloneCharacter::ServerHealingItemTimeOut_Validate(int HealingItemType) { return true; } void AFortniteCloneCharacter::ServerApplyStormDamage_Implementation() { if (CurrentStorm != nullptr && InStorm) { //get storm actor and get its damage component and apply the damage to the player's health Health -= CurrentStorm->Damage; if (Health <= 0) { if (BuildingPreview != nullptr) { BuildingPreview->Destroy(); BuildingPreview = nullptr; } if (CurrentWeapon) { CurrentWeapon->Destroy(); } if (CurrentHealingItem) { CurrentHealingItem->Destroy(); } if (GetController()) { AFortniteClonePlayerController* FortniteClonePlayerController = Cast<AFortniteClonePlayerController>(GetController()); if (FortniteClonePlayerController) { FortniteClonePlayerController->ServerSwitchToSpectatorMode(); } } Destroy(); } } } bool AFortniteCloneCharacter::ServerApplyStormDamage_Validate() { return true; } void AFortniteCloneCharacter::ServerRifleReloadTimeOut_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustReloadedRifle = false; } } } bool AFortniteCloneCharacter::ServerRifleReloadTimeOut_Validate() { return true; } void AFortniteCloneCharacter::ServerShotgunReloadTimeOut_Implementation() { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { State->JustReloadedShotgun = false; } } } bool AFortniteCloneCharacter::ServerShotgunReloadTimeOut_Validate() { return true; } void AFortniteCloneCharacter::ServerSpawnProjectile_Implementation(FTransform SpawnTransform) { // to do add current weapon null check if (CurrentWeapon != nullptr) { auto Bullet = Cast<AProjectileActor>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, CurrentWeapon->BulletClass, SpawnTransform, ESpawnActorCollisionHandlingMethod::AlwaysSpawn)); if (Bullet != nullptr) { //spawnactor has no way of passing parameters so need to use begindeferredactorspawn and finishspawningactor Bullet->Weapon = CurrentWeapon; Bullet->WeaponHolder = this; Bullet->SetOwner(this); UGameplayStatics::FinishSpawningActor(Bullet, SpawnTransform); } } } bool AFortniteCloneCharacter::ServerSpawnProjectile_Validate(FTransform SpawnTransform) { return true; } void AFortniteCloneCharacter::ServerSpawnAndAttachWeapon_Implementation(int WeaponType, FTransform SpawnTransform) { if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { CurrentWeaponType = WeaponType; CurrentHealingItemType = -1; FName WeaponSocketName = TEXT("hand_right_socket_pickaxe"); if (CurrentWeaponType == 1) { WeaponSocketName = TEXT("hand_right_socket_rifle"); } else if (CurrentWeaponType == 2) { WeaponSocketName = TEXT("hand_right_socket_shotgun"); } FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget, EAttachmentRule::KeepRelative, EAttachmentRule::KeepWorld, true); CurrentWeapon = Cast<AWeaponActor>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, WeaponClasses[WeaponType], SpawnTransform)); if (CurrentWeapon != nullptr) { CurrentWeapon->CurrentBulletCount = State->EquippedWeaponsClips[CurrentWeaponType]; //spawnactor has no way of passing parameters so need to use begindeferredactorspawn and finishspawningactor CurrentWeapon->Holder = this; UGameplayStatics::FinishSpawningActor(CurrentWeapon, SpawnTransform); UStaticMeshComponent* WeaponStaticMeshComponent = Cast<UStaticMeshComponent>(CurrentWeapon->GetComponentByClass(UStaticMeshComponent::StaticClass())); WeaponStaticMeshComponent->AttachToComponent(this->GetMesh(), AttachmentRules, WeaponSocketName); //animinstance properties HoldingWeapon = true; AimedIn = false; HoldingWeaponType = 1; State->HoldingWeapon = true; State->HoldingHealingItem = false; State->CurrentWeapon = WeaponType; State->CurrentHealingItem = -1; } } } } bool AFortniteCloneCharacter::ServerSpawnAndAttachWeapon_Validate(int WeaponType, FTransform SpawnTransform) { return true; } void AFortniteCloneCharacter::ServerSpawnAndAttachHealingItem_Implementation(int HealingItemType, FTransform SpawnTransform) { /*FString LogMsg = FString("server spawn and attach Current healing item type ") + FString::FromInt(HealingItemType); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ if (GetController()) { AFortniteClonePlayerState* State = Cast<AFortniteClonePlayerState>(GetController()->PlayerState); if (State) { CurrentWeaponType = -1; CurrentHealingItemType = HealingItemType; FName HealingItemSocketName = TEXT("hand_left_socket_bandage"); FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget, EAttachmentRule::KeepRelative, EAttachmentRule::SnapToTarget, true); if (CurrentHealingItemType == 1) { HealingItemSocketName = TEXT("hand_left_socket_potion"); AttachmentRules = FAttachmentTransformRules(EAttachmentRule::SnapToTarget, EAttachmentRule::KeepRelative, EAttachmentRule::KeepWorld, true); } auto HealingItem = Cast<AHealingActor>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, HealingItemClasses[CurrentHealingItemType], SpawnTransform)); if (HealingItem != nullptr) { CurrentHealingItem = HealingItem; //spawnactor has no way of passing parameters so need to use begindeferredactorspawn and finishspawningactor CurrentHealingItem->Holder = this; UGameplayStatics::FinishSpawningActor(CurrentHealingItem, SpawnTransform); FVector OldScale = CurrentHealingItem->GetActorScale3D(); CurrentHealingItem->SetActorScale3D(FVector(OldScale.X * 0.5, OldScale.Y * 0.5, OldScale.Z * 0.5)); // make the potion specifically smaller to fit hand UStaticMeshComponent* HealingItemStaticMeshComponent = Cast<UStaticMeshComponent>(CurrentHealingItem->GetComponentByClass(UStaticMeshComponent::StaticClass())); HealingItemStaticMeshComponent->AttachToComponent(this->GetMesh(), AttachmentRules, HealingItemSocketName); //animinstance properties HoldingWeapon = false; AimedIn = false; HoldingWeaponType = 0; State->HoldingWeapon = false; State->HoldingHealingItem = true; State->CurrentWeapon = -1; State->CurrentHealingItem = HealingItemType; } } } } bool AFortniteCloneCharacter::ServerSpawnAndAttachHealingItem_Validate(int HealingItemType, FTransform SpawnTransform) { return true; } void AFortniteCloneCharacter::ClientCameraAimIn_Implementation() { FollowCamera->FieldOfView = 45; } void AFortniteCloneCharacter::ClientCameraAimOut_Implementation() { FollowCamera->FieldOfView = 90; } void AFortniteCloneCharacter::ClientGetBulletTransform_Implementation() { FName WeaponSocketName = TEXT("hand_right_socket_pickaxe"); if (CurrentWeaponType == 1) { WeaponSocketName = TEXT("hand_right_socket_rifle"); } else if (CurrentWeaponType == 2) { WeaponSocketName = TEXT("hand_right_socket_shotgun"); } if (CurrentWeapon != nullptr) { TArray<UStaticMeshComponent*> Components; CurrentWeapon->GetComponents(Components); // find the muzzle component for (int i = 0; i < Components.Num(); i++) { if (Components[i]->GetName() == "Weapon") { UStaticMeshComponent* WeaponComponent = Components[i]; FVector MuzzleLocation = WeaponComponent->GetSocketLocation("muzzle"); //DrawDebugSphere(GetWorld(), MuzzleLocation, 200, 26, FColor(255, 0, 0), true, -1, 0, 2); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::SanitizeFloat(GetActorRotation().Roll) +FString(" ") + FString::SanitizeFloat(GetActorRotation().Pitch) +FString(" ") + FString::SanitizeFloat(GetActorRotation().Yaw)); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::SanitizeFloat(MuzzleLocation.X) + FString(" ") + FString::SanitizeFloat(MuzzleLocation.Y) + FString(" ") + FString::SanitizeFloat(MuzzleLocation.Z)); if (GetController() != nullptr) { APlayerController* PlayerController = Cast<APlayerController>(GetController()); FRotator CameraRotation = PlayerController->PlayerCameraManager->GetCameraRotation(); FVector CameraLocation = PlayerController->PlayerCameraManager->GetCameraLocation(); PlayerController->GetPlayerViewPoint(CameraLocation, CameraRotation); FVector ShootDirection = CameraRotation.Vector(); const FVector StartTrace = FollowCamera->GetComponentLocation(); const FVector EndTrace = StartTrace + ShootDirection * 100000.0; FHitResult Impact; FCollisionQueryParams CollisionParams; GetWorld()->LineTraceSingleByChannel(Impact, StartTrace, EndTrace, ECC_Visibility, CollisionParams); if (Impact.bBlockingHit) { FTransform SpawnTransform(ShootDirection.Rotation(), MuzzleLocation); ServerSpawnProjectile(SpawnTransform); } break; } } } } } void AFortniteCloneCharacter::NetMulticastPlayPickaxeSwingAnimation_Implementation() { PlayAnimMontage(PickaxeSwingingAnimation, 1.f, NAME_None); } void AFortniteCloneCharacter::NetMulticastPlayShootRifleAnimation_Implementation() { PlayAnimMontage(RifleHipShootingAnimation); } void AFortniteCloneCharacter::NetMulticastPlayShootShotgunAnimation_Implementation() { PlayAnimMontage(ShotgunHipShootingAnimation); } void AFortniteCloneCharacter::NetMulticastPlayShootRifleIronsightsAnimation_Implementation() { PlayAnimMontage(RifleIronsightsShootingAnimation); } void AFortniteCloneCharacter::NetMulticastPlayShootShotgunIronsightsAnimation_Implementation() { PlayAnimMontage(ShotgunIronsightsShootingAnimation); } void AFortniteCloneCharacter::NetMulticastPlayUseHealingItemAnimation_Implementation() { PlayAnimMontage(HealingAnimation); } void AFortniteCloneCharacter::NetMulticastPlayReloadRifleAnimation_Implementation() { PlayAnimMontage(RifleHipReloadAnimation); } void AFortniteCloneCharacter::NetMulticastPlayReloadRifleIronsightsAnimation_Implementation() { PlayAnimMontage(RifleIronsightsReloadAnimation); } void AFortniteCloneCharacter::NetMulticastPlayReloadShotgunAnimation_Implementation() { PlayAnimMontage(ShotgunHipReloadAnimation); } void AFortniteCloneCharacter::NetMulticastPlayReloadShotgunIronsightsAnimation_Implementation() { PlayAnimMontage(ShotgunIronsightsReloadAnimation); } void AFortniteCloneCharacter::ClientDrawHitMarker_Implementation() { if (GetController()) { APlayerController* PlayerController = Cast<APlayerController>(GetController()); if (PlayerController->GetHUD()) { AFortniteCloneHUD* FortniteCloneHUD = Cast<AFortniteCloneHUD>(PlayerController->GetHUD()); FortniteCloneHUD->DrawHitMarker(); } } } void AFortniteCloneCharacter::ClientDrawBloodEffect_Implementation() { if (GetController()) { APlayerController* PlayerController = Cast<APlayerController>(GetController()); if (PlayerController->GetHUD()) { AFortniteCloneHUD* FortniteCloneHUD = Cast<AFortniteCloneHUD>(PlayerController->GetHUD()); FortniteCloneHUD->DrawBloodSplash(); } } } void AFortniteCloneCharacter::ClientDestroyStructure_Implementation(int StructureId) { for (int i = 0; i < ClientSpawnedStructures.Num(); i++) { if (ClientSpawnedStructures[i] != nullptr) { if (ClientSpawnedStructures[i]->Id == StructureId) { ABuildingActor* Structure = ClientSpawnedStructures[i]; ClientSpawnedStructures.Remove(Structure); Structure->Destroy(); break; } } } } void AFortniteCloneCharacter::ClientGetWeaponTransform_Implementation(int WeaponType) { //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString("ClientGetweapontransform")); FTransform SpawnTransform(GetActorRotation(), GetActorLocation()); ServerSpawnAndAttachWeapon(WeaponType, SpawnTransform); } void AFortniteCloneCharacter::ClientGetHealingItemTransform_Implementation(int HealingItemType) { /*FString LogMsg = FString("client get healing item transform Current healing item type ") + FString::FromInt(HealingItemType); UE_LOG(LogFortniteCloneCharacter, Warning, TEXT("%s"), *LogMsg);*/ FTransform SpawnTransform(GetActorRotation(), GetActorLocation()); ServerSpawnAndAttachHealingItem(HealingItemType, SpawnTransform); } void AFortniteCloneCharacter::OnRepSetSkin() { USkeletalMeshComponent* CharacterMesh = GetMesh(); if (MaterialOrMaterialInstance == 0) { // assign UMaterial CharacterMesh->SetMaterial(0, SkinMaterials[CurrentSkin]); } else { // assign UMaterialInstance CharacterMesh->SetMaterial(0, SkinMaterialInstances[CurrentSkin]); } }
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "itkMacro.h" #include "otbImage.h" #include "otbImageFileReader.h" /* Example usage: ./FlusserMomentsImageFunctionExample Input/ROISpot5.png 2 */ // This example illustrates the use of the \doxygen{otb}{FlusserMomentsImageFunction}. // // The first step required to use this filter is to include its header file. #include "otbFlusserMomentsImageFunction.h" int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " inputImageFile "; std::cerr << " neighborhood_radius" << std::endl; return EXIT_FAILURE; } const char* inputFilename = argv[1]; const unsigned int radius = atoi(argv[2]); using InputPixelType = unsigned char; const unsigned int Dimension = 2; using InputImageType = otb::Image<InputPixelType, Dimension>; using ReaderType = otb::ImageFileReader<InputImageType>; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFilename); // The \doxygen{otb}{FlusserMomentsImageFunction} is templated over the // input image type and the output (real) type value, so we start by // defining: using FlusserType = otb::FlusserMomentsImageFunction<InputImageType>; using MomentType = FlusserType::OutputType; FlusserType::Pointer fmFunction = FlusserType::New(); // We can choose the region and the pixel of the image which will // used as coordinate origin // for the moment computation InputImageType::RegionType region; InputImageType::SizeType size; InputImageType::IndexType start; start[0] = 0; start[1] = 0; size[0] = 50; size[1] = 50; reader->Update(); InputImageType::Pointer image = reader->GetOutput(); region.SetIndex(start); region.SetSize(size); image->SetRegions(region); image->Update(); InputImageType::IndexType center; center[0] = start[0] + size[0] / 2; center[1] = start[1] + size[1] / 2; // Next, we plug the input image into the complex moment function // and we set its parameters. fmFunction->SetInputImage(image); fmFunction->SetNeighborhoodRadius(radius); // In order to get the value of the moment, we call the // \code{EvaluateAtIndex} method. MomentType Result = fmFunction->EvaluateAtIndex(center); for (unsigned int j = 0; j < 11; ++j) { std::cout << "The moment of order " << j + 1 << " is equal to " << Result[j] << std::endl; } // \relatedClasses // \begin{itemize} // \item \doxygen{otb}{FlusserPathFunction} // \end{itemize} return EXIT_SUCCESS; }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet/wallet.h" #include "askpassphrasedialog.h" #include <QDebug> #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; const QString AddressTableModel::Zerocoin = "X"; struct AddressTableEntry { enum Type { Sending, Receiving, Zerocoin, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; QString pubcoin; AddressTableEntry() {} AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {} AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const { return a.address < b.address; } bool operator()(const AddressTableEntry& a, const QString& b) const { return a.address < b; } bool operator()(const QString& a, const AddressTableEntry& b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet* wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel* parent; AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch (status) { case CT_NEW: if (inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } void updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin; switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model"; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = isUsed; parent->emitDataChanged(lowerIndex); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry* index(int idx) { if (idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Label: if (rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch (rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if (role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if (index.column() == Label) { // Do nothing, if old label == new label if (rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if (index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if (boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if (newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if (wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if (rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const { if (!index.isValid()) return 0; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if (rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column() == Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); AddressTableEntry* data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Update address book model from articash core priv->updateEntry(address, label, isMine, purpose, status); } void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Update stealth address book model from Bitcoin core priv->updateEntry(pubCoin, isUsed, status); } QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if (type == Send) { if (!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if (type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if (!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true)); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if (!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent) { Q_UNUSED(parent); AddressTableEntry* rec = priv->index(row); if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString& address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString& address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if (lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex())); }
#ifndef NUIE_UINODEGROUP_HPP #define NUIE_UINODEGROUP_HPP #include "NE_LocString.hpp" #include "NE_NodeGroup.hpp" #include "NUIE_UINode.hpp" namespace NUIE { class GroupDrawingImage : public DrawingImage { public: GroupDrawingImage (); virtual ~GroupDrawingImage (); void Reset (); const Rect& GetRect () const; void SetRect (const Rect& newRect); private: Rect rect; }; class NodeRectGetter { public: NodeRectGetter (); virtual ~NodeRectGetter (); virtual Rect GetNodeRect (const NE::NodeId& nodeId) const = 0; }; class UINodeGroup : public NE::NodeGroup { DYNAMIC_SERIALIZABLE (UINodeGroup); public: UINodeGroup (); UINodeGroup (const NE::LocString& name); ~UINodeGroup (); const NE::LocString& GetName () const; void SetName (const std::wstring& newName); size_t GetBackgroundColorIndex () const; void SetBackgroundColorIndex (size_t newColorIndex); Rect GetRect (NodeUIDrawingEnvironment& env, const NodeRectGetter& rectGetter, const NE::NodeCollection& nodes) const; void Draw (NodeUIDrawingEnvironment& env, const NodeRectGetter& rectGetter, const NE::NodeCollection& nodes) const; void InvalidateGroupDrawing () const; virtual NE::Stream::Status Read (NE::InputStream& inputStream) override; virtual NE::Stream::Status Write (NE::OutputStream& outputStream) const override; private: const GroupDrawingImage& GetDrawingImage (NodeUIDrawingEnvironment& env, const NodeRectGetter& rectGetter, const NE::NodeCollection& nodes) const; void UpdateDrawingImage (NodeUIDrawingEnvironment& env, const NodeRectGetter& rectGetter, const NE::NodeCollection& nodes) const; NE::LocString name; size_t backgroundColorIndex; mutable GroupDrawingImage drawingImage; }; using UINodeGroupPtr = std::shared_ptr<UINodeGroup>; using UINodeGroupConstPtr = std::shared_ptr<const UINodeGroup>; } #endif
#include "legacy_future.h" #include <library/cpp/testing/unittest/registar.h> namespace NThreading { Y_UNIT_TEST_SUITE(TLegacyFutureTest) { int intf() { return 17; } Y_UNIT_TEST(TestIntFunction) { TLegacyFuture<int> f((&intf)); UNIT_ASSERT_VALUES_EQUAL(17, f.Get()); } static int r; void voidf() { r = 18; } Y_UNIT_TEST(TestVoidFunction) { r = 0; TLegacyFuture<> f((&voidf)); f.Get(); UNIT_ASSERT_VALUES_EQUAL(18, r); } struct TSampleClass { int mValue; TSampleClass(int value) : mValue(value) { } int Calc() { return mValue + 1; } }; Y_UNIT_TEST(TestMethod) { TLegacyFuture<int> f11(std::bind(&TSampleClass::Calc, TSampleClass(3))); UNIT_ASSERT_VALUES_EQUAL(4, f11.Get()); TLegacyFuture<int> f12(std::bind(&TSampleClass::Calc, TSampleClass(3)), SystemThreadFactory()); UNIT_ASSERT_VALUES_EQUAL(4, f12.Get()); TSampleClass c(5); TLegacyFuture<int> f21(std::bind(&TSampleClass::Calc, std::ref(c))); UNIT_ASSERT_VALUES_EQUAL(6, f21.Get()); TLegacyFuture<int> f22(std::bind(&TSampleClass::Calc, std::ref(c)), SystemThreadFactory()); UNIT_ASSERT_VALUES_EQUAL(6, f22.Get()); } struct TSomeThreadPool: public IThreadFactory {}; Y_UNIT_TEST(TestFunction) { std::function<int()> f((&intf)); UNIT_ASSERT_VALUES_EQUAL(17, TLegacyFuture<int>(f).Get()); UNIT_ASSERT_VALUES_EQUAL(17, TLegacyFuture<int>(f, SystemThreadFactory()).Get()); if (false) { TSomeThreadPool* q = nullptr; TLegacyFuture<int>(f, q); // just check compiles, do not start } } } }
//#include "stdafx.h" extern "C" { #include "..\defs.h" } // total_h sum of the heights of all the items in the display queue // // display_y the display queue y coordinate that maps to the screen // // maxy_y the maximum value that display_y can have // // total_w the maximum width including right and left margins extern int line_height; extern int left_margin; extern int right_margin; extern int display_x; extern int display_y; extern int display_height; extern int display_width; extern int max_x; extern int max_y; extern int total_w; extern int total_h; extern int update_display_request; extern int text_width(int, char *); #define SMALL_FONT 1 #define DEFAULT_FONT 2 #define DRAW_HRULE 20 #define DRAW_LEFT_BRACKET 21 #define DRAW_RIGHT_BRACKET 22 #define DRAW_LINE 23 #define DRAW_POINT 24 #define DRAW_BOX 25 #define DRAW_LABEL 26 #define MAXHIST 10001 extern "C" { int test_flag; } int term_flag; // type // // 0 print string // // 1 display struct yy { unsigned char type, attr; int w, h; union { char *s; unsigned char *d; } u; } term[MAXHIST]; static int head, tail, len; static char buf[1000]; #define OUTBUFLEN 10000 char out_buf[OUTBUFLEN + 1]; int out_count; static void printcharf(int); static void advance(void); void printchar_nowrap(int c) { if (c == '\n' || len < 80) print_char(c); } static int breaking_char(int c) { switch (c) { case ' ': case '+': case '-': case '*': case '/': case ',': case '(': return 1; } return 0; } extern "C" void printchar(int c) { if (test_flag && out_count < OUTBUFLEN) out_buf[out_count++] = c; printcharf(c); if (len >= 80) printcharf('\n'); } static void printcharf(int c) { char *s; if (c == '\n') { s = (char *) malloc(len + 1); if (s == NULL) return; buf[len] = 0; strcpy(s, buf); len = 0; term[tail].type = 0; term[tail].attr = term_flag; term[tail].u.s = s; term[tail].w = text_width(DEFAULT_FONT, s); term[tail].h = line_height; total_h += line_height; if (total_h - max_y > display_height) max_y = total_h - display_height; display_y = max_y; advance(); return; } if (len < (int) sizeof buf) buf[len++] = c; } extern "C" void printstr(char *s) { while (*s) printchar(*s++); } extern "C" void clear_term(void) { while (head != tail) { free(term[head].u.s); head = (head + 1) % MAXHIST; } head = 0; tail = 0; display_x = 0; display_y = 0; max_x = 0; max_y = 0; total_w = 0; total_h = 0; update_display_request = 1; } extern "C" void eval_clear(void) { if (test_flag == 0) clear_term(); save_binding(symbol(PRATT)); save_binding(symbol(TRACE)); save_binding(symbol(TTY)); clear_symbols(); run_init_script(); gc(); // garbage collection restore_binding(symbol(TTY)); restore_binding(symbol(TRACE)); restore_binding(symbol(PRATT)); push_symbol(NIL); // result } void shipout(unsigned char *d, int w, int h) { term[tail].type = 1; term[tail].attr = 0; term[tail].u.d = d; term[tail].w = w; term[tail].h = h + line_height; total_h += h + line_height; if (total_h - max_y > display_height) max_y = total_h - display_height; display_y = max_y; advance(); } static void advance(void) { int h; tail = (tail + 1) % MAXHIST; if (tail == head) { h = term[head].h; free(term[head].u.s); head = (head + 1) % MAXHIST; total_h -= h; max_y -= h; display_y -= h; if (max_y < 0) max_y = 0; if (display_y < 0) display_y = 0; } update_display_request = 1; } extern void drawstring(int, int, char *, int); extern void drawpixel(int, int, int, int); extern void draw_left_bracket(int, int, int, int); extern void draw_right_bracket(int, int, int, int); extern void draw_line(int, int, int, int); static int find_start_index(void); static void draw(int); static int yy; void draw_display(void) { int i; update_display_request = 0; i = find_start_index(); total_w = 0; while (i != tail && yy < display_height) { draw(i); i = (i + 1) % MAXHIST; } max_x = total_w - display_width; if (max_x < display_x) max_x = display_x; } // find the top of the term static int find_start_index(void) { int indx, y; indx = tail; // back up until y <= display_y y = total_h; while (1) { if (y <= display_y) break; if (indx == head) break; indx = (indx + MAXHIST - 1) % MAXHIST; y -= term[indx].h; } // if too tall then negative start_y if (y - display_y < 0) yy = y - display_y; else yy = 0; return indx; } extern void draw_text(int, int, int, char *, int); extern void draw_hrule(int, int, int); extern void draw_point(int, int, int, int); extern void draw_box(int, int, int, int); extern void use_graph_pen(void); extern void use_normal_pen(void); #define N(x) (((int) d[k + x] << 24) | ((int) d[k + x + 1] << 16) | ((int) d[k + x + 2]) << 8 | ((int) d[k + x + 3])) static void draw(int i) { int cmd, h, k, len, w, xx, x, x1, x2, y, y1, y2; unsigned char *d; w = term[i].w; switch (term[i].type) { case 0: if (term[i].u.s[0]) { xx = left_margin; if (xx + w + right_margin > total_w) total_w = xx + w + right_margin; xx -= display_x; len = (int) strlen(term[i].u.s); draw_text(DEFAULT_FONT, xx, yy, term[i].u.s, len); } yy += line_height; break; case 1: yy += line_height / 2; d = term[i].u.d; xx = (display_width - w) / 2; // center it if (xx < left_margin) xx = left_margin; if (xx + w + right_margin > total_w) total_w = xx + w + right_margin; xx -= display_x; k = 0; while (1) { cmd = d[k]; if (cmd == 0) break; switch (cmd) { case 1: use_normal_pen(); x = 256 * d[k + 1] + d[k + 2]; y = 256 * d[k + 3] + d[k + 4]; if (x > 32767) x -= 65536; if (y > 32767) y -= 65536; len = d[k + 5]; draw_text(SMALL_FONT, xx + x, yy + y, (char *) d + k + 6, len); // small font k = k + 6 + len; break; case 2: // default font case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: use_normal_pen(); x = N(1); y = N(5); len = N(9); draw_text(cmd, xx + x, yy + y, (char *) d + k + 13, len); k = k + 13 + len; break; case DRAW_HRULE: use_normal_pen(); x = N(1); y = N(5); w = N(9); h = N(13); draw_hrule(xx + x, yy + y, w); k += 17; break; case DRAW_LEFT_BRACKET: use_normal_pen(); x = N(1); y = N(5); w = N(9); h = N(13); draw_left_bracket(xx + x, yy + y, w, h); k += 17; break; case DRAW_RIGHT_BRACKET: use_normal_pen(); x = N(1); y = N(5); w = N(9); h = N(13); draw_right_bracket(xx + x, yy + y, w, h); k += 17; break; case DRAW_LINE: use_normal_pen(); x1 = 256 * d[k + 1] + d[k + 2]; y1 = 256 * d[k + 3] + d[k + 4]; x2 = 256 * d[k + 5] + d[k + 6]; y2 = 256 * d[k + 7] + d[k + 8]; draw_line(xx + x1, yy + y1, xx + x2, yy + y2); k += 9; break; case DRAW_POINT: use_graph_pen(); x = 256 * d[k + 1] + d[k + 2]; y = 256 * d[k + 3] + d[k + 4]; draw_point(xx, x, yy, y); k += 5; break; case DRAW_BOX: x1 = 256 * d[k + 1] + d[k + 2]; y1 = 256 * d[k + 3] + d[k + 4]; x2 = 256 * d[k + 5] + d[k + 6]; y2 = 256 * d[k + 7] + d[k + 8]; draw_box(xx + x1, yy + y1, xx + x2, yy + y2); k += 9; break; default: d[4] = 0; // error, force stop k = 4; break; } } // 1/2 line_height above and below display yy -= line_height / 2; yy += term[i].h; use_normal_pen(); break; } } char * get_tty_buf(void) { int i, j, n; char *s; i = head; n = 0; while (i != tail) { if (term[i].type == 0) n += (int) strlen(term[i].u.s) + 1; i = (i + 1) % MAXHIST; } s = (char *) malloc(n + 1); if (s == NULL) return s; i = head; j = 0; while (i != tail) { if (term[i].type == 0) { strcpy(s + j, term[i].u.s); j += (int) strlen(term[i].u.s); s[j++] = '\n'; } i = (i + 1) % MAXHIST; } s[j] = 0; return s; }
class Solution { public: int regionsBySlashes(vector<string>& grid) { const int n = grid.size(); // g := upscaled grid vector<vector<int>> g(n * 3, vector<int>(n * 3)); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == '/') { g[i * 3][j * 3 + 2] = 1; g[i * 3 + 1][j * 3 + 1] = 1; g[i * 3 + 2][j * 3] = 1; } else if (grid[i][j] == '\\') { g[i * 3][j * 3] = 1; g[i * 3 + 1][j * 3 + 1] = 1; g[i * 3 + 2][j * 3 + 2] = 1; } int ans = 0; for (int i = 0; i < n * 3; ++i) for (int j = 0; j < n * 3; ++j) if (g[i][j] == 0) { dfs(g, i, j); ++ans; } return ans; } private: void dfs(vector<vector<int>>& g, int i, int j) { if (i < 0 || i == g.size() || j < 0 || j == g[0].size()) return; if (g[i][j] != 0) return; g[i][j] = 2; // mark 2 as visited dfs(g, i + 1, j); dfs(g, i - 1, j); dfs(g, i, j + 1); dfs(g, i, j - 1); } };
// Modifications copyright (C) 2017, Baidu.com, Inc. // Copyright 2017 The Apache Software Foundation // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/metrics.h" #include <sstream> #include <memory> #include <functional> #include <boost/algorithm/string/join.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include "common/logging.h" #include "gutil/strings/substitute.h" #include "util/palo_metrics.h" #include "http/web_page_handler.h" namespace palo { template <> void ToJsonValue<std::string>(const std::string& value, const TUnit::type unit, rapidjson::Document* document, rapidjson::Value* out_val) { rapidjson::Value val(value.c_str(), document->GetAllocator()); *out_val = val; } void Metric::AddStandardFields(rapidjson::Document* document, rapidjson::Value* val) { rapidjson::Value name(_key.c_str(), document->GetAllocator()); val->AddMember("name", name, document->GetAllocator()); rapidjson::Value desc(_description.c_str(), document->GetAllocator()); val->AddMember("description", desc, document->GetAllocator()); rapidjson::Value metric_value(ToHumanReadable().c_str(), document->GetAllocator()); val->AddMember("human_readable", metric_value, document->GetAllocator()); } MetricDefs* MetricDefs::GetInstance() { // Note that this is not thread-safe in C++03 (but will be in C++11 see // http://stackoverflow.com/a/19907903/132034). We don't bother with the double-check // locking pattern because it introduces complexity whereas a race is very unlikely // and it doesn't matter if we construct two instances since MetricDefsConstants is // just a constant map. static MetricDefs instance; return &instance; } TMetricDef MetricDefs::Get(const std::string& key, const std::string& arg) { MetricDefs* inst = GetInstance(); std::map<std::string, TMetricDef>::iterator it = inst->_metric_defs.TMetricDefs.find(key); if (it == inst->_metric_defs.TMetricDefs.end()) { DCHECK(false) << "Could not find metric definition for key=" << key << " arg=" << arg; return TMetricDef(); } TMetricDef md = it->second; md.__set_key(strings::Substitute(md.key, arg)); md.__set_description(strings::Substitute(md.description, arg)); return md; } MetricGroup::MetricGroup(const std::string& name) : _obj_pool(new ObjectPool()), _name(name) { } Status MetricGroup::init(WebPageHandler* webserver) { if (webserver != NULL) { WebPageHandler::PageHandlerCallback default_callback = boost::bind<void>(boost::mem_fn(&MetricGroup::text_callback), this, _1, _2); webserver->register_page("/metrics", default_callback); WebPageHandler::PageHandlerCallback json_callback = boost::bind<void>(boost::mem_fn(&MetricGroup::json_callback), this, _1, _2); webserver->register_page("/jsonmetrics", json_callback); } return Status::OK; } /// TODO: init, CMCompatibleCallback, TemplateCallback are for new webserver /* Status MetricGroup::init(Webserver* webserver) { if (webserver != NULL) { Webserver::UrlCallback default_callback = bind<void>(mem_fn(&MetricGroup::CMCompatibleCallback), this, _1, _2); webserver->RegisterUrlCallback("/jsonmetrics", "legacy-metrics.tmpl", default_callback, false); Webserver::UrlCallback json_callback = bind<void>(mem_fn(&MetricGroup::TemplateCallback), this, _1, _2); webserver->RegisterUrlCallback("/metrics", "metrics.tmpl", json_callback); } return Status::OK(); } void MetricGroup::CMCompatibleCallback(const Webserver::ArgumentMap& args, Document* document) { // If the request has a 'metric' argument, search all top-level metrics for that metric // only. Otherwise, return document with list of all metrics at the top level. Webserver::ArgumentMap::const_iterator metric_name = args.find("metric"); lock_guard<SpinLock> l(_lock); if (metric_name != args.end()) { MetricMap::const_iterator metric = _metric_map.find(metric_name->second); if (metric != _metric_map.end()) { metric->second->ToLegacyJson(document); } return; } stack<MetricGroup*> groups; groups.push(this); do { // Depth-first traversal of children to flatten all metrics, which is what was // expected by CM before we introduced metric groups. MetricGroup* group = groups.top(); for (const ChildGroupMap::value_type& child: group->_children) { groups.push(child.second); } for (const MetricMap::value_type& m: group->_metric_map) { m.second->ToLegacyJson(document); } } while (!groups.empty()); } void MetricGroup::TemplateCallback(const Webserver::ArgumentMap& args, Document* document) { Webserver::ArgumentMap::const_iterator metric_group = args.find("metric_group"); lock_guard<SpinLock> l(_lock); // If no particular metric group is requested, render this metric group (and all its // children). if (metric_group == args.end()) { Value container; ToJson(true, document, &container); document->AddMember("metric_group", container, document->GetAllocator()); return; } // Search all metric groups to find the one we're looking for. In the future, we'll // change this to support path-based resolution of metric groups. MetricGroup* found_group = NULL; stack<MetricGroup*> groups; groups.push(this); while (!groups.empty() && found_group == NULL) { // Depth-first traversal of children to flatten all metrics, which is what was // expected by CM before we introduced metric groups. MetricGroup* group = groups.top(); groups.pop(); for (const ChildGroupMap::value_type& child: group->_children) { if (child.first == metric_group->second) { found_group = child.second; break; } groups.push(child.second); } } if (found_group != NULL) { Value container; found_group->ToJson(false, document, &container); document->AddMember("metric_group", container, document->GetAllocator()); } else { Value error(Substitute("Metric group $0 not found", metric_group->second).c_str(), document->GetAllocator()); document->AddMember("error", error, document->GetAllocator()); } } */ void MetricGroup::ToJson(bool include_children, rapidjson::Document* document, rapidjson::Value* out_val) { rapidjson::Value metric_list(rapidjson::kArrayType); for (const MetricMap::value_type& m: _metric_map) { rapidjson::Value metric_value; m.second->ToJson(document, &metric_value); metric_list.PushBack(metric_value, document->GetAllocator()); } rapidjson::Value container(rapidjson::kObjectType); container.AddMember("metrics", metric_list, document->GetAllocator()); container.AddMember("name", rapidjson::Value(_name.c_str(), document->GetAllocator()).Move(), document->GetAllocator()); if (include_children) { rapidjson::Value child_groups(rapidjson::kArrayType); for (const ChildGroupMap::value_type& child: _children) { rapidjson::Value child_value; child.second->ToJson(true, document, &child_value); child_groups.PushBack(child_value, document->GetAllocator()); } container.AddMember("child_groups", child_groups, document->GetAllocator()); } *out_val = container; } MetricGroup* MetricGroup::GetOrCreateChildGroup(const std::string& name) { std::lock_guard<SpinLock> l(_lock); ChildGroupMap::iterator it = _children.find(name); if (it != _children.end()) return it->second; MetricGroup* group = _obj_pool->add(new MetricGroup(name)); _children[name] = group; return group; } MetricGroup* MetricGroup::FindChildGroup(const std::string& name) { std::lock_guard<SpinLock> l(_lock); ChildGroupMap::iterator it = _children.find(name); if (it != _children.end()) return it->second; return NULL; } ///TODO: debug string is for new web server /* std::string MetricGroup::debug_string() { Webserver::ArgumentMap empty_map; rapidjson::Document document; document.SetObject(); TemplateCallback(empty_map, &document); StringBuffer strbuf; PrettyWriter<StringBuffer> writer(strbuf); document.Accept(writer); return strbuf.GetString(); } */ TMetricDef MakeTMetricDef(const std::string& key, TMetricKind::type kind, TUnit::type unit) { TMetricDef ret; ret.__set_key(key); ret.__set_kind(kind); ret.__set_units(unit); return ret; } void MetricGroup::print_metric_map(std::stringstream* output) { std::lock_guard<SpinLock> l(_lock); BOOST_FOREACH(const MetricMap::value_type & m, _metric_map) { m.second->print(output); (*output) << std::endl; } } void MetricGroup::print_metric_map_as_json(std::vector<std::string>* metrics) { std::lock_guard<SpinLock> l(_lock); BOOST_FOREACH(const MetricMap::value_type & m, _metric_map) { std::stringstream ss; m.second->print_json(&ss); metrics->push_back(ss.str()); } } std::string MetricGroup::debug_string() { std::stringstream ss; WebPageHandler::ArgumentMap empty_map; text_callback(empty_map, &ss); return ss.str(); } std::string MetricGroup::debug_string_json() { std::stringstream ss; WebPageHandler::ArgumentMap empty_map; json_callback(empty_map, &ss); return ss.str(); } void MetricGroup::text_callback(const WebPageHandler::ArgumentMap& args, std::stringstream* output) { (*output) << "<pre>"; print_metric_map(output); (*output) << "</pre>"; } void MetricGroup::json_callback(const WebPageHandler::ArgumentMap& args, std::stringstream* output) { (*output) << "{"; std::vector<std::string> metrics; print_metric_map_as_json(&metrics); (*output) << boost::join(metrics, ",\n"); (*output) << "}"; } template<> void print_primitive_as_json<std::string>(const std::string& v, std::stringstream* out) { (*out) << "\"" << v << "\""; } }
// ExtractingFilePath.cpp #include "../../../Common/Wildcard.h" #include "../../../Windows/FileName.h" #include "ExtractingFilePath.h" static void ReplaceIncorrectChars(UString &s) { { for (unsigned i = 0; i < s.Len(); i++) { wchar_t c = s[i]; if ( #ifdef _WIN32 c == ':' || c == '*' || c == '?' || c < 0x20 || c == '<' || c == '>' || c == '|' || c == '"' || c == '/' // || c == 0x202E // RLO || #endif c == WCHAR_PATH_SEPARATOR) s.ReplaceOneCharAtPos(i, '_'); } } #ifdef _WIN32 { for (unsigned i = s.Len(); i != 0;) { wchar_t c = s[--i]; if (c != '.' && c != ' ') break; s.ReplaceOneCharAtPos(i, '_'); } } #endif } #ifdef _WIN32 /* WinXP-64 doesn't support ':', '\\' and '/' symbols in name of alt stream. But colon in postfix ":$DATA" is allowed. WIN32 functions don't allow empty alt stream name "name:" */ void Correct_AltStream_Name(UString &s) { unsigned len = s.Len(); const unsigned kPostfixSize = 6; if (s.Len() >= kPostfixSize && StringsAreEqualNoCase_Ascii(s.RightPtr(kPostfixSize), ":$DATA")) len -= kPostfixSize; for (unsigned i = 0; i < len; i++) { wchar_t c = s[i]; if (c == ':' || c == '\\' || c == '/' || c == 0x202E // RLO ) s.ReplaceOneCharAtPos(i, '_'); } if (s.IsEmpty()) s = L'_'; } static const unsigned g_ReservedWithNum_Index = 4; static const char * const g_ReservedNames[] = { "CON", "PRN", "AUX", "NUL", "COM", "LPT" }; static bool IsSupportedName(const UString &name) { for (unsigned i = 0; i < ARRAY_SIZE(g_ReservedNames); i++) { const char *reservedName = g_ReservedNames[i]; unsigned len = MyStringLen(reservedName); if (name.Len() < len) continue; if (!name.IsPrefixedBy_Ascii_NoCase(reservedName)) continue; if (i >= g_ReservedWithNum_Index) { wchar_t c = name[len]; if (c < L'0' || c > L'9') continue; len++; } for (;;) { wchar_t c = name[len++]; if (c == 0 || c == '.') return false; if (c != ' ') break; } } return true; } static void CorrectUnsupportedName(UString &name) { if (!IsSupportedName(name)) name.InsertAtFront(L'_'); } #endif static void Correct_PathPart(UString &s) { // "." and ".." if (s[0] == '.' && (s[1] == 0 || s[1] == '.' && s[2] == 0)) s.Empty(); #ifdef _WIN32 else ReplaceIncorrectChars(s); #endif } // static const wchar_t *k_EmptyReplaceName = L"[]"; static const wchar_t k_EmptyReplaceName = L'_'; UString Get_Correct_FsFile_Name(const UString &name) { UString res = name; Correct_PathPart(res); #ifdef _WIN32 CorrectUnsupportedName(res); #endif if (res.IsEmpty()) res = k_EmptyReplaceName; return res; } void Correct_FsPath(bool absIsAllowed, UStringVector &parts, bool isDir) { unsigned i = 0; if (absIsAllowed) { #if defined(_WIN32) && !defined(UNDER_CE) bool isDrive = false; #endif if (parts[0].IsEmpty()) { i = 1; #if defined(_WIN32) && !defined(UNDER_CE) if (parts.Size() > 1 && parts[1].IsEmpty()) { i = 2; if (parts.Size() > 2 && parts[2] == L"?") { i = 3; if (parts.Size() > 3 && NWindows::NFile::NName::IsDrivePath2(parts[3])) { isDrive = true; i = 4; } } } #endif } #if defined(_WIN32) && !defined(UNDER_CE) else if (NWindows::NFile::NName::IsDrivePath2(parts[0])) { isDrive = true; i = 1; } if (isDrive) { // we convert "c:name" to "c:\name", if absIsAllowed path. const UString &ds = parts[i - 1]; if (ds.Len() != 2) { UString s = ds.Ptr(2); parts.Insert(i, s); } } #endif } for (; i < parts.Size();) { UString &s = parts[i]; Correct_PathPart(s); if (s.IsEmpty()) { if (isDir || i != parts.Size() - 1) { parts.Delete(i); continue; } s = k_EmptyReplaceName; } else { #ifdef _WIN32 CorrectUnsupportedName(s); #endif } i++; } if (!isDir) { if (parts.IsEmpty()) parts.Add(k_EmptyReplaceName); else { UString &s = parts.Back(); if (s.IsEmpty()) s = k_EmptyReplaceName; } } } UString MakePathFromParts(const UStringVector &parts) { UString s; FOR_VECTOR (i, parts) { if (i != 0) s.Add_PathSepar(); s += parts[i]; } return s; }
/** * ScriptDev3 is an extension for mangos providing enhanced features for * area triggers, creatures, game objects, instances, items, and spells beyond * the default database scripting in mangos. * * Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/> * Copyright (C) 2014-2016 MaNGOS <https://getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ /** * ScriptData * SDName: GO_Scripts * SD%Complete: 100 * SDComment: Quest support: 5097, 5098, Barov_journal->Teaches spell 26089 * SDCategory: Game Objects * EndScriptData */ /** * ContentData * go_barov_journal #if defined (TBC) || defined (WOTLK) || defined (CATA) * go_ethereum_prison * go_ethereum_stasis #endif #if defined (WOTLK) || defined (CATA) * go_mysterious_snow_mound * go_tele_to_dalaran_crystal * go_tele_to_violet_stand #endif * go_andorhal_tower #if defined (WOTLK) || defined (CATA) * go_scourge_enclosure * go_lab_work_reagents #endif * EndContentData */ #include "precompiled.h" /*###### ## go_barov_journal ######*/ enum { SPELL_TAILOR_FELCLOTH_BAG = 26086, SPELL_LEARN_FELCLOTH_BAG = 26095 }; struct go_barov_journal : public GameObjectScript { go_barov_journal() : GameObjectScript("go_barov_journal") {} bool OnUse(Player* pPlayer, GameObject* /*pGo*/) override { if (pPlayer->HasSkill(SKILL_TAILORING) && pPlayer->GetBaseSkillValue(SKILL_TAILORING) >= 280 && !pPlayer->HasSpell(SPELL_TAILOR_FELCLOTH_BAG)) { pPlayer->CastSpell(pPlayer, SPELL_LEARN_FELCLOTH_BAG, false); } return true; } }; #if defined (TBC) || defined (WOTLK) || defined (CATA) /*###### ## go_ethereum_prison ######*/ enum { FACTION_LC = 1011, FACTION_SHAT = 935, FACTION_CE = 942, FACTION_CON = 933, FACTION_KT = 989, FACTION_SPOR = 970, SPELL_REP_LC = 39456, SPELL_REP_SHAT = 39457, SPELL_REP_CE = 39460, SPELL_REP_CON = 39474, SPELL_REP_KT = 39475, SPELL_REP_SPOR = 39476 }; const uint32 uiNpcPrisonEntry[] = { 22810, 22811, 22812, 22813, 22814, 22815, // good guys 20783, 20784, 20785, 20786, 20788, 20789, 20790 // bad guys }; struct go_ethereum_prison : public GameObjectScript { go_ethereum_prison() : GameObjectScript("go_ethereum_prison") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { uint8 uiRandom = urand(0, countof(uiNpcPrisonEntry) - 1); if (Creature* pCreature = pPlayer->SummonCreature(uiNpcPrisonEntry[uiRandom], pGo->GetPositionX(), pGo->GetPositionY(), pGo->GetPositionZ(), pGo->GetAngle(pPlayer), TEMPSUMMON_TIMED_OOC_DESPAWN, 30000)) { if (!pCreature->IsHostileTo(pPlayer)) { uint32 uiSpell = 0; if (FactionTemplateEntry const* pFaction = pCreature->getFactionTemplateEntry()) { switch (pFaction->faction) { case FACTION_LC: uiSpell = SPELL_REP_LC; break; case FACTION_SHAT: uiSpell = SPELL_REP_SHAT; break; case FACTION_CE: uiSpell = SPELL_REP_CE; break; case FACTION_CON: uiSpell = SPELL_REP_CON; break; case FACTION_KT: uiSpell = SPELL_REP_KT; break; case FACTION_SPOR: uiSpell = SPELL_REP_SPOR; break; } if (uiSpell) { pCreature->CastSpell(pPlayer, uiSpell, false); } else { script_error_log("go_ethereum_prison summoned creature (entry %u) but faction (%u) are not expected by script.", pCreature->GetEntry(), pCreature->getFaction()); } } } } return false; } }; /*###### ## go_ethereum_stasis ######*/ const uint32 uiNpcStasisEntry[] = { 22825, 20888, 22827, 22826, 22828 }; struct go_ethereum_stasis : public GameObjectScript { go_ethereum_stasis() : GameObjectScript("go_ethereum_stasis") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { uint8 uiRandom = urand(0, countof(uiNpcStasisEntry) - 1); pPlayer->SummonCreature(uiNpcStasisEntry[uiRandom], pGo->GetPositionX(), pGo->GetPositionY(), pGo->GetPositionZ(), pGo->GetAngle(pPlayer), TEMPSUMMON_TIMED_OOC_DESPAWN, 30000); return false; } }; /*###### ## go_jump_a_tron ######*/ enum { SPELL_JUMP_A_TRON = 33382, NPC_JUMP_A_TRON = 19041 }; struct go_jump_a_tron : public GameObjectScript { go_jump_a_tron() : GameObjectScript("go_jump_a_tron") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { if (Creature* pCreature = GetClosestCreatureWithEntry(pGo, NPC_JUMP_A_TRON, INTERACTION_DISTANCE)) { pCreature->CastSpell(pPlayer, SPELL_JUMP_A_TRON, false); } return false; } }; #endif #if defined (WOTLK) || defined (CATA) /*###### ## go_mysterious_snow_mound ######*/ struct go_mysterious_snow_mound : public GameObjectScript { enum { SPELL_SUMMON_DEEP_JORMUNGAR = 66510, SPELL_SUMMON_MOLE_MACHINE = 66492, SPELL_SUMMON_MARAUDER = 66491, }; go_mysterious_snow_mound() : GameObjectScript("go_mysterious_snow_mound") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { if (urand(0, 1)) { pPlayer->CastSpell(pPlayer, SPELL_SUMMON_DEEP_JORMUNGAR, true); } else { // This is basically wrong, but added for support. // Mole machine would summon, along with unkonwn GO (a GO trap?) and then // the npc would summon with base of that location. pPlayer->CastSpell(pPlayer, SPELL_SUMMON_MOLE_MACHINE, true); pPlayer->CastSpell(pPlayer, SPELL_SUMMON_MARAUDER, true); } pGo->SetLootState(GO_JUST_DEACTIVATED); return true; } }; /*###### ## go_tele_to_dalaran_crystal ######*/ enum { QUEST_LEARN_LEAVE_RETURN = 12790, QUEST_TELE_CRYSTAL_FLAG = 12845 }; struct go_tele_to_dalaran_crystal : public GameObjectScript { go_tele_to_dalaran_crystal() : GameObjectScript("go_tele_to_dalaran_crystal") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { if (pPlayer->GetQuestRewardStatus(QUEST_TELE_CRYSTAL_FLAG)) return false; // TODO: must send error message (what kind of message? On-screen?) return true; } }; /*###### ## go_tele_to_violet_stand ######*/ struct go_tele_to_violet_stand : public GameObjectScript { go_tele_to_violet_stand() : GameObjectScript("go_tele_to_violet_stand") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { if (pPlayer->GetQuestRewardStatus(QUEST_LEARN_LEAVE_RETURN) || pPlayer->GetQuestStatus(QUEST_LEARN_LEAVE_RETURN) == QUEST_STATUS_INCOMPLETE) return false; // TODO: must send error message (what kind of message? On-screen?) return true; } }; #endif /*###### ## go_andorhal_tower ######*/ enum { QUEST_ALL_ALONG_THE_WATCHTOWERS_ALLIANCE = 5097, QUEST_ALL_ALONG_THE_WATCHTOWERS_HORDE = 5098, NPC_ANDORHAL_TOWER_1 = 10902, NPC_ANDORHAL_TOWER_2 = 10903, NPC_ANDORHAL_TOWER_3 = 10904, NPC_ANDORHAL_TOWER_4 = 10905, GO_ANDORHAL_TOWER_1 = 176094, GO_ANDORHAL_TOWER_2 = 176095, GO_ANDORHAL_TOWER_3 = 176096, GO_ANDORHAL_TOWER_4 = 176097 }; struct go_andorhal_tower : public GameObjectScript { go_andorhal_tower() : GameObjectScript("go_andorhal_tower") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { if (pPlayer->GetQuestStatus(QUEST_ALL_ALONG_THE_WATCHTOWERS_ALLIANCE) == QUEST_STATUS_INCOMPLETE || pPlayer->GetQuestStatus(QUEST_ALL_ALONG_THE_WATCHTOWERS_HORDE) == QUEST_STATUS_INCOMPLETE) { uint32 uiKillCredit = 0; switch (pGo->GetEntry()) { case GO_ANDORHAL_TOWER_1: uiKillCredit = NPC_ANDORHAL_TOWER_1; break; case GO_ANDORHAL_TOWER_2: uiKillCredit = NPC_ANDORHAL_TOWER_2; break; case GO_ANDORHAL_TOWER_3: uiKillCredit = NPC_ANDORHAL_TOWER_3; break; case GO_ANDORHAL_TOWER_4: uiKillCredit = NPC_ANDORHAL_TOWER_4; break; } if (uiKillCredit) { pPlayer->KilledMonsterCredit(uiKillCredit); } } return true; } }; #if defined (CLASSIC) || defined (TBC) enum { GOSSIP_TABLE_THEKA = 1653, QUEST_SPIDER_GOD = 2936 }; struct go_table_theka : public GameObjectScript { go_table_theka() : GameObjectScript("go_table_theka") {} bool OnGossipHello(Player* pPlayer, GameObject* pGo) override { if (pPlayer->GetQuestStatus(QUEST_SPIDER_GOD) == QUEST_STATUS_INCOMPLETE) pPlayer->AreaExploredOrEventHappens(QUEST_SPIDER_GOD); pPlayer->SEND_GOSSIP_MENU(GOSSIP_TABLE_THEKA, pGo->GetObjectGuid()); return true; } }; #endif #if defined (WOTLK) || defined (CATA) /*###### ## go_scourge_enclosure ######*/ enum { SPELL_GYMER_LOCK_EXPLOSION = 55529, NPC_GYMER_LOCK_DUMMY = 29928 }; struct go_scourge_enclosure : public GameObjectScript { go_scourge_enclosure() : GameObjectScript("go_scourge_enclosure") {} bool OnUse(Player* pPlayer, GameObject* pGo) override { std::list<Creature*> m_lResearchersList; GetCreatureListWithEntryInGrid(m_lResearchersList, pGo, NPC_GYMER_LOCK_DUMMY, 15.0f); if (!m_lResearchersList.empty()) { for (std::list<Creature*>::iterator itr = m_lResearchersList.begin(); itr != m_lResearchersList.end(); ++itr) { (*itr)->CastSpell((*itr), SPELL_GYMER_LOCK_EXPLOSION, true); } } pPlayer->KilledMonsterCredit(NPC_GYMER_LOCK_DUMMY); return true; } }; /*###### ## go_lab_work_reagents ######*/ enum { QUEST_LAB_WORK = 12557, SPELL_WIRHERED_BATWING_KILL_CREDIT = 51226, SPELL_MUDDY_MIRE_MAGGOT_KILL_CREDIT = 51227, SPELL_AMBERSEED_KILL_CREDIT = 51228, SPELL_CHILLED_SERPENT_MUCUS_KILL_CREDIT = 51229, GO_AMBERSEED = 190459, GO_CHILLED_SERPENT_MUCUS = 190462, GO_WITHERED_BATWING = 190473, GO_MUDDY_MIRE_MAGGOTS = 190478, }; struct go_lab_work_reagents : public GameObjectScript { go_lab_work_reagents() : GameObjectScript("go_lab_work_reagents") {} bool GOUse_go_lab_work_reagents(Player* pPlayer, GameObject* pGo) { if (pPlayer->GetQuestStatus(QUEST_LAB_WORK) == QUEST_STATUS_INCOMPLETE) { uint32 uiCreditSpellId = 0; switch (pGo->GetEntry()) { case GO_AMBERSEED: uiCreditSpellId = SPELL_AMBERSEED_KILL_CREDIT; break; case GO_CHILLED_SERPENT_MUCUS: uiCreditSpellId = SPELL_CHILLED_SERPENT_MUCUS_KILL_CREDIT; break; case GO_WITHERED_BATWING: uiCreditSpellId = SPELL_WIRHERED_BATWING_KILL_CREDIT; break; case GO_MUDDY_MIRE_MAGGOTS: uiCreditSpellId = SPELL_MUDDY_MIRE_MAGGOT_KILL_CREDIT; break; } if (uiCreditSpellId) pPlayer->CastSpell(pPlayer, uiCreditSpellId, true); } return false; } }; #endif void AddSC_go_scripts() { Script* s; s = new go_barov_journal(); s->RegisterSelf(); s = new go_andorhal_tower(); s->RegisterSelf(); #if defined (CLASSIC) || defined (TBC) s = new go_table_theka(); s->RegisterSelf(); #endif #if defined (TBC) || defined (WOTLK) || defined (CATA) s = new go_ethereum_prison(); s->RegisterSelf(); s = new go_ethereum_stasis(); s->RegisterSelf(); s = new go_jump_a_tron(); s->RegisterSelf(); #endif #if defined (WOTLK) || defined (CATA) s = new go_mysterious_snow_mound(); s->RegisterSelf(); s = new go_tele_to_dalaran_crystal(); s->RegisterSelf(); s = new go_tele_to_violet_stand(); s->RegisterSelf(); s = new go_scourge_enclosure(); s->RegisterSelf(); s = new go_lab_work_reagents(); s->RegisterSelf(); #endif //pNewScript = new Script; //pNewScript->Name = "go_barov_journal"; //pNewScript->pGOUse = &GOUse_go_barov_journal; //pNewScript->RegisterSelf(); //#if defined (TBC) || defined (WOTLK) || defined (CATA) //pNewScript = new Script; //pNewScript->Name = "go_ethereum_prison"; //pNewScript->pGOUse = &GOUse_go_ethereum_prison; //pNewScript->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "go_ethereum_stasis"; //pNewScript->pGOUse = &GOUse_go_ethereum_stasis; //pNewScript->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "go_jump_a_tron"; //pNewScript->pGOUse = &GOUse_go_jump_a_tron; //pNewScript->RegisterSelf(); //#endif //#if defined (WOTLK) || defined (CATA) //pNewScript = new Script; //pNewScript->Name = "go_mysterious_snow_mound"; //pNewScript->pGOUse = &GOUse_go_mysterious_snow_mound; //pNewScript->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "go_tele_to_dalaran_crystal"; //pNewScript->pGOUse = &GOUse_go_tele_to_dalaran_crystal; //pNewScript->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "go_tele_to_violet_stand"; //pNewScript->pGOUse = &GOUse_go_tele_to_violet_stand; //pNewScript->RegisterSelf(); //#endif //pNewScript = new Script; //pNewScript->Name = "go_andorhal_tower"; //pNewScript->pGOUse = &GOUse_go_andorhal_tower; //pNewScript->RegisterSelf(); //#if defined (CLASSIC) || defined (TBC) //pNewScript = new Script; //pNewScript->Name = "go_table_theka"; //pNewScript->pGossipHelloGO = &GossipHelloGO_table_theka; //pNewScript->RegisterSelf(); //#endif //#if defined (WOTLK) || defined (CATA) //pNewScript = new Script; //pNewScript->Name = "go_scourge_enclosure"; //pNewScript->pGOUse = &GOUse_go_scourge_enclosure; //pNewScript->RegisterSelf(); //pNewScript = new Script; //pNewScript->Name = "go_lab_work_reagents"; //pNewScript->pGOUse = &GOUse_go_lab_work_reagents; //pNewScript->RegisterSelf(); //#endif }
#if defined(__cplusplus) && (__cplusplus >= 201103L) #include <iostream> #include <iomanip> #include <atomic> #include "myatomics.h" #ifdef _OPENMP # include <omp.h> # define OMP_PARALLEL _Pragma("omp parallel reduction(+:tavg) reduction(max:tmax) reduction(min:tmin) reduction(max:tinc)") # define OMP_BARRIER _Pragma("omp barrier") # define OMP_CRITICAL _Pragma("omp critical") # define OMP_SINGLE _Pragma("omp single") # define OMP_ATOMIC _Pragma("omp atomic") # define OMP_ATOMIC_CAPTURE _Pragma("omp atomic capture") # define OMP_ATOMIC_SC _Pragma("omp atomic seq_cst") # define OMP_ATOMIC_CAPTURE_SC _Pragma("omp atomic capture seq_cst") #else # error No OpenMP support! #endif int main(int argc, char * argv[]) { int iterations = (argc>1) ? atoi(argv[1]) : 10000000; std::cout << "thread counter benchmark\n"; std::cout << "num threads = " << omp_get_max_threads() << "\n"; std::cout << "iterations = " << iterations << "\n"; #ifdef SEQUENTIAL_CONSISTENCY std::cout << "memory model = " << "seq_cst"; #else std::cout << "memory model = " << "relaxed"; #endif std::cout << std::endl; double tmin, tmax, tavg, tinc; std::atomic<double> counter = {0.0}; double omp_counter = 0.0; std::cout << "1) atomic_sum(&counter, t0)\n"; counter = 0.0; tmin=1.e9, tmax=-1.0, tavg=-1.0, tinc=-1.0; OMP_PARALLEL { std::atomic_thread_fence(std::memory_order_seq_cst); /// START TIME OMP_BARRIER double t0 = omp_get_wtime(); for (int i=0; i<iterations; ++i) { atomic_sum_explicit(&counter, t0, std::memory_order_relaxed); } /// STOP TIME double t1 = omp_get_wtime(); OMP_BARRIER double t2 = omp_get_wtime(); std::atomic_thread_fence(std::memory_order_seq_cst); double junk = counter; /// PRINT TIME double dt = (t1-t0); tmin = dt; tmax = dt; tavg = dt; tinc = t2-t0; OMP_SINGLE { std::cerr << "junk = " << junk << std::endl; } } tavg /= omp_get_max_threads(); std::cout << "total time elapsed (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (s)\n"; tmin *= 1.e9/iterations; tmax *= 1.e9/iterations; tavg *= 1.e9/iterations; tinc *= 1.e9/iterations; std::cout << "time per iteration (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (ns)\n"; std::cout << "3) #pragma omp atomic\n"; omp_counter = 0.0; tmin=1.e9, tmax=-1.0, tavg=-1.0, tinc=-1.0; OMP_PARALLEL { /// START TIME OMP_BARRIER double t0 = omp_get_wtime(); for (int i=0; i<iterations; ++i) { OMP_ATOMIC omp_counter += t0; } /// STOP TIME double t1 = omp_get_wtime(); OMP_BARRIER double t2 = omp_get_wtime(); double junk = omp_counter; /// PRINT TIME double dt = (t1-t0); tmin = dt; tmax = dt; tavg = dt; tinc = t2-t0; OMP_SINGLE { std::cerr << "junk = " << junk << std::endl; } } tavg /= omp_get_max_threads(); std::cout << "total time elapsed (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (s)\n"; tmin *= 1.e9/iterations; tmax *= 1.e9/iterations; tavg *= 1.e9/iterations; tinc *= 1.e9/iterations; std::cout << "time per iteration (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (ns)\n"; std::cout << "5) atomic_sum(&counter, t0, seq_cst)\n"; counter = 0.0; tmin=1.e9, tmax=-1.0, tavg=-1.0, tinc=-1.0; OMP_PARALLEL { std::atomic_thread_fence(std::memory_order_seq_cst); /// START TIME OMP_BARRIER double t0 = omp_get_wtime(); for (int i=0; i<iterations; ++i) { atomic_sum_explicit(&counter, t0, std::memory_order_seq_cst); } /// STOP TIME double t1 = omp_get_wtime(); OMP_BARRIER double t2 = omp_get_wtime(); std::atomic_thread_fence(std::memory_order_seq_cst); double junk = counter; /// PRINT TIME double dt = (t1-t0); tmin = dt; tmax = dt; tavg = dt; tinc = t2-t0; OMP_SINGLE { std::cerr << "junk = " << junk << std::endl; } } tavg /= omp_get_max_threads(); std::cout << "total time elapsed (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (s)\n"; tmin *= 1.e9/iterations; tmax *= 1.e9/iterations; tavg *= 1.e9/iterations; tinc *= 1.e9/iterations; std::cout << "time per iteration (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (ns)\n"; std::cout << "7) #pragma omp atomic seq_cst\n"; omp_counter = 0.0; tmin=1.e9, tmax=-1.0, tavg=-1.0, tinc=-1.0; OMP_PARALLEL { /// START TIME OMP_BARRIER double t0 = omp_get_wtime(); for (int i=0; i<iterations; ++i) { OMP_ATOMIC_SC omp_counter += t0; } /// STOP TIME double t1 = omp_get_wtime(); OMP_BARRIER double t2 = omp_get_wtime(); double junk = omp_counter; /// PRINT TIME double dt = (t1-t0); tmin = dt; tmax = dt; tavg = dt; tinc = t2-t0; OMP_SINGLE { std::cerr << "junk = " << junk << std::endl; } } tavg /= omp_get_max_threads(); std::cout << "total time elapsed (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (s)\n"; tmin *= 1.e9/iterations; tmax *= 1.e9/iterations; tavg *= 1.e9/iterations; tinc *= 1.e9/iterations; std::cout << "time per iteration (min,max,avg,inc) = " << tmin << ", " << tmax << ", " << tavg << ", " << tinc << " (ns)\n"; return 0; } #else // C++11 #error You need C++11 for this test! #endif // C++11
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <memory> #include "itt.hpp" #include "ngraph/op/convert.hpp" #include "ngraph/op/greater.hpp" #include "ngraph/op/maximum.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/runtime/reference/maximum.hpp" #include "ngraph/type/element_type.hpp" using namespace std; using namespace ngraph; // ------------------------------------ v0 ------------------------------------- namespace maximumop { template <element::Type_t ET> bool evaluate(const HostTensorPtr& arg0, const HostTensorPtr& arg1, const HostTensorPtr& out, const op::AutoBroadcastSpec& broadcast_spec) { runtime::reference::maximum(arg0->get_data_ptr<ET>(), arg1->get_data_ptr<ET>(), out->get_data_ptr<ET>(), arg0->get_shape(), arg1->get_shape(), broadcast_spec); return true; } bool evaluate_maximum(const HostTensorPtr& arg0, const HostTensorPtr& arg1, const HostTensorPtr& out, const op::AutoBroadcastSpec& broadcast_spec) { bool rc = true; out->set_broadcast(broadcast_spec, arg0, arg1); switch (arg0->get_element_type()) { NGRAPH_TYPE_CASE(evaluate_maximum, i32, arg0, arg1, out, broadcast_spec); NGRAPH_TYPE_CASE(evaluate_maximum, i64, arg0, arg1, out, broadcast_spec); NGRAPH_TYPE_CASE(evaluate_maximum, u32, arg0, arg1, out, broadcast_spec); NGRAPH_TYPE_CASE(evaluate_maximum, u64, arg0, arg1, out, broadcast_spec); NGRAPH_TYPE_CASE(evaluate_maximum, f16, arg0, arg1, out, broadcast_spec); NGRAPH_TYPE_CASE(evaluate_maximum, f32, arg0, arg1, out, broadcast_spec); default: rc = false; break; } return rc; } } // ------------------------------------ v1 ------------------------------------- constexpr NodeTypeInfo op::v1::Maximum::type_info; op::v1::Maximum::Maximum(const Output<Node>& arg0, const Output<Node>& arg1, const AutoBroadcastSpec& auto_broadcast) : BinaryElementwiseArithmetic(arg0, arg1, auto_broadcast) { constructor_validate_and_infer_types(); } shared_ptr<Node> op::v1::Maximum::clone_with_new_inputs(const OutputVector& new_args) const { NGRAPH_OP_SCOPE(v1_Maximum_clone_with_new_inputs); check_new_args_count(this, new_args); return make_shared<op::v1::Maximum>(new_args.at(0), new_args.at(1), this->get_autob()); } bool op::v1::Maximum::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const { NGRAPH_OP_SCOPE(v1_Maximum_evaluate); return maximumop::evaluate_maximum(inputs[0], inputs[1], outputs[0], get_autob()); }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/alexaforbusiness/model/RejectSkillRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::AlexaForBusiness::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; RejectSkillRequest::RejectSkillRequest() : m_skillIdHasBeenSet(false) { } Aws::String RejectSkillRequest::SerializePayload() const { JsonValue payload; if(m_skillIdHasBeenSet) { payload.WithString("SkillId", m_skillId); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection RejectSkillRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AlexaForBusiness.RejectSkill")); return headers; }
// Generated by Haxe 4.2.1+bf9ff69 #include <hxcpp.h> #ifndef INCLUDED_lime_graphics_opengl_ext_EXT_color_buffer_half_float #include <lime/graphics/opengl/ext/EXT_color_buffer_half_float.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_15fbe66fa7b31d40_5_new,"lime.graphics.opengl.ext.EXT_color_buffer_half_float","new",0x4f3c63e5,"lime.graphics.opengl.ext.EXT_color_buffer_half_float.new","lime/graphics/opengl/ext/EXT_color_buffer_half_float.hx",5,0x98cfc34d) namespace lime{ namespace graphics{ namespace opengl{ namespace ext{ void EXT_color_buffer_half_float_obj::__construct(){ HX_STACKFRAME(&_hx_pos_15fbe66fa7b31d40_5_new) HXLINE( 14) this->UNSIGNED_NORMALIZED_EXT = 35863; HXLINE( 13) this->FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 33297; HXLINE( 11) this->R16F_EXT = 33325; HXLINE( 10) this->RG16F_EXT = 33327; HXLINE( 8) this->RGB16F_EXT = 34843; HXLINE( 7) this->RGBA16F_EXT = 34842; } Dynamic EXT_color_buffer_half_float_obj::__CreateEmpty() { return new EXT_color_buffer_half_float_obj; } void *EXT_color_buffer_half_float_obj::_hx_vtable = 0; Dynamic EXT_color_buffer_half_float_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< EXT_color_buffer_half_float_obj > _hx_result = new EXT_color_buffer_half_float_obj(); _hx_result->__construct(); return _hx_result; } bool EXT_color_buffer_half_float_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6360f823; } EXT_color_buffer_half_float_obj::EXT_color_buffer_half_float_obj() { } ::hx::Val EXT_color_buffer_half_float_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"R16F_EXT") ) { return ::hx::Val( R16F_EXT ); } break; case 9: if (HX_FIELD_EQ(inName,"RG16F_EXT") ) { return ::hx::Val( RG16F_EXT ); } break; case 10: if (HX_FIELD_EQ(inName,"RGB16F_EXT") ) { return ::hx::Val( RGB16F_EXT ); } break; case 11: if (HX_FIELD_EQ(inName,"RGBA16F_EXT") ) { return ::hx::Val( RGBA16F_EXT ); } break; case 23: if (HX_FIELD_EQ(inName,"UNSIGNED_NORMALIZED_EXT") ) { return ::hx::Val( UNSIGNED_NORMALIZED_EXT ); } break; case 41: if (HX_FIELD_EQ(inName,"FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT") ) { return ::hx::Val( FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT ); } } return super::__Field(inName,inCallProp); } ::hx::Val EXT_color_buffer_half_float_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"R16F_EXT") ) { R16F_EXT=inValue.Cast< int >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"RG16F_EXT") ) { RG16F_EXT=inValue.Cast< int >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"RGB16F_EXT") ) { RGB16F_EXT=inValue.Cast< int >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"RGBA16F_EXT") ) { RGBA16F_EXT=inValue.Cast< int >(); return inValue; } break; case 23: if (HX_FIELD_EQ(inName,"UNSIGNED_NORMALIZED_EXT") ) { UNSIGNED_NORMALIZED_EXT=inValue.Cast< int >(); return inValue; } break; case 41: if (HX_FIELD_EQ(inName,"FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT") ) { FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EXT_color_buffer_half_float_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("RGBA16F_EXT",8f,65,df,9d)); outFields->push(HX_("RGB16F_EXT",76,b0,bd,f1)); outFields->push(HX_("RG16F_EXT",ae,08,3f,88)); outFields->push(HX_("R16F_EXT",b1,4d,16,6c)); outFields->push(HX_("FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT",48,84,fe,43)); outFields->push(HX_("UNSIGNED_NORMALIZED_EXT",83,60,c1,33)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo EXT_color_buffer_half_float_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,RGBA16F_EXT),HX_("RGBA16F_EXT",8f,65,df,9d)}, {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,RGB16F_EXT),HX_("RGB16F_EXT",76,b0,bd,f1)}, {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,RG16F_EXT),HX_("RG16F_EXT",ae,08,3f,88)}, {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,R16F_EXT),HX_("R16F_EXT",b1,4d,16,6c)}, {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT),HX_("FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT",48,84,fe,43)}, {::hx::fsInt,(int)offsetof(EXT_color_buffer_half_float_obj,UNSIGNED_NORMALIZED_EXT),HX_("UNSIGNED_NORMALIZED_EXT",83,60,c1,33)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *EXT_color_buffer_half_float_obj_sStaticStorageInfo = 0; #endif static ::String EXT_color_buffer_half_float_obj_sMemberFields[] = { HX_("RGBA16F_EXT",8f,65,df,9d), HX_("RGB16F_EXT",76,b0,bd,f1), HX_("RG16F_EXT",ae,08,3f,88), HX_("R16F_EXT",b1,4d,16,6c), HX_("FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT",48,84,fe,43), HX_("UNSIGNED_NORMALIZED_EXT",83,60,c1,33), ::String(null()) }; ::hx::Class EXT_color_buffer_half_float_obj::__mClass; void EXT_color_buffer_half_float_obj::__register() { EXT_color_buffer_half_float_obj _hx_dummy; EXT_color_buffer_half_float_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.graphics.opengl.ext.EXT_color_buffer_half_float",73,8d,21,d5); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(EXT_color_buffer_half_float_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< EXT_color_buffer_half_float_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EXT_color_buffer_half_float_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EXT_color_buffer_half_float_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace graphics } // end namespace opengl } // end namespace ext
// // 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuGeometryUnion.h" #include "GuPCMShapeConvex.h" #include "GuVecConvexHull.h" #include "GuPCMContactGen.h" #include "CmRenderOutput.h" using namespace physx; using namespace Gu; namespace physx { namespace Gu { const PxU8 gPCMBoxPolygonData[24] = { 0, 3, 2, 1, 1, 2, 6, 5, 5, 6, 7, 4, 4, 7, 3, 0, 3, 7, 6, 2, 4, 0, 1, 5, }; Gu::PCMPolygonalBox::PCMPolygonalBox(const PxVec3& halfSide) : mHalfSide(halfSide) { //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ PxVec3 minimum = -mHalfSide; PxVec3 maximum = mHalfSide; // Generate 8 corners of the bbox mVertices[0] = PxVec3(minimum.x, minimum.y, minimum.z); mVertices[1] = PxVec3(maximum.x, minimum.y, minimum.z); mVertices[2] = PxVec3(maximum.x, maximum.y, minimum.z); mVertices[3] = PxVec3(minimum.x, maximum.y, minimum.z); mVertices[4] = PxVec3(minimum.x, minimum.y, maximum.z); mVertices[5] = PxVec3(maximum.x, minimum.y, maximum.z); mVertices[6] = PxVec3(maximum.x, maximum.y, maximum.z); mVertices[7] = PxVec3(minimum.x, maximum.y, maximum.z); //Setup the polygons for(PxU8 i=0; i < 6; i++) { mPolygons[i].mNbVerts = 4; mPolygons[i].mVRef8 = PxU16(i*4); } // ### planes needs *very* careful checks // X axis mPolygons[1].mPlane.n = PxVec3(1.0f, 0.0f, 0.0f); mPolygons[1].mPlane.d = -mHalfSide.x; mPolygons[3].mPlane.n = PxVec3(-1.0f, 0.0f, 0.0f); mPolygons[3].mPlane.d = -mHalfSide.x; mPolygons[1].mMinIndex = 0; mPolygons[3].mMinIndex = 1; PX_ASSERT(mPolygons[1].getMin(mVertices) == -mHalfSide.x); PX_ASSERT(mPolygons[3].getMin(mVertices) == -mHalfSide.x); // Y axis mPolygons[4].mPlane.n = PxVec3(0.f, 1.0f, 0.0f); mPolygons[4].mPlane.d = -mHalfSide.y; mPolygons[5].mPlane.n = PxVec3(0.0f, -1.0f, 0.0f); mPolygons[5].mPlane.d = -mHalfSide.y; mPolygons[4].mMinIndex = 0; mPolygons[5].mMinIndex = 2; PX_ASSERT(mPolygons[4].getMin(mVertices) == -mHalfSide.y); PX_ASSERT(mPolygons[5].getMin(mVertices) == -mHalfSide.y); // Z axis mPolygons[2].mPlane.n = PxVec3(0.f, 0.0f, 1.0f); mPolygons[2].mPlane.d = -mHalfSide.z; mPolygons[0].mPlane.n = PxVec3(0.0f, 0.0f, -1.0f); mPolygons[0].mPlane.d = -mHalfSide.z; mPolygons[2].mMinIndex = 0; mPolygons[0].mMinIndex = 4; PX_ASSERT(mPolygons[2].getMin(mVertices) == -mHalfSide.z); PX_ASSERT(mPolygons[0].getMin(mVertices) == -mHalfSide.z); } void Gu::PCMPolygonalBox::getPolygonalData(Gu::PolygonalData* PX_RESTRICT dst) const { dst->mCenter = PxVec3(0.0f, 0.0f, 0.0f); dst->mNbVerts = 8; dst->mNbPolygons = 6; dst->mPolygons = mPolygons; dst->mNbEdges = 0; dst->mVerts = mVertices; dst->mPolygonVertexRefs = gPCMBoxPolygonData; dst->mFacesByEdges = NULL; dst->mVerticesByEdges = NULL; dst->mInternal.mRadius = 0.0f; dst->mInternal.mExtents[0] = 0.0f; dst->mInternal.mExtents[1] = 0.0f; dst->mInternal.mExtents[2] = 0.0f; } static void getPCMPolygonalData_Convex(Gu::PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Ps::aos::Mat33V& vertexToShape) { using namespace Ps::aos; const Vec3V vertexSpaceCenterOfMass = V3LoadU(src->mCenterOfMass); const Vec3V shapeSpaceCenterOfMass = M33MulV3(vertexToShape, vertexSpaceCenterOfMass); V3StoreU(shapeSpaceCenterOfMass, dst->mCenter); dst->mNbVerts = src->mNbHullVertices; dst->mNbPolygons = src->mNbPolygons; dst->mNbEdges = src->mNbEdges; dst->mPolygons = src->mPolygons; dst->mVerts = src->getHullVertices(); dst->mPolygonVertexRefs = src->getVertexData8(); dst->mFacesByEdges = src->getFacesByEdges8(); dst->mVerticesByEdges = src->getVerticesByEdges16(); dst->mBigData = src->mBigConvexRawData; dst->mInternal = src->mInternal; } static void getPCMPolygonalData_Convex(Gu::PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling) { dst->mCenter = scaling * src->mCenterOfMass; dst->mNbVerts = src->mNbHullVertices; dst->mNbPolygons = src->mNbPolygons; dst->mNbEdges = src->mNbEdges; dst->mPolygons = src->mPolygons; dst->mVerts = src->getHullVertices(); dst->mPolygonVertexRefs = src->getVertexData8(); dst->mFacesByEdges = src->getFacesByEdges8(); dst->mVerticesByEdges = src->getVerticesByEdges16(); dst->mBigData = src->mBigConvexRawData; dst->mInternal = src->mInternal; } void getPCMConvexData(const Gu::ConvexHullV& convexHull, const bool idtScale, PolygonalData& polyData) { PX_ASSERT(!convexHull.hullData->mAABB.isEmpty()); //this is used to calculate the convex hull's center of mass getPCMPolygonalData_Convex(&polyData, convexHull.hullData, convexHull.vertex2Shape); if(!idtScale) polyData.mInternal.reset(); } bool getPCMConvexData(const Gu::GeometryUnion& shape, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData) { const PxConvexMeshGeometryLL& shapeConvex = shape.get<const PxConvexMeshGeometryLL>(); const bool idtScale = shapeConvex.scale.isIdentity(); if(!idtScale) scaling.init(shapeConvex.scale); PX_ASSERT(!shapeConvex.hullData->mAABB.isEmpty()); bounds = shapeConvex.hullData->mAABB.transformFast(scaling.getVertex2ShapeSkew()); getPCMPolygonalData_Convex(&polyData, shapeConvex.hullData, scaling); return idtScale; } } }
// Copyright (c) 2014, HelightXu // Author: Zhwen Xu<HelightXu@gmail.com> // Created: 2014-03-09 // Description: // #define _MULTI_THREADED #include <pthread.h> #include <stdio.h> #include <time.h> #include <unistd.h> void checkResults(const char* msg, const int rc) { // printf("%s : %d \r\n", msg, rc); } /* For safe condition variable usage, must use a boolean predicate and */ /* a mutex with the condition. */ int conditionMet = 0; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #define NTHREADS 5 void *threadfunc(void *parm) { int rc; rc = pthread_mutex_lock(&mutex); checkResults("pthread_mutex_lock()\n", rc); while (!conditionMet) { printf("Thread blocked\n"); rc = pthread_cond_wait(&cond, &mutex); printf("pthread_cond_wait wakeup ret: %d\n", rc); } rc = pthread_mutex_unlock(&mutex); checkResults("pthread_mutex_lock()\n", rc); return NULL; } int main(int argc, char **argv) { int rc = 0; int i; pthread_t threadid[NTHREADS]; printf("Enter Testcase - %s\n", argv[0]); printf("Create %d threads\n", NTHREADS); for (i = 0; i < NTHREADS; ++i) { rc = pthread_create(&threadid[i], NULL, threadfunc, NULL); checkResults("pthread_create()\n", rc); } sleep(5); /* Sleep is not a very robust way to serialize threads */ rc = pthread_mutex_lock(&mutex); checkResults("pthread_mutex_lock()\n", rc); /* The condition has occured. Set the flag and wake up any waiting threads */ conditionMet = 1; printf("Wake up all waiting threads...\n"); rc = pthread_cond_broadcast(&cond); checkResults("pthread_cond_broadcast()\n", rc); rc = pthread_mutex_unlock(&mutex); checkResults("pthread_mutex_unlock()\n", rc); printf("Wait for threads and cleanup\n"); for (i=0; i<NTHREADS; ++i) { rc = pthread_join(threadid[i], NULL); checkResults("pthread_join()\n", rc); } pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); printf("Main completed\n"); return 0; }
// represents raw data. // Copyright Sundeep S. Sangha 2013 - 2017. // 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 DATA_PATTERN_BITS_RAW_TCC #define DATA_PATTERN_BITS_RAW_TCC namespace data_pattern { template <typename Allocator> Allocator raw<Allocator>::get_allocator ( ) const { return this->allocator; } /* default ctor */ template <typename Allocator> raw<Allocator>::raw ( Allocator const & _alloc ) : data_ptr (nullptr) , data_size (0) , allocator (_alloc) {} /* copy ctor */ template <typename Allocator> raw<Allocator>::raw ( raw<Allocator> const & _other ) : data_ptr (nullptr) , data_size (_other.data_size) , allocator (_other.allocator) { if (this != &_other){ this->data_ptr = this->allocator.allocate (_other.data_size); memcpy (data_ptr, _other.data_ptr, _other.data_size); this->data_size = _other.data_size; } } /* ctor */ template <typename Allocator> template <typename T> raw<Allocator>::raw ( T const & _src , std::size_t _size , Allocator const & _alloc ) : data_ptr (nullptr) , data_size (_size) , allocator (_alloc) { this->data_ptr = this->allocator.allocate(_size); memcpy(data_ptr, & _src, _size); } /* dtor */ template <typename Allocator> raw<Allocator>::~raw ( ){ if (this->data_ptr == nullptr) return; this->allocator.deallocate(this->data_ptr, this->data_size); } /* size */ template <typename Allocator> std::size_t raw<Allocator>::size ( ) const { return this->data_size; } template <typename Allocator> std::size_t size ( raw<Allocator> const & _raw ){ return _raw.size(); } /**/ template <typename Allocator> typename raw<Allocator>::data_type * raw<Allocator>::data ( ) const { return this->data_ptr; } /* copy assignment */ template <typename Allocator> template <typename Alloc> raw<Allocator> & raw<Allocator>::operator = ( raw<Alloc> const & _rhs ){ if (this != &_rhs){ this->data_ptr = this->allocator.allocate(_rhs.data_size); memcpy (data_ptr, _rhs.data_ptr, _rhs.data_size); this->data_size = _rhs.data_size; } return *this; } /* copy assignment */ template <typename Allocator> raw<Allocator> & raw<Allocator>::operator = ( raw<Allocator> const & _rhs ){ if (this != &_rhs){ this->data_ptr = this->allocator.allocate(_rhs.data_size); memcpy (data_ptr, _rhs.data_ptr, _rhs.data_size); this->data_size = _rhs.data_size; } return *this; } /* move assignment */ template <typename Allocator> raw<Allocator> & raw<Allocator>::operator = ( raw<Allocator> && _rhs ){ //propagate_on_container_move_assignmen ?? if (this != &_rhs){ this->data_size = std::move(_rhs.data_size); this->data_ptr = std::move(_rhs.data_ptr); _rhs.data_ptr = nullptr; } return *this; } template <typename Allocator> raw<Allocator>::raw( raw<Allocator> && _other ) : data_ptr (std::move(_other.data_ptr)) , data_size (std::move(_other.data_size)) , allocator (std::move(_other.allocator)) { _other.data_ptr = nullptr; } template <typename Allocator> template <typename Allocator2> bool raw<Allocator>::operator == ( raw<Allocator2> const & _rhs ) const { if (this->size() != _rhs.size()) return false; return std::equal(begin(*this), end(*this), begin(_rhs)); } template <typename Allocator1, typename Allocator2> bool operator != ( raw<Allocator1> const & _lhs , raw<Allocator2> const & _rhs ){ return !(_lhs == _rhs); } template <typename Allocator> typename raw<Allocator>::data_type * begin ( raw<Allocator> & _raw ){ return _raw.data(); } template <typename Allocator> typename raw<Allocator>::data_type * end ( raw<Allocator> & _raw ){ typename raw<Allocator>::data_type * temp = _raw.data(); return temp += _raw.size(); } template <typename Allocator> typename raw<Allocator>::data_type const * cbegin ( raw<Allocator> const & _raw ){ return _raw.data(); } template <typename Allocator> typename raw<Allocator>::data_type const * cend ( raw<Allocator> const & _raw ){ typename raw<Allocator>::data_type * temp = _raw.data(); return temp += _raw.size(); } } /* data_pattern */ #endif
#include <bits/stdc++.h> using namespace std; //a medium level question of codechef // question code - CSS2 // simple solution using c++ maps and pairs int main() { int n,ma; cin>>n>>ma; map<pair<int,int>, pair<int,int>> m; map<pair<int,int>,pair<int,int>>::iterator it; for(int j=0;j<n;j++){ int i,a,v,p; pair<int,int> p11; pair<int,int> p22; cin>>i>>a>>v>>p; p11.first=i; p11.second=a; p22.first=v; p22.second=p; if (m.find(p11)!=m.end()){ it=m.find(p11); if((it->second.second)<=p){it->second=p22;} } else{m.insert({p11,p22});} } for(int j=0;j<ma;j++){ int i1,a1; cin>>i1>>a1; pair<int,int> p12; p12.first=i1; p12.second=a1; it=m.find(p12); cout<<(it->second).first<<"\n"; } return 0; }
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxN=1010; const int Mod=10000; const int inf=2147483647; int n,K; int F[maxN][maxN]; int Sum[maxN][maxN]; int main() { scanf("%d%d",&n,&K); F[1][0]=1; Sum[1][1]=1; for (int i=2;i<=K+1;i++) Sum[1][i]=Sum[1][i-1]; for (int i=2;i<=n;i++) { for (int j=0;j<=K;j++) { F[i][j]=(Sum[i-1][j+1]-Sum[i-1][max(j-i+1,0)]+Mod)%Mod;//由于左端点可能是0,再减一会变成负下标,所以整体向上移一位 Sum[i][j+1]=(Sum[i][j]+F[i][j]+Mod)%Mod; } Sum[i][K+1]=(Sum[i][K]+F[i][K]+Mod)%Mod; } printf("%d\n",F[n][K]); return 0; }
/* * \file Path.cpp * */ #include "Path.h" #include "Activity.h" Path::Path (std::vector<Activity *> activities, size_t current_index){ activities_ = activities; current_index_ = current_index; events_.push_back(activities_.front()->source()); for(Activity * act : activities_){ events_.push_back(act->target()); } } Path::Path(std::vector<int> eventIds, repast::SharedContext<MessagingAgent>& context, repast::SharedNetwork<MessagingAgent, Activity, ActivityContent, ActivityContentManager> * EAN){ current_index_ = 0; for(std::vector<int>::iterator it = eventIds.begin();;){ int firstIndex = *it; repast::AgentId id(firstIndex, repast::RepastProcess::instance()->rank(), EVENT); events_.push_back(dynamic_cast<Event*>(context.getAgent(id)));it++; if(it == eventIds.end()){ break; } int secondIndex = *it; try{ activities_.push_back(Activity::act_map_ptr()->at(std::make_pair(firstIndex, secondIndex))); if(Activity::act_map_ptr()->at(std::make_pair(firstIndex, secondIndex))->type() == "\"headway\""){ throw std::runtime_error("Trying to add a headway activity in a passenger path!"); } } catch(std::out_of_range&){ //This can happen if a wait activity is used, that does not exist in the original network. In this case, just create the activity //First get the two events in question Event* sourceEvent = dynamic_cast<Event*>(context.getAgent(repast::AgentId(firstIndex, repast::RepastProcess::instance()->rank(), EVENT))); Event* targetEvent = dynamic_cast<Event*>(context.getAgent(repast::AgentId(secondIndex, repast::RepastProcess::instance()->rank(), EVENT))); //Make a few checks to see if all went fine if(sourceEvent->station() != targetEvent->station() || sourceEvent->time() >= targetEvent->time()){ std::cerr << "Source: " << *sourceEvent << std::endl; std::cerr << "Target: " << *targetEvent << std::endl; throw std::runtime_error("Could not make a connection between this two events!"); } //Now create the new activity and add them to the network and the path Activity* act = new Activity(Activity::maxActivityId()+1, 0, "wait", 0, sourceEvent, targetEvent); boost::shared_ptr<Activity> act_pointer(act); EAN->addEdge(act_pointer); activities_.push_back(act); } } } void Path::addToFront(Activity* act){ activities_.insert(activities_.begin(), act); events_.insert(events_.begin(), act->source()); } void Path::addToEnd(Activity* act){ activities_.push_back(act); events_.push_back(act->target()); } int Path::getArrivalTime() const { return activities_.back()->target()->time(); } int Path::getDepartureTime() const { return activities_.front()->source()->time(); } std::ostream& operator<<(std::ostream& os, const Path& path){ os << "("; for(size_t index = 0; index < path.activities().size(); index++){ os << *(path.activities()[index])<<", "; } os << ", cur_index: " << path.current_index() << ")"; return os; } void Path::setNewPathFromHere(Path & new_path){ //Check if the new path is shorter than the old one, for debugging: /* int old_arrival_time = this->getArrivalTime(); int new_arrival_time = new_path.getArrivalTime(); This case can actually happen, if the passenger has a change that is not possible anymore if(repast::RepastProcess::instance()->rank() == 0){ if(old_arrival_time < new_arrival_time){ throw std::runtime_error("New path is longer than old path!"); } } */ std::vector<Activity*> new_activities = new_path.activities(); //First delete everything from here on. That is, all activities after current index and all events after current index + 1 activities_.erase(std::find(activities_.begin(), activities_.end(), activities_[current_index_])+1, activities_.end()); events_.erase(std::find(events_.begin(), events_.end(), events_[current_index_])+2, events_.end()); for(Activity * activity : new_activities){ this->addToEnd(activity); } }
#include "data/ops/channel.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace vectorbook { } // namespace vectorbook
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- // #include <OpenMS/COMPARISON/SPECTRA/SpectrumAlignment.h> using namespace std; namespace OpenMS { SpectrumAlignment::SpectrumAlignment() : DefaultParamHandler("SpectrumAlignment") { defaults_.setValue("tolerance", 0.3, "Defines the absolute (in Da) or relative (in ppm) tolerance"); defaults_.setValue("is_relative_tolerance", "false", "If true, the 'tolerance' is interpreted as ppm-value"); defaults_.setValidStrings("is_relative_tolerance", {"true","false"}); defaultsToParam_(); } SpectrumAlignment::SpectrumAlignment(const SpectrumAlignment & source) : DefaultParamHandler(source) { } SpectrumAlignment::~SpectrumAlignment() { } SpectrumAlignment & SpectrumAlignment::operator=(const SpectrumAlignment & source) { if (this != &source) { DefaultParamHandler::operator=(source); } return *this; } }
#ifndef insitu_utils_ROS_HPP #define insitu_utils_ROS_HPP #include <vector> #include <string> namespace insitu_utils { void getTopicsByType(std::vector<std::string>& ret, const std::string& type = ""); } #endif /* insitu_utils_ROS_HPP */
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #define JPEG_INTERNALS #include "jinclude.h" #include "mrpt_jpeglib.h" /* Pointer to routine to downsample a single component */ typedef JMETHOD(void, downsample1_ptr, (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data)); /* Private subobject */ typedef struct { struct jpeg_downsampler pub; /* public fields */ /* Downsampling method pointers, one per component */ downsample1_ptr methods[MAX_COMPONENTS]; } my_downsampler; typedef my_downsampler * my_downsample_ptr; /* * Initialize for a downsampling pass. */ METHODDEF(void) start_pass_downsample (j_compress_ptr ) { /* no work for now */ } /* * Expand a component horizontally from width input_cols to width output_cols, * by duplicating the rightmost samples. */ LOCAL(void) expand_right_edge (JSAMPARRAY image_data, int num_rows, JDIMENSION input_cols, JDIMENSION output_cols) { JSAMPROW ptr; JSAMPLE pixval; int count; int row; int numcols = (int) (output_cols - input_cols); if (numcols > 0) { for (row = 0; row < num_rows; row++) { ptr = image_data[row] + input_cols; pixval = ptr[-1]; /* don't need GETJSAMPLE() here */ for (count = numcols; count > 0; count--) *ptr++ = pixval; } } } /* * Do downsampling for a whole row group (all components). * * In this version we simply downsample each component independently. */ METHODDEF(void) sep_downsample (j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION in_row_index, JSAMPIMAGE output_buf, JDIMENSION out_row_group_index) { my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample; int ci; jpeg_component_info * compptr; JSAMPARRAY in_ptr, out_ptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { in_ptr = input_buf[ci] + in_row_index; out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor); (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr); } } /* * Downsample pixel values of a single component. * One row group is processed per call. * This version handles arbitrary integral sampling ratios, without smoothing. * Note that this version is not actually used for customary sampling ratios. */ METHODDEF(void) int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v; JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; JSAMPROW inptr, outptr; INT32 outvalue; h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor; v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor; numpix = h_expand * v_expand; numpix2 = numpix/2; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * h_expand); inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; for (outcol = 0, outcol_h = 0; outcol < output_cols; outcol++, outcol_h += h_expand) { outvalue = 0; for (v = 0; v < v_expand; v++) { inptr = input_data[inrow+v] + outcol_h; for (h = 0; h < h_expand; h++) { outvalue += (INT32) GETJSAMPLE(*inptr++); } } *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix); } inrow += v_expand; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * without smoothing. */ METHODDEF(void) fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { /* Copy the data */ jcopy_sample_rows(input_data, 0, output_data, 0, cinfo->max_v_samp_factor, cinfo->image_width); /* Edge-expand */ expand_right_edge(output_data, cinfo->max_v_samp_factor, cinfo->image_width, compptr->width_in_blocks * DCTSIZE); } /* * Downsample pixel values of a single component. * This version handles the common case of 2:1 horizontal and 1:1 vertical, * without smoothing. * * A note about the "bias" calculations: when rounding fractional values to * integer, we do not want to always round 0.5 up to the next integer. * If we did that, we'd introduce a noticeable bias towards larger values. * Instead, this code is arranged so that 0.5 will be rounded up or down at * alternate pixel locations (a simple ordered dither pattern). */ METHODDEF(void) h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int outrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; JSAMPROW inptr, outptr; int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr = input_data[outrow]; bias = 0; /* bias = 0,1,0,1,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1]) + bias) >> 1); bias ^= 1; /* 0=>1, 1=>0 */ inptr += 2; } } } /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * without smoothing. */ METHODDEF(void) h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION outcol; JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; JSAMPROW inptr0, inptr1, outptr; int bias; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data, cinfo->max_v_samp_factor, cinfo->image_width, output_cols * 2); inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; bias = 1; /* bias = 1,2,1,2,... for successive samples */ for (outcol = 0; outcol < output_cols; outcol++) { *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]) + bias) >> 2); bias ^= 3; /* 1=>2, 2=>1 */ inptr0 += 2; inptr1 += 2; } inrow += 2; } } #ifdef INPUT_SMOOTHING_SUPPORTED /* * Downsample pixel values of a single component. * This version handles the standard case of 2:1 horizontal and 2:1 vertical, * with smoothing. One row of context is required. */ METHODDEF(void) h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int inrow, outrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr; INT32 membersum, neighsum, memberscale, neighscale; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols * 2); /* We don't bother to form the individual "smoothed" input pixel values; * we can directly compute the output which is the average of the four * smoothed values. Each of the four member pixels contributes a fraction * (1-8*SF) to its own smoothed image and a fraction SF to each of the three * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final * output. The four corner-adjacent neighbor pixels contribute a fraction * SF to just one smoothed pixel, or SF/4 to the final output; while the * eight edge-adjacent neighbors contribute SF to each of two smoothed * pixels, or SF/2 overall. In order to use integer arithmetic, these * factors are scaled by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */ neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */ inrow = 0; for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr0 = input_data[inrow]; inptr1 = input_data[inrow+1]; above_ptr = input_data[inrow-1]; below_ptr = input_data[inrow+2]; /* Special case for first column: pretend column -1 is same as column 0 */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]); neighsum += neighsum; neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]); membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; for (colctr = output_cols - 2; colctr > 0; colctr--) { /* sum of pixels directly mapped to this output element */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); /* sum of edge-neighbor pixels */ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]); /* The edge-neighbors count twice as much as corner-neighbors */ neighsum += neighsum; /* Add in the corner-neighbors */ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]); /* form final output scaled up by 2^16 */ membersum = membersum * memberscale + neighsum * neighscale; /* round, descale and output it */ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]); neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) + GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) + GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]); neighsum += neighsum; neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) + GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]); membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); inrow += 2; } } /* * Downsample pixel values of a single component. * This version handles the special case of a full-size component, * with smoothing. One row of context is required. */ METHODDEF(void) fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr, JSAMPARRAY input_data, JSAMPARRAY output_data) { int outrow; JDIMENSION colctr; JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE; JSAMPROW inptr, above_ptr, below_ptr, outptr; INT32 membersum, neighsum, memberscale, neighscale; int colsum, lastcolsum, nextcolsum; /* Expand input data enough to let all the output samples be generated * by the standard loop. Special-casing padded output would be more * efficient. */ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2, cinfo->image_width, output_cols); /* Each of the eight neighbor pixels contributes a fraction SF to the * smoothed pixel, while the main pixel contributes (1-8*SF). In order * to use integer arithmetic, these factors are multiplied by 2^16 = 65536. * Also recall that SF = smoothing_factor / 1024. */ memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */ neighscale = cinfo->smoothing_factor * 64; /* scaled SF */ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) { outptr = output_data[outrow]; inptr = input_data[outrow]; above_ptr = input_data[outrow-1]; below_ptr = input_data[outrow+1]; /* Special case for first column */ colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) + GETJSAMPLE(*inptr); membersum = GETJSAMPLE(*inptr++); nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = colsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; for (colctr = output_cols - 2; colctr > 0; colctr--) { membersum = GETJSAMPLE(*inptr++); above_ptr++; below_ptr++; nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) + GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + nextcolsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16); lastcolsum = colsum; colsum = nextcolsum; } /* Special case for last column */ membersum = GETJSAMPLE(*inptr); neighsum = lastcolsum + (colsum - membersum) + colsum; membersum = membersum * memberscale + neighsum * neighscale; *outptr = (JSAMPLE) ((membersum + 32768) >> 16); } } #endif /* INPUT_SMOOTHING_SUPPORTED */ /* * Module initialization routine for downsampling. * Note that we must select a routine for each component. */ GLOBAL(void) jinit_downsampler (j_compress_ptr cinfo) { my_downsample_ptr downsample; int ci; jpeg_component_info * compptr; boolean smoothok = TRUE; downsample = (my_downsample_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_downsampler)); cinfo->downsample = (struct jpeg_downsampler *) downsample; downsample->pub.start_pass = start_pass_downsample; downsample->pub.downsample = sep_downsample; downsample->pub.need_context_rows = FALSE; if (cinfo->CCIR601_sampling) ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); /* Verify we can handle the sampling factors, and set up method pointers */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor == cinfo->max_h_samp_factor && compptr->v_samp_factor == cinfo->max_v_samp_factor) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = fullsize_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = fullsize_downsample; } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && compptr->v_samp_factor == cinfo->max_v_samp_factor) { smoothok = FALSE; downsample->methods[ci] = h2v1_downsample; } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor && compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) { #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor) { downsample->methods[ci] = h2v2_smooth_downsample; downsample->pub.need_context_rows = TRUE; } else #endif downsample->methods[ci] = h2v2_downsample; } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 && (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) { smoothok = FALSE; downsample->methods[ci] = int_downsample; } else ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); } #ifdef INPUT_SMOOTHING_SUPPORTED if (cinfo->smoothing_factor && !smoothok) TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL); #endif }
/* * Created by Phil on 22/10/2010. * Copyright 2010 Two Blue Cubes Ltd. All rights reserved. * * 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 TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED #include "catch_interfaces_runner.h" #include "catch_interfaces_reporter.h" #include "catch_interfaces_exception.h" #include "catch_config.hpp" #include "catch_test_registry.hpp" #include "catch_test_case_info.h" #include "catch_capture.hpp" #include "catch_totals.hpp" #include "catch_test_spec.hpp" #include "catch_test_case_tracker.hpp" #include "catch_timer.h" #include "catch_result_builder.h" #include "catch_fatal_condition.hpp" #include <set> #include <string> namespace Catch { class StreamRedirect { public: StreamRedirect( std::ostream& stream, std::string& targetString ) : m_stream( stream ), m_prevBuf( stream.rdbuf() ), m_targetString( targetString ) { stream.rdbuf( m_oss.rdbuf() ); } ~StreamRedirect() { m_targetString += m_oss.str(); m_stream.rdbuf( m_prevBuf ); } private: std::ostream& m_stream; std::streambuf* m_prevBuf; std::ostringstream m_oss; std::string& m_targetString; }; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { RunContext( RunContext const& ); void operator =( RunContext const& ); public: explicit RunContext( Ptr<IConfig const> const& _config, Ptr<IStreamingReporter> const& reporter ) : m_runInfo( _config->name() ), m_context( getCurrentMutableContext() ), m_activeTestCase( CATCH_NULL ), m_config( _config ), m_reporter( reporter ) { m_context.setRunner( this ); m_context.setConfig( m_config ); m_context.setResultCapture( this ); m_reporter->testRunStarting( m_runInfo ); } virtual ~RunContext() { m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); } void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); } void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); } Totals runTest( TestCase const& testCase ) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; TestCaseInfo testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting( testInfo ); m_activeTestCase = &testCase; do { ITracker& rootTracker = m_trackerContext.startRun(); assert( rootTracker.isSectionTracker() ); static_cast<SectionTracker&>( rootTracker ).addInitialFilters( m_config->getSectionsToRun() ); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) ); runCurrentTest( redirectedCout, redirectedCerr ); } while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); } // !TBD: deprecated - this will be replaced by indexed trackers while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); Totals deltaTotals = m_totals.delta( prevTotals ); if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { deltaTotals.assertions.failed++; deltaTotals.testCases.passed--; deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting() ) ); m_activeTestCase = CATCH_NULL; m_testCaseTracker = CATCH_NULL; return deltaTotals; } Ptr<IConfig const> config() const { return m_config; } private: // IResultCapture virtual void assertionEnded( AssertionResult const& result ) { if( result.getResultType() == ResultWas::Ok ) { m_totals.assertions.passed++; } else if( !result.isOk() ) { m_totals.assertions.failed++; } if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) m_messages.clear(); // Reset working state m_lastAssertionInfo = AssertionInfo( std::string(), m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); m_lastResult = result; } virtual bool sectionStarted ( SectionInfo const& sectionInfo, Counts& assertions ) { ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) ); if( !sectionTracker.isOpen() ) return false; m_activeSections.push_back( &sectionTracker ); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting( sectionInfo ); assertions = m_totals.assertions; return true; } bool testForMissingAssertions( Counts& assertions ) { if( assertions.total() != 0 ) return false; if( !m_config->warnAboutMissingAssertions() ) return false; if( m_trackerContext.currentTracker().hasChildren() ) return false; m_totals.assertions.failed++; assertions.failed++; return true; } virtual void sectionEnded( SectionEndInfo const& endInfo ) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( !m_activeSections.empty() ) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); m_messages.clear(); } virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { if( m_unfinishedSections.empty() ) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back( endInfo ); } virtual void pushScopedMessage( MessageInfo const& message ) { m_messages.push_back( message ); } virtual void popScopedMessage( MessageInfo const& message ) { m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); } virtual std::string getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string(); } virtual const AssertionResult* getLastResult() const { return &m_lastResult; } virtual void handleFatalErrorCondition( std::string const& message ) { ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); resultBuilder.setResultType( ResultWas::FatalErrorCondition ); resultBuilder << message; resultBuilder.captureExpression(); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); m_reporter->sectionEnded( testCaseSectionStats ); TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, std::string(), std::string(), false ) ); m_totals.testCases.failed++; testGroupEnded( std::string(), m_totals, 1, 1 ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); } public: // !TBD We need to do this another way! bool aborting() const { return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() ); } private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; try { m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, std::string(), ResultDisposition::Normal ); seedRng( *m_config ); Timer timer; timer.start(); if( m_reporter->getPreferences().shouldRedirectStdOut ) { StreamRedirect coutRedir( Catch::cout(), redirectedCout ); StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); invokeActiveTestCase(); } else { invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } catch( TestFailureException& ) { // This just means the test was aborted due to failure } catch(...) { makeUnexpectedResultBuilder().useActiveException(); } m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( testCaseInfo.okToFail() ) { std::swap( assertions.failedButOk, assertions.failed ); m_totals.assertions.failed -= assertions.failedButOk; m_totals.assertions.failedButOk += assertions.failedButOk; } SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } void invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } private: ResultBuilder makeUnexpectedResultBuilder() const { return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), m_lastAssertionInfo.lineInfo, m_lastAssertionInfo.capturedExpression.c_str(), m_lastAssertionInfo.resultDisposition ); } void handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it ) sectionEnded( *it ); m_unfinishedSections.clear(); } TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase; ITracker* m_testCaseTracker; ITracker* m_currentSectionTracker; AssertionResult m_lastResult; Ptr<IConfig const> m_config; Totals m_totals; Ptr<IStreamingReporter> m_reporter; std::vector<MessageInfo> m_messages; AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; }; IResultCapture& getResultCapture() { if( IResultCapture* capture = getCurrentContext().getResultCapture() ) return *capture; else throw std::logic_error( "No result capture instance" ); } } // end namespace Catch #endif // TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
#include "pch.h" #include "PetSkillWindow.h" #include "GameTextControl.h" #include "PetSkillPage.h" #include "GLGaeaClient.h" #include "SkillSlot.h" #include "InnerInterface.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CPetSkillWindow::CPetSkillWindow() : m_pPage( NULL ) { } CPetSkillWindow::~CPetSkillWindow () { } void CPetSkillWindow::CreateSubControl () { SNATIVEID sNativeIDArray[GLSkillMan::MAX_CLASSSKILL]; for ( int i = 0; i < GLSkillMan::MAX_CLASSSKILL; i++ ) { sNativeIDArray[i] = NATIVEID_NULL(); } int nSkillCount(0); for ( int j = 0; j < GLSkillMan::MAX_CLASSSKILL; j++ ) { PGLSKILL pSkill = GLSkillMan::GetInstance().GetData ( EMSKILL_PET, j ); if ( pSkill ) { sNativeIDArray[nSkillCount++] = SNATIVEID(EMSKILL_PET,j); } } CPetSkillPage* pSkillPage = new CPetSkillPage; pSkillPage->CreateSub ( this, "PET_SKILL_PAGE", UI_FLAG_DEFAULT, PET_SKILL_WINDOW_PAGE ); pSkillPage->CreateSubControl ( sNativeIDArray, nSkillCount ); RegisterControl ( pSkillPage ); m_pPage = pSkillPage; } void CPetSkillWindow::TranslateUIMessage ( UIGUID ControlID, DWORD dwMsg ) { CUIWindowEx::TranslateUIMessage ( ControlID, dwMsg ); switch ( ControlID ) { case PET_SKILL_WINDOW_PAGE: { if ( CHECK_MOUSE_IN ( dwMsg ) ) { int nSkillIndex = m_pPage->GetSkillIndex (); if ( nSkillIndex < 0 ) return; SNATIVEID sNativeID = m_pPage->GetSkillID ( nSkillIndex ); if ( sNativeID != NATIVEID_NULL() ) { CInnerInterface::GetInstance().SHOW_SKILL_INFO ( sNativeID, FALSE ); } } } break; } }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include <glob.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #include <sys/ioctl.h> #include <string.h> #include <unistd.h> #include <sys/mman.h> #include <malloc.h> #include <errno.h> #include <pthread.h> #include "dialogs.h" #include "cvcam.h" #include "cvvidtypes.h" #include "videodev.h" #include "icvvideo.h" #include "render.h" //#define DEBUG_CVCAM 1 //#define DEBUG_THREADS 1 #ifdef DEBUG_THREADS #define pthread_mutex_lock(x) printf("locking mutex "#x" from thread %p\n",pthread_self()),pthread_mutex_lock(x) #define pthread_mutex_unlock(x) printf("unlocking mutex "#x" from thread %p\n",pthread_self()),pthread_mutex_unlock(x) #define pthread_rwlock_rdlock(x) printf("rdlocking rwlock "#x" from thread %p\n",pthread_self()),pthread_rwlock_rdlock(x) #define pthread_rwlock_wrlock(x) printf("wrlocking rwlock "#x" from thread %p\n",pthread_self()),pthread_rwlock_wrlock(x) #define pthread_rwlock_unlock(x) printf("unlocking rwlock "#x" from thread %p\n",pthread_self()),pthread_rwlock_unlock(x) #define pthread_create(a,b,c,d) printf("starting new thread from thread %p\n",pthread_self()),pthread_create(a,b,c,d) #endif const int FRAMES_FORMAT=0; const int TIME_FORMAT = 1; CvVideoCamera* cameras = NULL; static int ncameras = 0; static void icvVideoPicture2ImageBuffer(int camera); static IplImage * icvVideoGetImage(int cameraid); /* Returns the actual number of currently available cameras */ int cvcamGetCamerasCount() { glob_t pglob; int count, count1; int CamerasCount = 0; int* descriptors; struct video_capability VidCap; struct video_channel Channel; #ifdef DEBUG_CVCAM printf("cvcamGetCamerasCount(), ncameras=%d\n",ncameras); #endif if(ncameras) return ncameras; if(glob("/dev/video*",GLOB_MARK,NULL, &pglob)) { fprintf(stderr, "cvcamGetCamerasCount:no video devices /dev/video(n)" "found\n"); return 0; } descriptors = (int*)malloc(pglob.gl_pathc*sizeof(int)); for(count = 0; count < pglob.gl_pathc; count++) { descriptors[count] = open(pglob.gl_pathv[count],O_RDWR); if (descriptors[count] != -1 ) { if(ioctl(descriptors[count], VIDIOCGCAP, &VidCap)==-1) { close(descriptors[count]); break; } for(count1=0; count1<VidCap.channels; count1++) { Channel.channel = count1; if((ioctl(descriptors[count], VIDIOCGCHAN, &Channel) != -1)) { Channel.norm = 1; Channel.channel = count1; if((ioctl(descriptors[count],VIDIOCSCHAN, &Channel) != -1)&& (ioctl(descriptors[count], VIDIOCGCAP, &VidCap) != -1)) { if(Channel.type&VIDEO_TYPE_CAMERA) { cameras = (CvVideoCamera*)realloc(cameras, (CamerasCount+1)*sizeof(CvVideoCamera)); if(!icvVideoSetDefaultValues(CamerasCount, descriptors[count], count1, VidCap)) { printf("icvVideoSetDefaultValues failed for camera %d, channel %d\n",count,count1); break; } strcpy(cameras[CamerasCount].description.device, pglob.gl_pathv[count]); strcpy(cameras[CamerasCount].description.DeviceDescription, VidCap.name); strcpy(cameras[CamerasCount].description.ChannelDescription, Channel.name); CamerasCount++; break; }//if(Channel.type&VIDEO_TYPE_CAMERA) }//if((ioctl(descriptors[count],VIDIOCSCHAN, &Channel) != -1)&& //(ioctl(descriptors[count], VIDIOCGCAP, &VidCap)!=-1)) }//if(ioctl(fd, VIDIOCSCHAN, &Channel) != -1) }//for(count1=0; count1<VidCap.channels; count1++) if(count1 == VidCap.channels) // no valid channel found { printf("closing descriptors[%d]=%d\n",count,descriptors[count]); close(descriptors[count]); } }//if (descriptors[count] = open(pglob.gl_pathv[count],O_RDWR) != -1 ) }//for (count = 0; count < pglob.gl_pathc; count++) globfree(&pglob); free(descriptors); ncameras = CamerasCount; XInitThreads(); #ifdef DEBUG_CVCAM printf("cvcamGetCamerasCount() found %d cameras\n",ncameras); #endif return CamerasCount; } /////////////////////////////////////////////////////////////////////////////// /* get/set the property of the camera. returns 0 if the property is not supported */ int cvcamGetProperty(int cameraid, const char* property, void* value) { CvVideoCamera *const camera = &(cameras[cameraid]); #ifdef DEBUG_CVCAM printf("cvcamGetProperty(camera=%d,property=%s)\n",cameraid, property); #endif if(!cameras||cameraid>ncameras-1||cameraid<0) { fprintf(stderr,"cvcamGetProperty:no such camera\n"); return 0; }//if(!cameras||camera>ncameras-1||camera<0) IF_GETTING_PROPERTY("description") { strcpy(((CameraDescription*)value)->DeviceDescription,camera->description.DeviceDescription); strcpy(((CameraDescription*)value)->device, camera->description.device); strcpy(((CameraDescription*)value)->ChannelDescription,camera->description.ChannelDescription); ((CameraDescription*)value)->channel = camera->description.channel; ((CameraDescription*)value)->maxwidth = camera->description.maxwidth; ((CameraDescription*)value)->maxheight = camera->description.maxheight; ((CameraDescription*)value)->minwidth = camera->description.minwidth; ((CameraDescription*)value)->minheight = camera->description.minheight; return 1; }//IF_GETTING_PROPERTY("description") IF_GETTING_PROPERTY("enable") { *(int*)value = camera->enabled; return 1; }//IF_GETTING_PROPERTY("enable") IF_GETTING_PROPERTY("render") { *(int*)value = camera->rendered; //TODO: real call to rendering ioctl(if after initialisation) return 1; }//IF_GETTING_PROPERTY("render") IF_GETTING_PROPERTY("window") { *(Window*)value = camera->window; return 1; }//IF_GETTING_PROPERTY("window") IF_GETTING_PROPERTY("callback") { fprintf(stdout,"The property \"callback\" is set-only\n"); return 0; }//IF_GETTING_PROPERTY("callback") IF_GETTING_PROPERTY("camera_pp") { icvVideoCameraPPDialog(cameraid); return 1; }//IF_GETTING_PROPERTY("camera_pp") IF_GETTING_PROPERTY("set_video_format") { /* if(!camera->initialised) { fprintf(stderr, "cvcamGetProperty, property = video_pp, camera\ isn't initialised"); return 0; } */ ((VideoFormat*)value)->width = camera->videopp.width; ((VideoFormat*)value)->height = camera->videopp.height; ((VideoFormat*)value)->picture.brightness = camera->videopp.picture.brightness; ((VideoFormat*)value)->picture.hue = camera->videopp.picture.hue; ((VideoFormat*)value)->picture.colour = camera->videopp.picture.colour; ((VideoFormat*)value)->picture.contrast = camera->videopp.picture.contrast; ((VideoFormat*)value)->picture.whiteness = camera->videopp.picture.whiteness; ((VideoFormat*)value)->picture.depth = camera->videopp.picture.depth; ((VideoFormat*)value)->picture.palette = camera->videopp.picture.palette; return 1; }//IF_GETTING_PROPERTY("set_video_format") IF_GETTING_PROPERTY("rectify_parameters") { fprintf(stdout,"TODO get prop rectify_parameters\n"); return 1; }//IF_GETTING_PROPERTY("rectify_parameters") IF_GETTING_PROPERTY("stereo_parameters") { fprintf(stdout,"TODO get prop stereo_parameters\n"); return 1; }//IF_GETTING_PROPERTY("stereo_parameters") IF_GETTING_PROPERTY("raw_image") { *((IplImage**)value) = icvVideoGetImage(cameraid); if(*((IplImage**)value) != NULL) return 1; else return 0; }//IF_GETTING_PROPERTY("raw_image") IF_GETTING_PROPERTY("disparity") { fprintf(stdout,"TODO get prop disparity\n"); return 1; }//IF_GETTING_PROPERTY("disparity") IF_GETTING_PROPERTY("stereo_image") { fprintf(stdout,"TODO get prop stereo_image\n"); return 1; }//IF_GETTING_PROPERTY("stereo_image") IF_GETTING_PROPERTY("video_pp") { icvVideoVideoPPDialog(cameraid); return 1; }//IF_GETTING_PROPERTY("video_pp") IF_GETTING_PROPERTY(CVCAM_RNDWIDTH) { *(int*)value = camera->renderwidth; return 1; }//IF_GETTING_PROPERTY (CVCAM_RNDWIDTH) IF_GETTING_PROPERTY(CVCAM_RNDHEIGHT) { *(int*)value = camera->renderheight; return 1; }//IF_GETTING_PROPERTY("CVCAM_RNDHEIGHT") return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////// /* gets all property names. the actual number of properties is returned. */ int cvcamGetPropertiesList(int camera, const char** properties, int count) { #ifdef DEBUG_CVCAM printf("cvcamGetPropertiesList()\n"); #endif assert(properties); properties[0] = "description" ; properties[1] = "enable"; properties[2] = "render"; properties[3] = "window"; properties[4] = "callback"; properties[5] = "camera_pp"; properties[6] = "video_pp" ; properties[7] = "raw_image"; properties[8] = "set_video_format" ; return 9; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// int cvcamSetProperty(int cameraid, const char* property, void* value) { int k; CvVideoCamera *const camera = &(cameras[cameraid]); #ifdef DEBUG_CVCAM printf("cvcamSetProperty(camera=%d,property=%s)\n",cameraid, property); #endif if(!cameras||cameraid>ncameras-1||cameraid<0) { fprintf(stderr,"cvcamSetProperty: no such camera\n"); return 0; }//if(!cameras||camera>ncameras-1) IF_SETTING_PROPERTY("description") { fprintf(stdout, "cvcamSetProperty: The property \"description\" cannot be " "set\n"); return 0; }//IF_SETTING_PROPERTY("description") IF_SETTING_PROPERTY("enable") { camera->enabled = (int)value; return 1; }//IF_SETTING_PROPERTY("enable") IF_SETTING_PROPERTY("render") { camera->rendered = (int)value; return 1; }//IF_SETTING_PROPERTY("render") IF_SETTING_PROPERTY("window") { camera->window = *(Window*)value; //fprintf(stdout,"TODO get prop window\n"); return 1; }//IF_SETTING_PROPERTY("window") IF_SETTING_PROPERTY("callback") { camera->callback = ( void (*)(IplImage*) )value; return 1; }//IF_SETTING_PROPERTY("callback") IF_SETTING_PROPERTY("camera_pp") { fprintf(stdout,"TODO get prop camera_pp\n"); return 1; }//IF_SETTING_PROPERTY("camera_pp") IF_SETTING_PROPERTY("description") { fprintf(stdout,"TODO get prop camera_pp\n"); return 1; }//IF_SETTING_PROPERTY("camera_pp") IF_SETTING_PROPERTY("set_video_format") { k = icvVideoStop(cameraid); if( (((VideoFormat*)value)->picture.brightness>0xffff)|| (((VideoFormat*)value)->picture.hue>0xffff)|| (((VideoFormat*)value)->picture.colour>0xffff)|| (((VideoFormat*)value)->picture.contrast>0xffff)|| (((VideoFormat*)value)->picture.whiteness>0xffff)|| (((VideoFormat*)value)->width > camera->description.maxwidth)|| (((VideoFormat*)value)->height > camera->description.maxheight)|| (((VideoFormat*)value)->width < camera->description.minwidth)|| (((VideoFormat*)value)->height < camera->description.minheight) ) { #ifdef DEBUG_CVCAM printf("cvcamSetProperty(camera=%d,property=%s): values out of bounds\n",cameraid, property); #endif if(k) icvVideoStart(cameraid); return 0; } if( ((((VideoFormat*)value)->width == camera->description.maxwidth)&& (((VideoFormat*)value)->height == camera->description.maxheight))|| ((((VideoFormat*)value)->width == camera->description.minwidth)&& (((VideoFormat*)value)->height == camera->description.minheight))|| ((((VideoFormat*)value)->width == 320)&& (((VideoFormat*)value)->height == 240)) ) { camera->videopp.width = ((VideoFormat*)value)->width; camera->videopp.height= ((VideoFormat*)value)->height; } else { if( ((((VideoFormat*)value)->width > 320)&& ((VideoFormat*)value)->height > 240) ) { camera->videopp.width = 320; camera->videopp.height= 240; }else { camera->videopp.width= camera->description.minwidth; camera->videopp.height= camera->description.minheight; } } camera->videopp.picture.brightness= ((VideoFormat*)value)->picture.brightness; camera->videopp.picture.hue= ((VideoFormat*)value)->picture.hue; camera->videopp.picture.colour= ((VideoFormat*)value)->picture.colour; camera->videopp.picture.contrast= ((VideoFormat*)value)->picture.contrast ; camera->videopp.picture.whiteness= ((VideoFormat*)value)->picture.whiteness; camera->videopp.picture.palette= ((VideoFormat*)value)->picture.palette; if(camera->videopp.picture.palette == VIDEO_PALETTE_YUV420P) camera->imagepalette = VIDEO_PALETTE_RGB24; camera->videopp.picture.depth = icvVideoFormat2Depth(camera->imagepalette); if(!camera->videopp.picture.depth) return 0; //cvcamInit(); if(k) icvVideoStart(cameraid); //fprintf(stdout,"TODO get prop video_pp\n"); return 1; }//IF_SETTING_PROPERTY("set_video_format") IF_SETTING_PROPERTY("rectify_parameters") { fprintf(stdout,"TODO get prop rectify_parameters\n"); return 1; }//IF_SETTING_PROPERTY("rectify_parameters") IF_SETTING_PROPERTY("stereo_parameters") { fprintf(stdout,"TODO get prop stereo_parameters\n"); return 1; }//IF_SETTING_PROPERTY("stereo_parameters") IF_SETTING_PROPERTY("raw_image") { fprintf(stdout,"TODO get prop raw_image\n"); return 1; }//IF_SETTING_PROPERTY("raw_image") IF_SETTING_PROPERTY("disparity") { fprintf(stdout,"TODO get prop disparity\n"); return 1; }//IF_SETTING_PROPERTY("disparity") IF_SETTING_PROPERTY("stereo_image") { fprintf(stdout,"TODO get prop stereo_image\n"); return 1; }//IF_SETTING_PROPERTY("stereo_image") IF_SETTING_PROPERTY("video_pp") { fprintf(stdout,"TODO get prop set_video_format\n"); return 1; }//IF_SETTING_PROPERTY( "video_pp" ) IF_SETTING_PROPERTY(CVCAM_RNDWIDTH) { k=icvVideoStop(cameraid); camera->renderwidth = *(int*)value; if(k) icvVideoStart(cameraid); return 1; }//IF_SETTING_PROPERTY(CVCAM_RNDWIDTH) IF_SETTING_PROPERTY(CVCAM_RNDHEIGHT) { k=icvVideoStop(cameraid); camera->renderheight = *(int*)value; if(k) icvVideoStart(cameraid); return 1; }//IF_SETTING_PROPERTY(CVCAM_RNDHEIGHT) return 0; } /////////////////////////////////////////////////////////////////////////////// /* Prepares the currently enabled cameras for work */ int cvcamInit() { int camera; #ifdef DEBUG_CVCAM printf("cvcamInit()\n"); #endif for(camera=0; camera<ncameras; camera++) { icvVideoInit(camera); }//for(camera=0; camera<ncameras; camera++) return 1; } /////////////////////////////////////////////////////////////////////////////// /* Start the video */ int cvcamStart() { int cameraid; #ifdef DEBUG_CVCAM printf("cvcamStart()\n"); #endif for(cameraid=0; cameraid<ncameras; cameraid++) { if(cameras[cameraid].enabled) { if(!icvVideoStart(cameraid)) { return 0; } } }//for(cameraid=0; cameraid<ncameras; cameraid++) return 1; } int icvVideoStart(int cameraid) { CvVideoCamera *const camera = &(cameras[cameraid]); int frame; pthread_mutex_lock(&(camera->capturestatemutex)); if(camera->capturestate != READY) { fprintf(stderr,"icvVideoStart: camera %d not ready\n",camera); pthread_mutex_unlock(&(camera->capturestatemutex)); return 0; } camera->capturestate = STARTING; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device, VIDIOCGMBUF, &(camera->mbuf)) == -1) { pthread_mutex_unlock(&(camera->ioctlmutex)); return 0; } pthread_mutex_unlock(&(camera->ioctlmutex)); #ifdef DEBUG_CVCAM printf("mbuf: size=%d, frames=%d, offsets=",camera->mbuf.size, camera->mbuf.frames); #endif camera->memorymap = (char*)mmap(0, camera->mbuf.size, PROT_READ|PROT_WRITE, MAP_SHARED, camera->device, 0); if((int)camera->memorymap == -1) { fprintf(stderr, "icvVideoStart: mmap failed"); return 0; } // acquire first frame camera->vid_mmap.frame = 0; camera->vid_mmap.width = camera->videopp.width; camera->vid_mmap.height = camera->videopp.height; camera->vid_mmap.format = camera->videopp.picture.palette; camera->lastframe = 0; pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device, VIDIOCMCAPTURE, &(camera->vid_mmap)) < 0) { fprintf(stderr, "icvVideoInit: ioctl VIDIOCMCAPTURE failed \n"); return 0; } if(ioctl(camera->device, VIDIOCSYNC, &(camera->vid_mmap.frame) ) < 0) { fprintf(stderr, "icvVideoInit: ioctl VIDIOCSYNC failed \n"); return 0; }//if ioctl(..., VIDIOCSYNK, ...) pthread_mutex_unlock(&(camera->ioctlmutex)); assert(camera->videopp.picture.palette); assert(icvVideoFormat2Depth(camera->imagepalette)); pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = CAPTURING; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); // initialize frame locks. pthread_mutex_init(&(camera->lastframemutex), NULL); camera->framelock = (pthread_rwlock_t *)malloc(camera->mbuf.frames * sizeof(pthread_rwlock_t)); for(frame = 0; frame < camera->mbuf.frames; frame++) { pthread_rwlock_init(&(camera->framelock[frame]),NULL); } camera->updated = 1; // start capture thread if(pthread_create((&(camera->thread)),NULL, icvVideoCaptureProc, (void*)cameraid)) { fprintf(stderr, "icvVideoStart: couldn't start thread for " "camera %d\n", camera); return 0; }//if pthread_create ... #ifdef DEBUG_THREADS printf("started icvVideoCaptureProc thread %p from thread %p\n", camera->thread, pthread_self()); #endif if(camera->rendered) { #ifdef DEBUG_CVCAM printf("icvVideoStart: start rendering\n"); #endif icvVideoRenderStart(cameraid); } return 1; } //////////////////////////////////////////////////////////////////////////////// void* icvVideoCaptureProc(void* arg) { int cameraid = (int) arg; CvVideoCamera* const camera = &(cameras[cameraid]); assert(cameras != NULL); assert(cameraid>=0 && cameraid <ncameras); assert(camera->mbuf.frames>0); pthread_mutex_lock(&(camera->capturestatemutex)); while(camera->capturestate == CAPTURING) { pthread_mutex_unlock(&(camera->capturestatemutex)); #ifdef DEBUG_CVCAM printf("*"); fflush(stdout); #endif // I don't need to rdlock lastframe, since I'm the one who writes it //pthread_mutex_lock(&(camera->lastframemutex)); camera->vid_mmap.frame = (camera->lastframe + 1)%camera->mbuf.frames; //pthread_mutex_unlock(&(camera->lastframemutex)); pthread_rwlock_wrlock(&(camera->framelock[camera->vid_mmap.frame])); pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device, VIDIOCMCAPTURE, &(camera->vid_mmap)) < 0) { fprintf(stderr, "icvVideoCaptureProc: ioctl VIDIOCMCAPTURE failed \n"); pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = FINISHED; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); } if(ioctl(camera->device, VIDIOCSYNC, &(camera->vid_mmap.frame) ) < 0) { fprintf(stderr, "icvVideoCaptureProc: ioctl VIDIOCSYNC failed \n"); pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = FINISHED; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); }//if ioctl(..., VIDIOCSYNK, ...) pthread_mutex_unlock(&(camera->ioctlmutex)); pthread_rwlock_unlock(&(camera->framelock[camera->vid_mmap.frame])); pthread_mutex_lock(&(camera->lastframemutex)); camera->lastframe = camera->vid_mmap.frame; pthread_mutex_unlock(&(camera->lastframemutex)); // if the camera is not rendered, call the callback myself if (!camera->rendered && (camera->callback != NULL)) { IplImage *image = icvVideoGetImage(cameraid); if(image != NULL) { camera->callback(image); cvReleaseImage(&image); } else { fprintf(stderr, "icvVideoCaptureProc: icvVideoGetImage() returned NULL\n"); } } // signal that the rendering should be updated, since the image changed if (camera->rendered) { pthread_mutex_lock(&(camera->updatedmutex)); if(camera->updated == 0) { pthread_cond_signal(&(camera->updatedcond)); camera->updated = 1; } pthread_mutex_unlock(&(camera->updatedmutex)); } // stop here if we're paused pthread_mutex_lock(&(camera->pausemutex)); pthread_mutex_unlock(&(camera->pausemutex)); pthread_mutex_lock(&(camera->capturestatemutex)); } pthread_mutex_unlock(&(camera->capturestatemutex)); pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = FINISHED; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); pthread_exit(NULL); } //////////////////////////////////////////////////////////////////////////////// /* Frees all resources */ int cvcamExit() { int cameraid, frame; #ifdef DEBUG_CVCAM printf("cvcamExit(), ncameras = %d\n",ncameras); #endif cvcamStop(); for(cameraid=0; cameraid<ncameras; cameraid++) { CvVideoCamera *const camera = &(cameras[cameraid]); close(camera->device); pthread_mutex_destroy(&(camera->ioctlmutex)); pthread_mutex_destroy(&(camera->pausemutex)); pthread_mutex_destroy(&(camera->capturestatemutex)); pthread_cond_destroy(&(camera->capturestatecond)); for(frame=0; frame< camera->mbuf.frames; frame++) { pthread_rwlock_destroy(&(camera->framelock[frame])); } free(camera->framelock); pthread_mutex_destroy(&(camera->lastframemutex)); pthread_cond_destroy(&(camera->updatedcond)); pthread_mutex_destroy(&(camera->updatedmutex)); camera->initialised = 0; } free(cameras); cameras = NULL; ncameras = 0; return 1; } //////////////////////////////////////////////////////////////////////////////// int icvVideoPauseCamera(int cameraid) { CvVideoCamera *const camera = &(cameras[cameraid]); pthread_mutex_lock(&(camera->capturestatemutex)); if(!(camera->capturestate==CAPTURING)) { pthread_mutex_unlock(&(camera->capturestatemutex)); return 1; } pthread_mutex_unlock(&(camera->capturestatemutex)); // taking this lock will stop grabbing if(!camera->paused) { pthread_mutex_lock(&(camera->pausemutex)); camera->paused = 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// int icvVideoResumeCamera(int cameraid) { CvVideoCamera *const camera = &(cameras[cameraid]); pthread_mutex_lock(&(camera->capturestatemutex)); if(!(camera->capturestate==CAPTURING)) { pthread_mutex_unlock(&(camera->capturestatemutex)); return 1; } pthread_mutex_unlock(&(camera->capturestatemutex)); if(camera->paused) { camera->paused = 0; pthread_mutex_unlock(&(camera->pausemutex)); } return 0; } //////////////////////////////////////////////////////////////////////////////// /* Pause the video; should be used for preventing data changes during frame reading using "frame" and other properties */ int cvcamPause() { int i; #ifdef DEBUG_CVCAM printf("cvcamPause()\n"); #endif for(i=0; i<ncameras; i++) { icvVideoPauseCamera(i); } return 0; } //////////////////////////////////////////////////////////////////////////////// /* Resume the video */ int cvcamResume() { int i; #ifdef DEBUG_CVCAM printf("cvcamResume()\n"); #endif for(i=0; i<ncameras; i++) { icvVideoResumeCamera(i); } return 0; } //////////////////////////////////////////////////////////////////////////////// int icvVideoInit(int cameraid) { struct video_channel Channel; struct video_capability VidCap; CvVideoCamera *const camera = &(cameras[cameraid]); #ifdef DEBUG_CVCAM printf("icvVideoInit(%d)\n",cameraid); #endif char *rgbframe; if(camera->initialised) { /* fprintf(stderr, "icvVideoInit:camera %d is already " "initialized\n",camera);*/ return 0; } if(camera->enabled) { pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device,VIDIOCSPICT, &(camera->videopp.picture) )==-1) { pthread_mutex_unlock(&(camera->ioctlmutex)); fprintf(stdout, "icvVideoInit: ioctl VIDIOCSPICT failed\n"); fprintf(stdout,"camera=%d,brightness=%d,hue=%d,colour=%d,contrast=%d,whiteness=%d,depth=%d,palette=%d\n", camera, camera->videopp.picture.brightness, camera->videopp.picture.hue, camera->videopp.picture.colour, camera->videopp.picture.contrast,camera->videopp.picture.whiteness,camera->videopp.picture.depth,camera->videopp.picture.palette); return 0; } pthread_mutex_unlock(&(camera->ioctlmutex)); Channel.norm = 1; Channel.channel = camera->channel; pthread_mutex_lock(&(camera->ioctlmutex)); if((ioctl(camera->device,VIDIOCSCHAN, &Channel) == -1)|| (ioctl(camera->device, VIDIOCGCAP, &VidCap)==-1)) { fprintf(stderr, "icvVideoInit: ioctl VIDIOCSCHAN or VIDIOCGCAP failed\n"); pthread_mutex_unlock(&(camera->ioctlmutex)); return 0; } pthread_mutex_unlock(&(camera->ioctlmutex)); pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device, VIDIOCGMBUF, &(camera->mbuf)) == -1) { pthread_mutex_unlock(&(camera->ioctlmutex)); fprintf(stdout, "icvVideoInit: ioctl VIDIOCGMBUF failed\n"); return 0; } pthread_mutex_unlock(&(camera->ioctlmutex)); pthread_mutex_lock(&(camera->ioctlmutex)); if(ioctl(camera->device, VIDIOCSCHAN, &Channel)==-1) { fprintf(stderr, "icvVideoInit: couldn't set channel %d", Channel.channel); pthread_mutex_unlock(&(camera->ioctlmutex)); return 0; } pthread_mutex_unlock(&(camera->ioctlmutex)); camera->initialised = 1; pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = READY; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); }//if(camera->IsEnabled) return 1; } //////////////////////////////////////////////////////////// int icvVideoStop(int cameraid) { int i, frame; CvVideoCamera *const camera = &(cameras[cameraid]); #ifdef DEBUG_CVCAM printf("icvVideoStop(%d)\n",cameraid); #endif pthread_mutex_lock(&(camera->capturestatemutex)); if(camera->capturestate != CAPTURING) { #ifdef DEBUG_CVCAM printf("icvVideoStop: not capturing (state=%d), returning 0\n",camera->capturestate); #endif pthread_mutex_unlock(&(camera->capturestatemutex)); return 0; } camera->capturestate = STOPPING; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); if(camera->paused) icvVideoResumeCamera(cameraid); pthread_mutex_lock(&(camera->capturestatemutex)); // wait for the end of capture proc while (camera->capturestate != FINISHED ) { pthread_cond_wait(&(camera->capturestatecond),&(camera->capturestatemutex)); } // wait for the end of rendering while (camera->renderstate) { // the rendering loop may be waiting for an update pthread_mutex_lock(&(camera->updatedmutex)); camera->updated = 1; pthread_cond_signal(&(camera->updatedcond)); pthread_mutex_unlock(&(camera->updatedmutex)); pthread_cond_wait(&(camera->capturestatecond),&(camera->capturestatemutex)); } pthread_mutex_unlock(&(camera->capturestatemutex)); munmap(camera->memorymap, camera->mbuf.size); pthread_mutex_lock(&(camera->capturestatemutex)); camera->capturestate = READY; pthread_cond_signal(&(camera->capturestatecond)); pthread_mutex_unlock(&(camera->capturestatemutex)); #ifdef DEBUG_CVCAM printf("icvVideoStop: returning 1\n",camera->capturestate); #endif return 1; } ////////////////////////////////////////////////////////////////// /* Stop the video */ int cvcamStop() { int camera; #ifdef DEBUG_CVCAM printf("cvcamStop()\n"); #endif for(camera=0; camera<ncameras; camera++) { icvVideoStop(camera); }//for(camera=0; camera<ncameras; camera++) return 1; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// int icvVideoFormat2Depth(int format) { switch (format) { case VIDEO_PALETTE_RGB24: return 24; case VIDEO_PALETTE_RGB32: return 32; case VIDEO_PALETTE_RGB565: return 16; case VIDEO_PALETTE_RGB555: return 16; default: return 0; } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// int icvVideoSetDefaultValues(int cameraid, int device, int channel, struct video_capability VidCap) { CvVideoCamera *const camera = &(cameras[cameraid]); camera->device = device; camera->channel = channel; camera->description.channel = channel; pthread_mutex_init(&(camera->ioctlmutex), NULL); camera->enabled = 0; camera->rendered = 0; camera->initialised = 0; camera->paused = 0; pthread_mutex_init(&(camera->pausemutex), NULL); pthread_mutex_init(&(camera->capturestatemutex), NULL); pthread_cond_init(&(camera->capturestatecond), NULL); camera->capturestate = FINISHED; camera->memorymap = NULL; camera->renderstate = 0; pthread_mutex_init(&(camera->updatedmutex), NULL); pthread_cond_init(&(camera->updatedcond), NULL); camera->updated = 0; camera->videopp.picture.palette = VIDEO_PALETTE_RGB24; camera->imagepalette = VIDEO_PALETTE_RGB24; camera->description.maxwidth = VidCap.maxwidth; camera->description.maxheight = VidCap.maxheight; camera->description.minwidth = VidCap.minwidth; if(camera->description.minwidth<160) camera->description.minwidth = 160; camera->description.minheight = VidCap.minheight; if(camera->description.minheight<120) camera->description.minheight = 120; if(ioctl(device,VIDIOCGPICT, &(camera->videopp.picture) )==-1) return 0; camera->videopp.picture.palette = VIDEO_PALETTE_RGB24; camera->imagepalette = VIDEO_PALETTE_RGB24; camera->videopp.width = camera->description.maxwidth; camera->videopp.height = camera->description.maxheight; camera->videopp.picture.depth = 24; camera->videopp.picture.brightness = 30000; camera->videopp.picture.hue = 30000; camera->videopp.picture.colour = 30000; camera->videopp.picture.contrast = 30000; camera->videopp.picture.whiteness = 30000; camera->callback = NULL; camera->renderwidth = 0; camera->renderheight = 0; if(ioctl(device,VIDIOCSPICT, &(camera->videopp.picture) )==-1) { #ifdef DEBUG_CVCAM fprintf(stdout, "icvSetDefaultValues: ioctl VIDIOCSPICT failed, trying YUV420P format\n"); #endif camera->videopp.picture.palette = VIDEO_PALETTE_YUV420P; if(ioctl(device,VIDIOCSPICT, &(camera->videopp.picture) )==-1) { fprintf(stdout, "icvSetDefaultValues: ioctl VIDIOCSPICT failed even in YUV420P format\n"); #ifdef DEBUG_CVCAM fprintf(stdout,"camera=%d,brightness=%d,hue=%d,colour=%d,contrast=%d,whiteness=%d,depth=%d,palette=%d\n", camera, camera->videopp.picture.brightness, camera->videopp.picture.hue, camera->videopp.picture.colour, camera->videopp.picture.contrast, camera->videopp.picture.whiteness, camera->videopp.picture.depth, camera->videopp.picture.palette); #endif return 0; } } #ifdef DEBUG_CVCAM fprintf(stdout,"OK! camera=%d,brightness=%d,hue=%d,colour=%d,contrast=%d,whiteness=%d,depth=%d,palette=%d\n", camera, camera->videopp.picture.brightness, camera->videopp.picture.hue, camera->videopp.picture.colour, camera->videopp.picture.contrast,camera->videopp.picture.whiteness,camera->videopp.picture.depth,camera->videopp.picture.palette); #endif return 1; } /********************************************************************** * * Color correction functions * **********************************************************************/ /* * Turn a YUV4:2:0 block into an RGB block * * Video4Linux seems to use the blue, green, red channel * order convention-- rgb[0] is blue, rgb[1] is green, rgb[2] is red. * * Color space conversion coefficients taken from the excellent * http://www.inforamp.net/~poynton/ColorFAQ.html * In his terminology, this is a CCIR 601.1 YCbCr -> RGB. * Y values are given for all 4 pixels, but the U (Pb) * and V (Pr) are assumed constant over the 2x2 block. * * To avoid floating point arithmetic, the color conversion * coefficients are scaled into 16.16 fixed-point integers. * They were determined as follows: * * double brightness = 1.0; (0->black; 1->full scale) * double saturation = 1.0; (0->greyscale; 1->full color) * double fixScale = brightness * 256 * 256; * int rvScale = (int)(1.402 * saturation * fixScale); * int guScale = (int)(-0.344136 * saturation * fixScale); * int gvScale = (int)(-0.714136 * saturation * fixScale); * int buScale = (int)(1.772 * saturation * fixScale); * int yScale = (int)(fixScale); */ /* LIMIT: convert a 16.16 fixed-point value to a byte, with clipping. */ #define LIMIT(x) ((x)>0xffffff?0xff: ((x)<=0xffff?0:((x)>>16))) static inline void move_420_block(int yTL, int yTR, int yBL, int yBR, int u, int v, int rowPixels, unsigned char * rgb, int bits) { const int rvScale = 91881; const int guScale = -22553; const int gvScale = -46801; const int buScale = 116129; const int yScale = 65536; int r, g, b; g = guScale * u + gvScale * v; // if (force_rgb) { // r = buScale * u; // b = rvScale * v; // } else { r = rvScale * v; b = buScale * u; // } yTL *= yScale; yTR *= yScale; yBL *= yScale; yBR *= yScale; if (bits == 24) { /* Write out top two pixels */ rgb[0] = LIMIT(b+yTL); rgb[1] = LIMIT(g+yTL); rgb[2] = LIMIT(r+yTL); rgb[3] = LIMIT(b+yTR); rgb[4] = LIMIT(g+yTR); rgb[5] = LIMIT(r+yTR); /* Skip down to next line to write out bottom two pixels */ rgb += 3 * rowPixels; rgb[0] = LIMIT(b+yBL); rgb[1] = LIMIT(g+yBL); rgb[2] = LIMIT(r+yBL); rgb[3] = LIMIT(b+yBR); rgb[4] = LIMIT(g+yBR); rgb[5] = LIMIT(r+yBR); } else if (bits == 16) { /* Write out top two pixels */ rgb[0] = ((LIMIT(b+yTL) >> 3) & 0x1F) | ((LIMIT(g+yTL) << 3) & 0xE0); rgb[1] = ((LIMIT(g+yTL) >> 5) & 0x07) | (LIMIT(r+yTL) & 0xF8); rgb[2] = ((LIMIT(b+yTR) >> 3) & 0x1F) | ((LIMIT(g+yTR) << 3) & 0xE0); rgb[3] = ((LIMIT(g+yTR) >> 5) & 0x07) | (LIMIT(r+yTR) & 0xF8); /* Skip down to next line to write out bottom two pixels */ rgb += 2 * rowPixels; rgb[0] = ((LIMIT(b+yBL) >> 3) & 0x1F) | ((LIMIT(g+yBL) << 3) & 0xE0); rgb[1] = ((LIMIT(g+yBL) >> 5) & 0x07) | (LIMIT(r+yBL) & 0xF8); rgb[2] = ((LIMIT(b+yBR) >> 3) & 0x1F) | ((LIMIT(g+yBR) << 3) & 0xE0); rgb[3] = ((LIMIT(g+yBR) >> 5) & 0x07) | (LIMIT(r+yBR) & 0xF8); } } /* Converts from planar YUV420 to RGB24. */ static void yuv420p_to_rgb(int width, int height, unsigned char *pIn0, unsigned char *pOut0, int bits) { const int numpix = width * height; const int bytes = bits >> 3; int i, j, y00, y01, y10, y11, u, v; unsigned char *pY = pIn0; unsigned char *pU = pY + numpix; unsigned char *pV = pU + numpix / 4; unsigned char *pOut = pOut0; for (j = 0; j <= height - 2; j += 2) { for (i = 0; i <= width - 2; i += 2) { y00 = *pY; y01 = *(pY + 1); y10 = *(pY + width); y11 = *(pY + width + 1); u = (*pU++) - 128; v = (*pV++) - 128; move_420_block(y00, y01, y10, y11, u, v, width, pOut, bits); pY += 2; pOut += 2 * bytes; } pY += width; pOut += width * bytes; } } // allocates a nes iplimage containing the last grabbed image. // Can be called from the main thread or the render thread, via // GetProperty("raw_image"), or from the capturing thread, via // the callback static IplImage * icvVideoGetImage(int cameraid) { CvSize size; CvVideoCamera *const camera = &(cameras[cameraid]); IplImage *image; void *data; int lastframe; int depth = icvVideoFormat2Depth(camera->imagepalette); pthread_mutex_lock(&(camera->capturestatemutex)); if(!(camera->capturestate==CAPTURING)) { pthread_mutex_unlock(&(camera->capturestatemutex)); return NULL; } pthread_mutex_unlock(&(camera->capturestatemutex)); size.width = camera->videopp.width; size.height = camera->videopp.height; assert(camera->videopp.picture.palette); assert(icvVideoFormat2Depth(camera->imagepalette)); image = cvCreateImageHeader(size,IPL_DEPTH_8U,depth/8); pthread_mutex_lock(&(camera->lastframemutex)); lastframe = camera->lastframe; pthread_mutex_unlock(&(camera->lastframemutex)); pthread_rwlock_rdlock(&(camera->framelock[lastframe])); if (camera->imagepalette == camera->videopp.picture.palette) { IplImage *buffer = cvCreateImageHeader(size,IPL_DEPTH_8U,depth/8); cvSetImageData(buffer, (void*)(camera->memorymap+ camera->mbuf.offsets[camera->lastframe]), size.width*(depth/8)); cvCreateImageData(image); cvCopyImage(buffer, image); pthread_rwlock_unlock(&(camera->framelock[lastframe])); cvReleaseImageHeader(&buffer); return image; } // only one conversion is implemented, for now assert(camera->videopp.picture.palette == VIDEO_PALETTE_YUV420P); assert((camera->imagepalette == VIDEO_PALETTE_RGB24) || (camera->imagepalette == VIDEO_PALETTE_RGB565)); data = (void*)cvAlloc(size.width*size.height*(depth/8)); cvSetImageData(image, data, size.width*(depth/8)); yuv420p_to_rgb(camera->videopp.width, camera->videopp.height, (unsigned char*)(camera->memorymap+ camera->mbuf.offsets[camera->lastframe]), (unsigned char*)(data), depth); pthread_rwlock_unlock(&(camera->framelock[lastframe])); return image; } //Stubs for avi files /*Plays a specified avi file into a specified window if file is NULL, file browser is opened. if window is 0, it is created. width and height mean output size's 0 means those of avi file are used. __cdecl (*callback)(IplImage*) would be called on every frame. NULL means no callback*/ CVCAM_API int cvcamPlayAVI(const char* file, void* window, int width, int height, void* callback) { return -1; } /*Advanced API for dealing with AVI files*/ /*Opens a given file or pops up a dialog if file is NULL returns a handle to the file opened for success or -1 for failure*/ CVCAM_API cvcamAVIFILE cvcamAVIOpenFile(char* file) { return (cvcamAVIFILE)-1; } /*The next functions just do what they say and return 0 for success, anything other for failure*/ CVCAM_API int cvcamAVICloseFile(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVISetWindow(cvcamAVIFILE file, void* window) { return -1; } CVCAM_API int cvcamAVISetCallback(cvcamAVIFILE file, void* callback) { return -1; } CVCAM_API int cvcamAVISetSize(cvcamAVIFILE file, int width, int height) { return -1; } CVCAM_API int cvcamAVIRun(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVIStop(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVIPause(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVIResume(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVIWaitCompletion(cvcamAVIFILE file) { return -1; } CVCAM_API int cvcamAVIIsRunning(cvcamAVIFILE file) { return -1; }
#include "inventorydialog.h" #include "ui_inventorydialog.h" InventoryDialog::InventoryDialog(QWidget *parent) : QDialog(parent, Qt::WindowFlags() | Qt::Window), ui(new Ui::InventoryDialog) { ui->setupUi(this); createActions(); } InventoryDialog::~InventoryDialog() { delete ui; } void InventoryDialog::createActions() { actRefreshView = new QAction("Обновить", this); connect(actRefreshView, &QAction::triggered, this, &InventoryDialog::procActRefreshView); actEdit = new QAction("Редктировать", this); connect(actEdit, &QAction::triggered, this, &InventoryDialog::procActEdit); actDelete= new QAction("Удалить", this); connect(actDelete, &QAction::triggered, this, &InventoryDialog::procActDelete); actCategoryAdd = new QAction("Добавить категорию", this); connect(actCategoryAdd, &QAction::triggered, this, &InventoryDialog::procActCategoryAdd); actCategoryEdit = new QAction("Редактировать категорию", this); connect(actCategoryEdit, &QAction::triggered, this, &InventoryDialog::procActCategoryEdit); actCategoryDelete = new QAction("Удалить категорию", this); connect(actCategoryDelete, &QAction::triggered, this, &InventoryDialog::procActCategoryDelete); actGroupAdd = new QAction("Добавить группу", this); connect(actGroupAdd, &QAction::triggered, this, &InventoryDialog::procActGroupAdd); actGroupEdit = new QAction("Редактировать группу", this); connect(actGroupEdit, &QAction::triggered, this, &InventoryDialog::procActGroupEdit); actGroupDelete = new QAction("Удалить группу", this); connect(actGroupDelete, &QAction::triggered, this, &InventoryDialog::procActGroupDelete); actInventoryAdd = new QAction("Добавить номенклатуру", this); connect(actInventoryAdd, &QAction::triggered, this, &InventoryDialog::procActInventoryAdd); actInventoryCopy = new QAction("Скопировать номенклатуру", this); connect(actInventoryCopy, &QAction::triggered, this, &InventoryDialog::procActInventoryCopy); actInventoryEdit = new QAction("Редактировать номеклатуру", this); connect(actInventoryEdit, &QAction::triggered, this, &InventoryDialog::procActInventoryEdit); actInventoryDelete = new QAction("Удалить номенклатуру", this); connect(actInventoryDelete, &QAction::triggered, this, &InventoryDialog::procActInventoryDelete); actRegisterStock = new QAction("Удалить номенклатуру", this); connect(actRegisterStock, &QAction::triggered, this, &InventoryDialog::procActRegisterStock); } void InventoryDialog::initDialog() { m_inventoryModel = new InventoryModel(this); m_inventoryModel->setDatabaseManager(m_dbman); m_inventoryModel->setDictModel(m_dictModel); m_inventoryModel->initModel(); m_searchProxyModel = new RecursiveFilterProxyModel(this); m_searchProxyModel->setSourceModel(m_inventoryModel); m_searchProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_searchProxyModel->setFilterWildcard(""); m_searchProxyModel->setFilterRole(Constants::RoleSearchString); ui->treeInventory->setModel(m_searchProxyModel); ui->treeInventory->setSelectionMode(QAbstractItemView::SingleSelection); ui->treeInventory->setSelectionBehavior(QAbstractItemView::SelectRows); ui->treeInventory->setUniformRowHeights(false); // ui->treeInventory->setAlternatingRowColors(true); ui->treeInventory->setItemDelegate(new DelegateHighligtableTreeText(ui->treeInventory)); ui->treeInventory->header()->setStretchLastSection(true); ui->treeInventory->hideColumn(1); // hide "code" column showMaximized(); actRefreshView->trigger(); } void InventoryDialog::procActRefreshView() { qint32 trwidth = ui->treeInventory->frameGeometry().width()-30; if (trwidth < 200) { trwidth = ui->grpInventory->frameGeometry().width()-50; } ui->treeInventory->hide(); ui->treeInventory->setColumnWidth(0, trwidth*0.15); // ui->treeInventory->setColumnWidth(1, trwidth*0.05); // -5, hidden code column ui->treeInventory->setColumnWidth(2, trwidth*0.55); ui->treeInventory->setColumnWidth(3, trwidth*0.05); ui->treeInventory->setColumnWidth(4, trwidth*0.10); // +5 ui->treeInventory->setColumnWidth(5, trwidth*0.15); ui->treeInventory->show(); } void InventoryDialog::procActEdit() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); switch (index.data(Constants::RoleNodeType).toInt()) { case Constants::ItemCategory: actCategoryEdit->trigger(); break; case Constants::ItemGroup: actGroupEdit->trigger(); break; case Constants::ItemItem: actInventoryEdit->trigger(); break; case Constants::ItemClass: default: break; } } void InventoryDialog::procActDelete() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); switch (index.data(Constants::RoleNodeType).toInt()) { case Constants::ItemCategory: actCategoryDelete->trigger(); break; case Constants::ItemGroup: actGroupDelete->trigger(); break; case Constants::ItemItem: actInventoryDelete->trigger(); break; case Constants::ItemClass: default: break; } } void InventoryDialog::procActCategoryAdd() { QModelIndexList path; getPathToRoot(ui->treeInventory->selectionModel()->selectedIndexes().first(), path); QModelIndex parentIndex = m_searchProxyModel->mapToSource(path.last()); bool ok; QString newName = QInputDialog::getText(this, "Добавить категорию", "Введите название:", QLineEdit::Normal, QString(), &ok); if (ok & !newName.isEmpty()) { newName.replace(0, 1, newName.at(0).toUpper()); QModelIndex index = m_inventoryModel->addCategory(parentIndex, newName); m_dictModel->updateCategoryList(); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(m_searchProxyModel->mapFromSource(index), QItemSelectionModel::Select | QItemSelectionModel::Rows); treeUpdated = true; } } void InventoryDialog::procActCategoryEdit() { QModelIndex index = m_searchProxyModel->mapToSource(ui->treeInventory->selectionModel()->selectedIndexes(). first()); bool ok; QString oldName = index.data(Qt::DisplayRole).toString(); QString newName = QInputDialog::getText(this, "Изменить категорию", "Введите новое название", QLineEdit::Normal, oldName, &ok); if (ok && !oldName.isEmpty() && oldName != newName) { newName.replace(0, 1, newName.at(0).toUpper()); m_inventoryModel->editCategory(index, newName); m_dictModel->updateCategoryList(); treeUpdated = true; } } void InventoryDialog::procActCategoryDelete() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); QModelIndex sourceIndex = m_searchProxyModel->mapToSource(index); if (index.data(Constants::RoleNodeHasChildren).toBool()) { QMessageBox::warning(this, "Ошибка!", "Нельзя удалить непустую категорию. " "Сначала удалите все группы."); return; } qint32 res = QMessageBox::question(this, "Внимание!", "Вы действительно хотите удалить выбранную категорию?", QMessageBox::Yes, QMessageBox::No | QMessageBox::Default); if (res == QMessageBox::Yes) { m_inventoryModel->deleteCategory(sourceIndex); m_dictModel->updateCategoryList(); treeUpdated = true; } } void InventoryDialog::procActGroupAdd() { QModelIndexList path; getPathToRoot(ui->treeInventory->selectionModel()->selectedIndexes().first(), path); QModelIndex parentIndex = m_searchProxyModel->mapToSource(path.end()[-1-1]); bool ok; QString newName = QInputDialog::getText(this, "Добавить группу", "Введите название:", QLineEdit::Normal, QString(), &ok); if (ok & !newName.isEmpty()) { newName.replace(0, 1, newName.at(0).toUpper()); QModelIndex index = m_inventoryModel->addGroup(parentIndex, newName); m_dictModel->updateGroupList(); m_dictModel->updateMapGroupToCategory(); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(m_searchProxyModel->mapFromSource(index), QItemSelectionModel::Select | QItemSelectionModel::Rows); treeUpdated = true; } } void InventoryDialog::procActGroupEdit() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); bool ok; QString oldName = index.data(Qt::DisplayRole).toString(); QString newName = QInputDialog::getText(this, "Изменить группу", "Введите новое название", QLineEdit::Normal, oldName, &ok); if (ok && !oldName.isEmpty() && oldName != newName) { newName.replace(0, 1, newName.at(0).toUpper()); m_inventoryModel->editGroup(m_searchProxyModel->mapToSource(index), newName); m_dictModel->updateGroupList(); // m_dictModel->updateMapGroupToCategory(); treeUpdated = true; } } void InventoryDialog::procActGroupDelete() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); if (index.data(Constants::RoleNodeHasChildren).toBool()) { QMessageBox::warning(this, "Ошибка!", "Нельзя удалить непустую группу. " "Сначала удалите всю номенклатуру."); return; } qint32 res = QMessageBox::question(this, "Внимание!", "Вы действительно хотите удалить выбранную группу?", QMessageBox::Yes, QMessageBox::No | QMessageBox::Default); if (res == QMessageBox::Yes) { m_inventoryModel->deleteGroup(m_searchProxyModel->mapToSource(index)); m_dictModel->updateGroupList(); m_dictModel->updateMapGroupToCategory(); treeUpdated = true; } } void InventoryDialog::procActInventoryAdd() { // TODO: merge with copy method QModelIndexList path; if (ui->treeInventory->selectionModel()->hasSelection()) { getPathToRoot(ui->treeInventory->selectionModel()->selectedIndexes().first(), path); } // qDebug() << "path: " << path.size(); InventoryDataDialog::DialogData dummyData; if (path.size() > 2) { dummyData = InventoryDataDialog::DialogData(ProductItem::ProductItemBuilder().build(), ProductRelation::ProductRelationBuilder() .setClass (path.end()[-1-0].data(Constants::RoleNodeId).toInt()) .setCategory(path.end()[-1-1].data(Constants::RoleNodeId).toInt()) .setGroup (path.end()[-1-2].data(Constants::RoleNodeId).toInt()) .build()); // TODO: extract to a method } else { dummyData = InventoryDataDialog::DialogData(ProductItem::ProductItemBuilder().build(), ProductRelation::ProductRelationBuilder() .build()); // TODO: extract to a method } InventoryDataDialog dialog(this); dialog.setDictModel(m_dictModel) .setData(dummyData) .initDialog(); if (dialog.exec() != QDialog::Accepted) { return; } InventoryDataDialog::DialogData recievedData = dialog.getData(); QModelIndex parentIndex = m_inventoryModel->getParentIndexByRelation(recievedData.relation); QModelIndex index = m_inventoryModel->addInventory(parentIndex, recievedData.relation, recievedData.item); m_dictModel->updateProductList(); QModelIndex indexToSelect = m_searchProxyModel->mapFromSource(index); QModelIndexList ePath; getPathToRoot(indexToSelect, ePath); expandTreePath(ePath); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(m_searchProxyModel->mapFromSource(index), QItemSelectionModel::Select | QItemSelectionModel::Rows); treeUpdated = true; } void InventoryDialog::procActInventoryCopy() { QModelIndex proxyIndex = ui->treeInventory->selectionModel()->selectedIndexes().first(); QModelIndex sourceIndex = m_searchProxyModel->mapToSource(proxyIndex); QModelIndex parentIndex = sourceIndex.parent(); QModelIndexList path; getPathToRoot(sourceIndex, path); ProductItem copyProduct = m_inventoryModel->getProductItemByIndex(sourceIndex); copyProduct.itemId = 0; InventoryDataDialog::DialogData dummyData(copyProduct, ProductRelation::ProductRelationBuilder() .setClass (path.end()[-1-0].data(Constants::RoleNodeId).toInt()) .setCategory(path.end()[-1-1].data(Constants::RoleNodeId).toInt()) .setGroup (path.end()[-1-2].data(Constants::RoleNodeId).toInt()) .build()); InventoryDataDialog dialog(this); dialog.setDictModel(m_dictModel) .setData(dummyData) .initDialog(); if (dialog.exec() != QDialog::Accepted) { return; } InventoryDataDialog::DialogData recievedData(dialog.getData()); QModelIndex index = m_inventoryModel->addInventory(parentIndex, recievedData.relation, recievedData.item); m_dictModel->updateProductList(); QModelIndex indexToSelect = m_searchProxyModel->mapFromSource(index); QModelIndexList ePath; getPathToRoot(indexToSelect, ePath); expandTreePath(ePath); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(m_searchProxyModel->mapFromSource(index), QItemSelectionModel::Select | QItemSelectionModel::Rows); treeUpdated = true; } void InventoryDialog::procActInventoryEdit() { QModelIndex proxyIndex = ui->treeInventory->selectionModel()->selectedIndexes().first(); QModelIndex sourceIndex = m_searchProxyModel->mapToSource(proxyIndex); // QModelIndex parentIndex = sourceIndex.parent(); QModelIndexList path; getPathToRoot(sourceIndex, path); ProductItem editProduct = m_inventoryModel->getProductItemByIndex(sourceIndex); InventoryDataDialog::DialogData editData(editProduct, ProductRelation::ProductRelationBuilder() .setClass (path.end()[-1-0].data(Constants::RoleNodeId).toInt()) .setCategory(path.end()[-1-1].data(Constants::RoleNodeId).toInt()) .setGroup (path.end()[-1-2].data(Constants::RoleNodeId).toInt()) .build()); InventoryDataDialog dialog(this); dialog.setDictModel(m_dictModel) .setData(editData) .initDialog(); if (dialog.exec() != QDialog::Accepted) { return; } InventoryDataDialog::DialogData recievedData(dialog.getData()); QModelIndex index = m_inventoryModel->editInventory(sourceIndex, recievedData.relation, recievedData.item); m_dictModel->updateProductList(); // TODO: extract to selectNode method QModelIndex indexToSelect = m_searchProxyModel->mapFromSource(index); QModelIndexList ePath; getPathToRoot(indexToSelect, ePath); expandTreePath(ePath); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(m_searchProxyModel->mapFromSource(index), QItemSelectionModel::Select | QItemSelectionModel::Rows); treeUpdated = true; } void InventoryDialog::procActInventoryDelete() { QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); qint32 res = QMessageBox::question(this, "Внимание!", "Вы действительно хотите удалить выбранную номенклатуру?", QMessageBox::Yes, QMessageBox::No | QMessageBox::Default); if (res == QMessageBox::Yes) { m_inventoryModel->deleteInventory(m_searchProxyModel->mapToSource(index)); m_dictModel->updateProductList(); treeUpdated = true; } } void InventoryDialog::procActRegisterStock() { // FIXME: ХАК: работает в обход модели, переписать на работу со стокмоделью QModelIndex proxyIndex = ui->treeInventory->selectionModel()->selectedIndexes().first(); QModelIndex sourceIndex = m_searchProxyModel->mapToSource(proxyIndex); StockItem newStockItem = StockItem::StockItemBuilder() .setName(sourceIndex.sibling(sourceIndex.row(), 2).data(Qt::DisplayRole).toString()) .setProduct(sourceIndex.data(Constants::RoleNodeId).toInt()) .build(); StockDataDialog dialog(this); dialog.setData(newStockItem) .setDictModel(m_dictModel) .setDbManager(m_dbman) .initDialog(); if (dialog.exec() != QDialog::Accepted) { return; } newStockItem = dialog.getData(); if (newStockItem.itemAmount < 0) newStockItem.itemAmount = 0; // TODO: check stock for dupes qint32 newStockId = m_dbman->insertStock(newStockItem); if (newStockItem.itemAmount > 0) { TransactItem newTransact(TransactItem::TransactItemBuilder() .setDate(QDate::currentDate()) .setDiff(newStockItem.itemAmount) .setNote(QString("Поступление")) .setStock(newStockId) .setStaff(22) // TODO: FIX: add default staff .setProject(newStockItem.itemProject) .build()); m_dbman->insertTransact(newTransact); } treeUpdated = true; QMessageBox::information(this, "Информация", "Позиция успешно зарегистрирована на складе."); } void InventoryDialog::resizeEvent(QResizeEvent *event) { Q_UNUSED(event); actRefreshView->trigger(); } void InventoryDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; case QEvent::Resize: // actRefreshView->trigger(); // break; default: break; } } void InventoryDialog::on_btnAddCategory_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection()) { QMessageBox::warning(this, "Ошибка!", "Выберите раздел для добавления категории."); return; } actCategoryAdd->trigger(); } void InventoryDialog::on_btnAddGroup_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection()) { QMessageBox::warning(this, "Ошибка!", "Выберите категорию для добавления группы."); return; } QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); if (index.data(Constants::RoleNodeType).toInt() == Constants::ItemClass) { QMessageBox::warning(this, "Ошибка!", "Выберите категорию для добавления группы."); return; } actGroupAdd->trigger(); } void InventoryDialog::on_btnAddInventory_clicked() { // if (!ui->treeInventory->selectionModel()->hasSelection()) { // QMessageBox::warning(this, // "Ошибка!", // "Выберите группу для добавления номенклатуры."); // return; // } // QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); // if ((index.data(Constants::RoleNodeType).toInt() == Constants::ItemClass) || // (index.data(Constants::RoleNodeType).toInt() == Constants::ItemCategory)) { // QMessageBox::warning(this, // "Ошибка!", // "Выберите группу для добавления номенклатуры."); // return; // } actInventoryAdd->trigger(); } void InventoryDialog::on_btnCopy_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection() || (ui->treeInventory->selectionModel()->selectedIndexes().first().data(Constants::RoleNodeType).toInt() != Constants::ItemItem)) { QMessageBox::warning(this, "Ошибка!", "Выберите номенклатуру для создания копии."); return; } actInventoryCopy->trigger(); } void InventoryDialog::on_btnEdit_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection()) { QMessageBox::warning(this, "Ошибка!", "Выберите запись для редактирования."); return; } QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); if (index.data(Constants::RoleNodeType).toInt() == Constants::ItemClass) { QMessageBox::warning(this, "Ошибка!", "Нельзя редактировать раздел."); return; } actEdit->trigger(); } void InventoryDialog::on_btnDelete_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection()) { QMessageBox::warning(this, "Ошибка!", "Выберите запись для удаления."); return; } QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); if (index.data(Constants::RoleNodeType).toInt() == Constants::ItemClass) { QMessageBox::warning(this, "Ошибка!", "Нельзя удалить раздел."); return; } actDelete->trigger(); } void InventoryDialog::on_btnRegisterStock_clicked() { if (!ui->treeInventory->selectionModel()->hasSelection()) { QMessageBox::warning(this, "Ошибка!", "Выберите номенклатуру для регистрации на складе."); return; } QModelIndex index = ui->treeInventory->selectionModel()->selectedIndexes().first(); if (index.data(Constants::RoleNodeType) != Constants::ItemItem) { QMessageBox::warning(this, "Ошибка!", "Выберите номенклатуру для регистрации на складе."); return; } actRegisterStock->trigger(); } void InventoryDialog::on_treeInventory_doubleClicked(const QModelIndex &index) { if (index.data(Constants::RoleNodeType) == Constants::ItemItem) { actInventoryEdit->trigger(); } // qDebug() << m_inventoryModel->getInventoryItemByIndex(m_searchProxyModel->mapToSource(index)); } void InventoryDialog::on_editSearch_textChanged(const QString &arg1) { if (arg1.size() == 0) ui->treeInventory->collapseAll(); m_searchProxyModel->setFilterWildcard(arg1); if (arg1.size() > 2) ui->treeInventory->expandAll(); } // ------------------------- utility routines ----------------- void InventoryDialog::getPathToRoot(const QModelIndex &node, QModelIndexList &path) { // TODO: exstract to separate TreeHelper class if (!node.isValid()) return; path.append(node); getPathToRoot(node.parent(), path); } void InventoryDialog::expandTreePath(const QModelIndexList &path) { for (auto it = path.rbegin(); it != path.rend(); ++it) { ui->treeInventory->expand(*it); } } // ------------------------- Testing routines ---------------- void InventoryDialog::testAddCat() { // for (int i=0; i<10; ++i) { // QString id = Utility::rndString(12); // id.replace(0, 1, id.at(0).toUpper()); // QModelIndex ind = m_inventoryModel->addCategory(id); // ui->treeInventory->selectionModel()->clear(); // ui->treeInventory->selectionModel()->setCurrentIndex(ind, QItemSelectionModel::Select | QItemSelectionModel::Rows); // } } void InventoryDialog::testRemCat() { qint32 count = m_inventoryModel->rowCount(QModelIndex()); for (qint32 i=0; i<count; ++i) { QModelIndex ind = m_inventoryModel->index(i, 0); if (!ind.data(Constants::RoleNodeHasChildren).toBool()) { m_inventoryModel->deleteCategory(ind); --i; --count; } } } void InventoryDialog::testAddGrp() { QModelIndex catind = ui->treeInventory->selectionModel()->selectedIndexes().first(); for (int i=0; i<10; ++i) { QString id = Utility::rndString(12); id.replace(0, 1, id.at(0).toUpper()); QModelIndex ind = m_inventoryModel->addGroup(catind, id); ui->treeInventory->selectionModel()->clear(); ui->treeInventory->selectionModel()->setCurrentIndex(ind, QItemSelectionModel::Select | QItemSelectionModel::Rows); // qDebug() << id; } } void InventoryDialog::testRemGrp() { QModelIndex catind = ui->treeInventory->selectionModel()->selectedIndexes().first(); qint32 count = m_inventoryModel->rowCount(catind); for (qint32 i=0; i<count; ++i) { QModelIndex ind = m_inventoryModel->index(i, 0, catind); if (!ind.data(Constants::RoleNodeHasChildren).toBool()) { m_inventoryModel->deleteGroup(ind); --i; --count; } } } QString Utility::rndString(qint32 len) { static const QString charset = "0123456789" // "АБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧшщЪЫЬЭЮЯ" "абвгдеёжзиклмнопрстуфхцчшщъыьэюя"; QString out; while (len>0) { qint32 chr = qrand() % (charset.size() - 1); out.append(charset.at(chr)); --len; } return out; }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #ifndef LIBND4J_CONVOLUTIONTESTS1_H #define LIBND4J_CONVOLUTIONTESTS1_H #include "testlayers.h" #include <NDArray.h> #include <Context.h> #include <Node.h> #include <graph/Variable.h> #include <graph/VariableSpace.h> #include <ops/declarable/CustomOperations.h> #include <ops/declarable/helpers/convolutions.h> #include <ops/declarable/helpers/col2im.h> #include <PointersManager.h> using namespace nd4j; using namespace nd4j::graph; class ConvolutionTests1 : public testing::Test { public: }; template <typename T> class TypedConvolutionTests1 : public testing::Test { public: }; typedef ::testing::Types<double, float> TestingTypes; TYPED_TEST_CASE(TypedConvolutionTests1, TestingTypes); TYPED_TEST(TypedConvolutionTests1, TestConv2D_1) { int bS=1, iH=5,iW=4, iC=2,oC=3, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; TypeParam _expB[]{664.0, 700.0, 736.0, 344.0, 808.0, 844.0, 880.0, 408.0, 952.0, 988.0, 1024.0, 472.0, 1096.0, 1132.0, 1168.0, 536.0, 466.0, 480.0, 494.0, 220.0, 1528.0, 1628.0, 1728.0, 856.0, 1928.0, 2028.0, 2128.0, 1048.0, 2328.0, 2428.0, 2528.0, 1240.0, 2728.0, 2828.0, 2928.0, 1432.0, 1346.0, 1392.0, 1438.0, 700.0, 2392.0, 2556.0, 2720.0, 1368.0, 3048.0, 3212.0, 3376.0, 1688.0, 3704.0, 3868.0, 4032.0, 2008.0, 4360.0, 4524.0, 4688.0, 2328.0, 2226.0, 2304.0, 2382.0, 1180.0}; Nd4jLong _expS[]{4, 1, 3, 5, 4, 60, 20, 4, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; auto input = NDArrayFactory::create_<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create_<TypeParam>('c', {oC, iC, kH, kW}); for (int e = 0; e < input->lengthOf(); e++) input->p(e, e + 1); for (int e = 0; e < weights->lengthOf(); e++) weights->p(e, e + 1); weights->permutei({2,3,1,0}); // weights->printShapeInfo("weights"); ArrayOptions::setDataType(_expS, input->dataType()); auto exp = new NDArray(_expB, _expS); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); // not-in-place block->fillInputs({-1, -2}); // 5,5 kernel block->getIArguments()->push_back(kH); block->getIArguments()->push_back(kW); // 1,1 stride block->getIArguments()->push_back(sH); block->getIArguments()->push_back(sW); // 0,0 padding block->getIArguments()->push_back(pH); block->getIArguments()->push_back(pW); // 1,1 dilation block->getIArguments()->push_back(dH); block->getIArguments()->push_back(dW); // same mode block->getIArguments()->push_back(1); // is NHWC block->getIArguments()->push_back(0); nd4j::ops::conv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto res = variableSpace->getVariable(1)->getNDArray(); // checking output shape ASSERT_EQ(1, res->sizeAt(0)); ASSERT_EQ(3, res->sizeAt(1)); ASSERT_EQ(5, res->sizeAt(2)); ASSERT_EQ(4, res->sizeAt(3)); // basically the same as above ASSERT_TRUE(res->isSameShape(exp)); // just for visual validation // exp->printIndexedBuffer("Expected"); // res->printIndexedBuffer("Actual "); // res->printShapeInfo("Result shape"); // final check ASSERT_TRUE(res->equalsTo(exp)); delete block; delete variableSpace; delete exp; } TYPED_TEST(TypedConvolutionTests1, TestAvgFF_TF) { auto input = NDArrayFactory::create<TypeParam>('c', {4, 10, 10, 3}, {9.37125111, 2.20166993, 2.91434479, 5.43639755, -2.10573769, 4.08528662, 5.86908436, -4.46203756, 2.21057916, 5.35849190, 0.01394637, 4.40566349, 7.07982206, -0.09633455, 2.42429352, 3.97301817, -1.89553940, 1.99690318, 6.33141708, 0.55401880, 1.70707977, 5.55204201, -0.03513752, 1.60011971, 2.62700319, -2.74582434, 3.06697464, 1.06277943, -1.16075921, -0.78095782, 9.72352791, -1.22686064, 1.99644792, 7.35571337, 1.40607321, 0.11390255, 9.53334427, 2.28303599, -1.66728830, 6.16678810, -0.04532295, -1.97708666, 9.74906158, 1.46223176, -1.46734393, 4.30761862, -1.23790228, 1.24823606, 6.13938427, -3.83689475, -1.19625473, 7.91535568, 6.05868721, -3.22946382, 8.81633949, -0.19967777, 0.66053957, 2.30919123, 0.74543846, -0.39347672, 11.11058044, 0.53720862, 1.52645731, 5.70012379, -1.15213466, 1.16451406, 7.00526333, 1.57362783, -2.44384766, 5.54213285, -1.98828590, -0.70483637, 7.88281822, -3.59875536, 0.80745387, 13.41578484, -1.55507684, -0.65855008, 9.32583523, -0.14544789, 0.73436141, 3.61176538, -1.71268058, -2.58490300, 9.09280205, -3.27405524, -2.04569697, 4.44761324, -0.62955856, -2.61917663, 8.04890442, 0.54579324, 0.85929775, 9.82259560, -1.93825579, 0.77703512, 4.67090321, -4.79267597, -2.38906908, 9.31265545, 0.96026313, -1.14109385, 11.54231834, -0.01417295, -0.39500344, 8.49191666, 0.55300158, 2.79490185, 6.92466164, 1.72254205, 2.82222271, 8.83112717, 2.95033407, 2.18054962, 6.73509789, -2.22272944, 0.51127720, -1.04563558, 2.15747333, -2.30959272, 9.55441570, 1.50396204, 1.77370787, 7.38146257, -1.79076433, 3.20961165, 7.18864202, 2.91217351, 0.43018937, 7.11078024, -1.17386127, -0.16817921, 6.12327290, -2.82205725, 3.30696845, 13.51291752, -1.30856836, -2.38332748, 11.09487438, -1.47190213, -0.53050828, 4.38285351, -5.07309771, 1.50714362, 5.72274446, -2.85825086, -0.89673209, 3.73791552, -0.67708802, -4.13149452, -0.00671843, -0.26566532, 0.32961160, 7.14501762, -1.41608179, -4.96590328, 12.26205540, -0.65158135, -0.88641000, 6.95777559, -0.79058206, -0.10260171, 7.87169170, 1.35921454, 1.11759663, 5.46187401, -2.57214499, 2.48484039, 4.04043484, -2.07137156, -1.42709637, 9.25487137, -0.12605135, -2.66949964, 2.89412403, 0.74451172, -2.96250391, 3.99258423, 0.27084303, 0.32213116, 5.42332172, -0.44414216, 1.70881832, 6.69346905, 0.53058422, -4.73146200, 4.22051668, 2.24834967, 0.66996074, 4.30173683, 0.11849818, -4.07520294, 8.27318478, -2.54398274, -2.86705542, 10.11775303, -0.99382895, 0.65881538, 7.93556786, -1.27934420, -1.69343162, 9.68042564, -1.02609646, -1.18189347, 5.75370646, -1.67888868, -4.48871994, 4.79537392, -0.79212248, -0.19855022, 6.15060997, -0.01081491, 3.64454579, 10.82562447, 1.58859253, -2.65847278, 8.60093212, -1.59196103, 0.07635692, 11.76175690, -1.17453325, 0.10122013, 6.86458445, -2.18891335, -2.74004745, 8.07066154, 0.71818852, -2.03035975, 6.31053686, 0.51509416, 1.39789927, 9.43515587, 2.04256630, 0.13985133, 4.65010691, 2.40911126, -0.36255789, -3.06867862, -0.45225358, -1.56778407, 6.05917358, -1.09891272, 1.77184200, 6.46248102, 0.96042323, -0.24346280, 4.63436460, -4.69907761, 1.25187206, 11.46173859, -2.21917558, 1.28007793, 6.92173195, 2.11268163, -3.47389889, 5.08722782, -3.03950930, -4.17154264, 11.30568314, 0.80361372, 2.53214502, 7.18707085, -4.49114513, 2.85449266, 10.14906883, -0.31974933, -0.84472644, -0.52459574, 0.12921631, -1.81390119, 2.76170087, 1.03982210, 2.91744232, -0.29048753, 5.87453508, -1.53684759, 1.85800636, -0.91404629, 1.28954852, 5.11354685, -2.47475505, -1.33179152, 2.58552408, 1.37316465, -3.32339454, 1.54122913, 3.24953628, -0.29758382, 2.82391763, -1.51142192, -1.22699404, 6.75745535, 0.65452754, -3.29385471, 2.06008053, 2.53172946, -4.23532820, -1.53909743, -0.07010663, -1.42173731, 7.29031610, -0.18448229, 4.59496164, 6.73027277, 0.73441899, 0.14426160, 4.14915276, -2.97010231, 6.05851364, 4.95218086, -2.39145470, 2.40494704, 2.10288811, 0.53503096, 1.44511235, 6.66344261, -3.05803776, 7.21418667, 3.30303526, -0.24163735, 3.47409391, 3.64520788, 2.15189481, -3.11243272, 3.62310791, 0.37379482, 0.40865007, -0.83132005, -4.78246069, 2.07030797, 6.51765442, 3.16178989, 5.06180477, 3.78434467, -0.96689719, 0.35965276, 5.89967585, 1.40294051, 1.11952639, 10.59778214, 0.26739889, -1.61297631, 6.24801159, -0.93914318, -0.57812452, 9.92604542, -0.73025000, -3.38530874, 2.45646000, -2.47949195, 0.51638460, 10.65636063, 1.97816694, -3.00407791, 2.66914415, -0.81951088, -0.23316640, 2.40737987, -2.70007610, 1.51531935, 4.08860207, -0.27552786, -1.31721711, 7.11568260, -3.33498216, -4.02545023, 7.22675610, -0.81690705, -2.52689576, 1.04016697, -0.79291463, -0.34875512, 10.00498390, -4.24167728, 1.46162593, 11.82569408, -1.70359993, -0.30161047, 16.44085884, -0.82253462, -0.09435523, 6.13080597, -0.20259480, 0.68308711, 6.15663004, -6.61776876, 0.33295766, 2.55449438, -0.17819691, -1.14892209, 5.56776142, 1.99279118, 1.33035934, 4.45823956, 3.34916544, -2.59905386, 6.16164446, -2.03881931, -2.45273542, 12.46793365, -2.22743297, 2.83738565, 8.48628139, -1.39347959, -1.30867767, 11.08041477, -4.00363779, 2.09183025, 11.30395889, -2.20504737, 1.37426853, 8.98735619, 1.04676604, -0.72757077, 8.28050232, -6.70741081, -0.65798020, 5.68592072, -0.60760021, 0.35854483, 6.26852131, 1.94100165, 1.32112014, 0.80987954, -1.74617672, -0.25434083, 7.16045523, 1.58884013, -2.64847064, 13.14820385, 1.21393633, -2.47258949, 9.41650105, -0.79384226, 2.48954105, 10.95629311, 0.47723705, 4.02126694, 8.02593136, -2.20726371, -1.18794477, 1.50836647, 0.93118095, -1.73513174, 8.85493565, -2.99670315, -0.79055870, 2.39473820, 2.05046916, -2.38055134, 11.82299423, 0.15609655, 0.68744308, 5.66401434, -0.69281673, 2.09855556, 7.74626589, -0.34283102, 1.00542057, 9.95838642, 0.80161905, 2.33455157, 9.80057335, -0.93561798, 2.56991577, 8.29711342, 0.94213426, 0.44209945, 11.70259857, 0.92710167, 2.60957146, 0.24971688, -0.86529571, 3.78628922, 6.80884457, -0.68178189, 2.21103406, 3.18895817, 0.60283208, -2.92716241, 6.72060776, -1.06625068, 2.56543374, 9.97404480, 3.58080721, -0.94936347, 10.16736984, -1.38464379, 1.18191063, 6.66179037, -3.56115270, 0.32329530, 10.90870762, 2.20638227, 0.19653285, 7.34650040, -3.63859272, -1.03027737, 5.98829985, -3.66606474, -3.89746714, 8.63469028, 1.22569811, 1.63240814, 3.74385309, 0.58243257, -0.56981975, 3.69260955, 1.00979900, -1.44030499, 8.57058144, -1.10648811, 1.20474911, 5.43133020, -2.14822555, -0.07928789, 11.25825310, 0.19645604, -5.49546146, 10.41917038, -0.68178523, -2.99639869, 6.50054455, 0.46488351, -5.42328453, 9.09500027, -2.82107449, 0.05601966, 15.34610748, -0.06820253, 3.86699796, 10.73316956, -3.04795432, -0.14702171, 5.64813185, 1.44028485, -2.47596145, 0.07280898, -3.03187990, -1.35183525, 9.35835648, 2.72966957, 1.88199532, 10.36187744, -0.22834805, -3.26738238, 6.92025137, -2.34061313, 4.77379704, 5.28559113, -2.96323752, -1.76186585, 5.94436455, 0.38647744, -5.73869514, 6.76849556, 1.40892124, -1.19068217, 5.37919092, -6.65328646, 3.62782669, 12.34744644, 2.44762444, -4.19242620, 6.14906216, 0.08121119, 0.61355996, 2.69666457, -1.88962626, -0.55314136, 1.84937525, 1.56048691, 1.17460012, 3.75674725, 1.06198275, -5.74625874, 5.41645575, -1.28946674, -1.51689398, 4.32400894, -0.05222082, -4.83948946, 1.80747867, 1.63144708, -2.73887825, 1.63975775, -2.02163982, -0.16210437, 2.93518686, 1.14427686, -2.83246303, 4.79283667, 2.69697428, -3.12678456, -1.19225168, -2.37022972, -3.09429741, 1.94225383, -1.13747168, -2.55048585, 5.40242243, 1.12777328, 3.43713188, 3.62658787, -2.16878843, 0.30164462, 2.97407579, -0.07275413, -1.31149673, 4.70066261, -2.01323795, 4.85255766, 4.59128904, 1.68084168, 1.60336494, 6.58138466, -1.04759812, 2.69906545, 3.55769277, -0.74327278, 2.65819693, 5.39528131, 2.11248922, -1.06446671, 5.24546766, -2.43146014, 4.58907509, 0.06521678, -2.24503994, 2.45722699, 6.94863081, 0.35258654, 2.83396196, 9.92525196, -1.12225175, -0.34365177, 7.19116688, -4.39813757, 0.46517885, 13.22028065, -2.57483673, -6.37226963, 7.58046293, -2.74600363, 0.42231262, 8.04881668, 0.17289802, -0.53447008, 16.55157471, -5.63614368, 0.39288223, 3.37079263, 1.26484549, -0.12820500, 8.46440125, -4.39304399, 2.97676420, 0.65650189, 0.83158541, -1.11556435, 6.32885838, -0.36087769, 2.80724382, 9.90292645, 1.15936041, 0.20947981, 6.91249275, -2.67404819, 2.93782163, 6.65656614, -2.30828357, 2.98214006, 6.80611229, -4.93821478, -7.66555262, 7.59763002, -0.54159302, 3.87403512, 12.42607784, 2.59284401, -0.23375344, 8.95293331, -0.71807784, 0.61873478, 8.66713524, 1.24289191, -2.37835455, 2.08071637, -0.88315344, -3.41891551, 6.85245323, 1.73007369, 1.02169311, 7.69170332, -2.85411978, 2.69790673, 8.12906551, -1.19351399, -2.26442742, 12.26104450, -0.75579089, -1.73274946, 10.68729019, 2.20655656, -0.90522075, 12.42165184, -1.67929137, 2.44851565, 9.31565762, -0.06645700, 1.52762020, 6.18427515, -1.68882596, 3.70261097, 3.02252960, -3.44125366, -1.31575799, 2.84617424, -0.96849400, -4.52356243, 9.95027161, 0.19966406, -0.78874779, 8.18595028, -4.08300209, 1.75126517, 0.96418417, -4.04913044, -0.95200396, 12.03637886, -0.03041124, 0.41642749, 8.88267422, -3.24985337, -2.24919462, 7.32566118, 0.16964148, -2.74123430, 7.05264473, -3.30191112, 0.17163286, 4.81851053, -1.64463484, -0.85933101, 7.29276276, 2.34066939, -2.14860010, 3.46148157, -0.01782012, 1.51504040, 4.79304934, 1.85281146, -1.70663762, 6.93470192, -4.15440845, -1.25983095, 10.52491760, 0.42930329, -1.85146868, 11.70042324, -0.41704914, 3.83796859, 9.21148491, -2.79719448, 0.79470479, 6.26926661, -5.85230207, 3.95105338, 7.84790897, -1.38680744, -1.78099084, 11.95235348, -2.99841452, -1.34507811, 6.15714645, -1.07552516, -2.81228638, 1.66234732, -4.55166149, -1.92601109, 8.64634514, -0.48158705, 3.31595659, 7.67371941, 2.56964207, 0.12107098, 4.56467867, -0.93541539, 1.39432955, 11.99714088, 1.05353570, -2.13099813, 3.67617917, 3.45895386, 1.37365830, 8.74344158, -4.17585802, 1.43908918, 6.28764772, 3.97346330, -0.69144285, 9.07983303, -0.41635889, -0.14965028, 8.85469818, 1.11306190, 2.59440994, 5.38982344, -1.07948279, 1.37252975, 10.26984596, -0.09318046, 2.73104119, 12.45902252, -1.55446684, -2.76124811, 12.19395065, -0.51846564, 1.02764034, 11.42673588, -0.95940983, -0.04781032, 8.78379822, -4.88957930, 0.32534006, 11.97696400, -3.35108662, 1.95104563, 4.46915388, -2.32061648, 3.45230985, 8.29983711, 2.81034684, -2.35529327, 6.07801294, -0.98105043, -0.05359888, 2.52291036, -0.01986909, -2.35321999, 10.51954269, 2.11145401, 3.53506470, 7.29093266, 0.03721160, -1.13496494, 7.43886709, -5.84201956, 2.50796294, 12.14647675, 2.77490377, -2.18896222, 6.05641937, 5.32617044, 1.04221284, 10.79106712, -2.95749092, -2.75414610, 11.30037117, -3.40654182, -2.24673963, 7.49126101, 0.70811015, -6.18003702, 13.83951187, -1.01204085, 1.36298490, -1.04451632, 2.42435336, -0.02346706, -0.85528886, 1.04731262, 0.22192979, 4.15708160, 0.34933877, 0.04814529, 2.24107265, 0.49676740, -1.47752666, 0.45040059, -0.70471478, -1.19759345, 0.21711677, 0.88461423, -2.76830935, 5.52066898, 1.97664857, -1.75381601, 3.45877838, 1.52617192, -1.61350942, 0.85337949, 1.97610760, -3.40310287, 3.40319014, -3.38691044, -0.71319139, 1.65463758, -0.60680127, -1.80700517, 8.02592373, 2.59627104, 2.65895891, 5.93043184, -4.48425817, 3.92670918, 4.19496679, -2.28286791, 6.41634607, 5.72330523, 1.16269672, -0.28753027, 2.46342492, 0.36693189, 0.26712441, 6.37652683, -2.50139046, 2.43923736, 5.56310415, 0.98065847, 1.04267502, 4.16403675, -0.04966142, 4.40897894, 3.72905660, -3.46129870, 3.59962773, 1.34830284, -1.76661730, 0.47943926, 5.29946661, -1.12711561, 1.26970029, 15.17655945, -1.50971997, 5.81345224, 8.48562050, -4.36049604, 2.48144460, 8.23780441, -3.46030426, -0.84656560, 5.94946814, 1.12747943, -2.65683913, 8.69085693, 1.31309867, -2.79958344, 8.76840591, -1.56444156, 1.62710834, 2.41177034, -0.72804940, 5.70619011, 4.67169666, -0.86167198, -1.83803177, 2.96346045, 2.82692933, -2.81557131, 7.11113358, -1.90071094, 2.54244423, 11.19284058, -0.06298946, -1.71517313, 12.98388577, 0.84510714, 3.00816894, 2.57200313, 0.03899818, -1.49330592, 9.60099125, -3.59513044, -1.30045319, 7.09241819, -0.65233821, -2.33627677, 8.81366920, 0.84154201, 1.03312039, 9.85289097, 0.19351870, 1.78496623, 7.34631205, -2.16530800, -0.65016162, 2.46842360, 0.24016285, -1.24308395, 4.78175163, -0.97682536, 2.20942235, 6.68382788, 3.76786447, -1.44454038, 6.26453733, -3.23575711, -2.30137897, 9.53092670, -5.55222607, 3.25999236, 9.37559509, 1.86339056, -0.23551451, 10.23400211, 3.93031883, -0.52629089, 7.85724449, -2.91549587, 4.46612740, 5.66530371, -2.70820427, 4.81359577, 10.31247330, 1.92230141, 2.53931546, 0.74986327, 1.70303428, 0.48063779, 5.31099129, -0.78976244, 3.75864220, 4.23051405, 2.34042454, -7.98193836, 9.83987141, -1.46722627, 3.54497814, 10.36455154, -4.51249075, 0.77715248, 7.78694630, -4.59989023, -2.49585629, 9.90296268, 1.38535416, 1.17441154, 10.10452843, -0.98628229, 0.60194463, 9.12639141, -3.90754628, 2.88526392, 7.24123430, -0.15283313, -0.75728363, -1.15116858, -2.53791571, 0.77229571, 6.44114161, 0.02646767, 4.95463037, 7.21066380, 1.79384065, 0.73250306, 8.04447937, 0.32576546, -0.79447043, 10.12717724, 2.33392906, 1.30716443, 12.36073112, -0.36694977, -1.20438910, 7.03105593, 0.59557682, 0.69267452, 10.18113136, 2.49944925, -0.42229167, 8.83143330, -1.18805945, -2.87509322, 4.53596449, 4.09732771, -3.39088297, -1.02536607, 0.82119560, -3.47302604, 9.29991817, 0.21001509, 4.97036457, 9.50018406, 1.04420102, 1.96560478, 10.74769592, -6.22709799, 3.11690164, 5.06759691, -1.23724771, -3.05831861, 8.12925529, -1.93435478, -1.10151744, 9.32263088, -0.04249470, -5.98547363, 10.49398136, 0.26400441, -0.78915191, 13.28219604, 2.99276900, 0.74853164, 2.49364305, -3.43529654, 4.05278301, 2.13498688, -2.35444307, -0.79900265, 4.66968822, -0.31095147, 3.60674143, 12.37222099, -0.07855003, -3.30292702, 12.15215874, 0.60886210, 2.87075138, 7.75271845, 0.38044083, 3.34402204, 6.40583277, -0.87888050, 0.67438459, 6.91080809, 1.98332930, -0.08303714, 8.08630371, -0.16772588, -2.74058914, 7.17253590, -2.69122696, 1.48173678, 8.99470139, -1.43302310, -0.88651133, 2.66944790, -0.29186964, 2.00838661, 5.09587479, -0.76676071, -2.88322186, 8.31110573, -0.14550979, -1.37726915, 10.28355122, -1.60575438, -0.04118848, 9.97510815, 0.14440438, -3.24632120, 9.00034523, 4.14319563, -1.31023729, 7.16950464, -0.70428526, 2.01559544, 7.26155043, 2.40816474, 2.09847403, 7.31264496, -0.75401551, 2.13392544, 7.03648758, 1.04036045, -1.15636516, 1.09634531, -0.06340861, -0.58107805, -0.65623116, 1.18972754, -0.80717683, 1.40118241, -0.61932516, -3.60596156, 1.59904599, -2.23774099, -1.13721037, 3.89620137, -0.09115922, -7.51356888, 2.36975193, -1.42520905, -2.34173775, 3.33830214, -2.74016523, -3.04115510, 6.00119495, -1.36084354, -2.45065260, 4.56992292, -3.02825928, -3.74182844, 5.11069250, -0.91531068, -2.31385994, 1.83399653, 3.39370203, -3.60886002}); auto exp = NDArrayFactory::create<TypeParam>('c', {4, 4, 4, 3}, {7.97172260, 0.06878620, 2.27749538, 7.29276514, -0.14074677, 0.65480286, 5.70313978, -0.06546132, 0.35443667, 3.70382833, -0.84020567, 0.63826996, 8.60301399, -0.38236514, 1.55177069, 7.37542057, -0.99374938, -0.29971302, 8.84352493, -0.67121059, 0.43132120, 4.78175592, -1.25070143, -1.91523600, 6.03855371, -0.00292124, -1.11214364, 7.90158176, -0.57949901, -0.96735370, 7.81192017, -0.53255427, -0.48009714, 3.16953635, 0.08353355, -1.54299748, 3.74821687, 1.69396687, 0.72724354, 5.42915201, -1.13686812, -0.71793109, 5.78376389, -0.72239977, -0.60055625, 2.53636408, 0.56777251, -2.07892323, 6.08064651, 0.68620735, 2.54017019, 5.65828180, -0.68255502, 1.47283304, 6.10842514, -0.39655915, 0.28380761, 1.96707797, -1.98206317, 0.94027776, 4.71811438, 0.32104525, -0.92409706, 8.34588146, -1.05581069, -0.55217457, 9.58440876, -0.96549922, 0.45820439, 5.65453672, -2.50953507, -0.71441835, 8.03059578, -0.21281289, 0.92125505, 9.26900673, -0.35963219, -0.70039093, 8.59924412, -1.22358346, 0.81318003, 3.85920119, -0.01305223, -1.09234154, 6.33158875, 1.28094780, -1.48926139, 4.94969177, -0.77126902, -1.97033751, 5.64381838, -0.16285487, -1.31277227, 2.39893222, -1.32902908, -1.39609122, 6.47572327, -0.45267010, 1.55727172, 6.70965624, -1.68735468, -0.05672536, 7.25092363, -0.64613032, 0.67050058, 3.60789680, -2.05948973, 2.22687531, 8.15202713, -0.70148355, 1.28314006, 8.14842319, -1.88807654, -1.04808438, 8.45500565, -0.76425624, 0.94542569, 4.56179953, -0.28786001, -2.04502511, 8.46278095, -0.31019822, 0.07339200, 9.34214592, -0.61948007, 0.52481830, 8.32515621, -1.52418160, 0.49678251, 5.11082315, -1.09908783, -0.52969611, 5.27806664, 0.88632923, 0.66754371, 4.75839233, 0.48928693, -0.68036932, 6.56925392, -0.02949905, -2.99189186, 4.46320581, -0.64534980, -0.29516968, 8.60809517, -1.13120568, 3.41720533, 5.84243155, -1.24109328, 0.89566326, 5.99578333, -0.42496428, 2.07076764, 3.17812920, -0.81566459, -0.14363396, 6.55184317, 0.39633346, -0.43852386, 8.70214558, -2.24613595, 0.30708700, 8.73882294, -0.53545928, 1.54409575, 4.49452257, -0.16509305, 0.19028664, 8.24897003, 0.44750381, 2.15448594, 8.97640514, -0.77728152, 0.57272542, 9.03467560, 0.47173575, -1.10807717, 3.30056310, -0.43268481, -0.41470885, 3.53798294, -0.08546703, -2.16840744, 6.18733406, -0.17871059, -2.59837723, 5.94218683, -1.02990067, -0.49760687, 3.76938033, 0.86383581, -1.91504073}); nd4j::ops::avgpool2d op; auto result = op.execute({&input}, {}, {3,3, 3,3, 0,0, 1,1,1, 0,1}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("z"); // exp.printIndexedBuffer("e"); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, SeparableConv2D_FF_NoBias_1) { float _expB[] = {10025.0f, 10350.0f, 10675.0f, 11000.0f, 11325.0f, 11650.0f, 13275.0f, 13600.0f, 13925.0f, 14250.0f, 14575.0f, 14900.0f, 16525.0f, 16850.0f, 17175.0f, 17500.0f, 17825.0f, 18150.0f, 19775.0f, 20100.0f, 20425.0f, 20750.0f, 21075.0f, 21400.0f, 23025.0f, 23350.0f, 23675.0f, 24000.0f, 24325.0f, 24650.0f, 26275.0f, 26600.0f, 26925.0f, 27250.0f, 27575.0f, 27900.0f, 38775.0f, 40350.0f, 41925.0f, 43500.0f, 45075.0f, 46650.0f, 54525.0f, 56100.0f, 57675.0f, 59250.0f, 60825.0f, 62400.0f, 70275.0f, 71850.0f, 73425.0f, 75000.0f, 76575.0f, 78150.0f, 86025.0f, 87600.0f, 89175.0f, 90750.0f, 92325.0f, 93900.0f, 101775.0f, 103350.0f, 104925.0f, 106500.0f, 108075.0f, 109650.0f, 117525.0f, 119100.0f, 120675.0f, 122250.0f, 123825.0f, 125400.0f, 67525.0f, 70350.0f, 73175.0f, 76000.0f, 78825.0f, 81650.0f, 95775.0f, 98600.0f, 101425.0f, 104250.0f, 107075.0f, 109900.0f, 124025.0f, 126850.0f, 129675.0f, 132500.0f, 135325.0f, 138150.0f, 152275.0f, 155100.0f, 157925.0f, 160750.0f, 163575.0f, 166400.0f, 180525.0f, 183350.0f, 186175.0f, 189000.0f, 191825.0f, 194650.0f, 208775.0f, 211600.0f, 214425.0f, 217250.0f, 220075.0f, 222900.0f, 119400.0f, 120350.0f, 121300.0f, 122250.0f, 123200.0f, 124150.0f, 128900.0f, 129850.0f, 130800.0f, 131750.0f, 132700.0f, 133650.0f, 138400.0f, 139350.0f, 140300.0f, 141250.0f, 142200.0f, 143150.0f, 147900.0f, 148850.0f, 149800.0f, 150750.0f, 151700.0f, 152650.0f, 157400.0f, 158350.0f, 159300.0f, 160250.0f, 161200.0f, 162150.0f, 166900.0f, 167850.0f, 168800.0f, 169750.0f, 170700.0f, 171650.0f, 273150.0f, 275350.0f, 277550.0f, 279750.0f, 281950.0f, 284150.0f, 295150.0f, 297350.0f, 299550.0f, 301750.0f, 303950.0f, 306150.0f, 317150.0f, 319350.0f, 321550.0f, 323750.0f, 325950.0f, 328150.0f, 339150.0f, 341350.0f, 343550.0f, 345750.0f, 347950.0f, 350150.0f, 361150.0f, 363350.0f, 365550.0f, 367750.0f, 369950.0f, 372150.0f, 383150.0f, 385350.0f, 387550.0f, 389750.0f, 391950.0f, 394150.0f, 426900.0f, 430350.0f, 433800.0f, 437250.0f, 440700.0f, 444150.0f, 461400.0f, 464850.0f, 468300.0f, 471750.0f, 475200.0f, 478650.0f, 495900.0f, 499350.0f, 502800.0f, 506250.0f, 509700.0f, 513150.0f, 530400.0f, 533850.0f, 537300.0f, 540750.0f, 544200.0f, 547650.0f, 564900.0f, 568350.0f, 571800.0f, 575250.0f, 578700.0f, 582150.0f, 599400.0f, 602850.0f, 606300.0f, 609750.0f, 613200.0f, 616650.0f, 75025.0f, 75350.0f, 75675.0f, 76000.0f, 76325.0f, 76650.0f, 78275.0f, 78600.0f, 78925.0f, 79250.0f, 79575.0f, 79900.0f, 81525.0f, 81850.0f, 82175.0f, 82500.0f, 82825.0f, 83150.0f, 84775.0f, 85100.0f, 85425.0f, 85750.0f, 86075.0f, 86400.0f, 88025.0f, 88350.0f, 88675.0f, 89000.0f, 89325.0f, 89650.0f, 91275.0f, 91600.0f, 91925.0f, 92250.0f, 92575.0f, 92900.0f, 353775.0f, 355350.0f, 356925.0f, 358500.0f, 360075.0f, 361650.0f, 369525.0f, 371100.0f, 372675.0f, 374250.0f, 375825.0f, 377400.0f, 385275.0f, 386850.0f, 388425.0f, 390000.0f, 391575.0f, 393150.0f, 401025.0f, 402600.0f, 404175.0f, 405750.0f, 407325.0f, 408900.0f, 416775.0f, 418350.0f, 419925.0f, 421500.0f, 423075.0f, 424650.0f, 432525.0f, 434100.0f, 435675.0f, 437250.0f, 438825.0f, 440400.0f, 632525.0f, 635350.0f, 638175.0f, 641000.0f, 643825.0f, 646650.0f, 660775.0f, 663600.0f, 666425.0f, 669250.0f, 672075.0f, 674900.0f, 689025.0f, 691850.0f, 694675.0f, 697500.0f, 700325.0f, 703150.0f, 717275.0f, 720100.0f, 722925.0f, 725750.0f, 728575.0f, 731400.0f, 745525.0f, 748350.0f, 751175.0f, 754000.0f, 756825.0f, 759650.0f, 773775.0f, 776600.0f, 779425.0f, 782250.0f, 785075.0f, 787900.0f, 309400.0f, 310350.0f, 311300.0f, 312250.0f, 313200.0f, 314150.0f, 318900.0f, 319850.0f, 320800.0f, 321750.0f, 322700.0f, 323650.0f, 328400.0f, 329350.0f, 330300.0f, 331250.0f, 332200.0f, 333150.0f, 337900.0f, 338850.0f, 339800.0f, 340750.0f, 341700.0f, 342650.0f, 347400.0f, 348350.0f, 349300.0f, 350250.0f, 351200.0f, 352150.0f, 356900.0f, 357850.0f, 358800.0f, 359750.0f, 360700.0f, 361650.0f, 713150.0f, 715350.0f, 717550.0f, 719750.0f, 721950.0f, 724150.0f, 735150.0f, 737350.0f, 739550.0f, 741750.0f, 743950.0f, 746150.0f, 757150.0f, 759350.0f, 761550.0f, 763750.0f, 765950.0f, 768150.0f, 779150.0f, 781350.0f, 783550.0f, 785750.0f, 787950.0f, 790150.0f, 801150.0f, 803350.0f, 805550.0f, 807750.0f, 809950.0f, 812150.0f, 823150.0f, 825350.0f, 827550.0f, 829750.0f, 831950.0f, 834150.0f, 1116900.0f, 1120350.0f, 1123800.0f, 1127250.0f, 1130700.0f, 1134150.0f, 1151400.0f, 1154850.0f, 1158300.0f, 1161750.0f, 1165200.0f, 1168650.0f, 1185900.0f, 1189350.0f, 1192800.0f, 1196250.0f, 1199700.0f, 1203150.0f, 1220400.0f, 1223850.0f, 1227300.0f, 1230750.0f, 1234200.0f, 1237650.0f, 1254900.0f, 1258350.0f, 1261800.0f, 1265250.0f, 1268700.0f, 1272150.0f, 1289400.0f, 1292850.0f, 1296300.0f, 1299750.0f, 1303200.0f, 1306650.0f,}; Nd4jLong _expS[] = {4, 2, 6, 6, 6, 144, 36, 6, 1, 8192, 1, 99}; NDArray exp(_expB, _expS); int sY = 1; int sX = 1; int pY = 0; int pX = 0; int iC = 2; int oC = 3; int kY = 5; int kX = 5; int iY = 10; int iX = 10; int B = 2; auto input = NDArrayFactory::create_<float>('c', {B, iC, iY, iX}); for (int e = 0; e < input->lengthOf(); e++) input->p(e, e+1); auto weights = NDArrayFactory::create_<float>('c', {oC, iC, kY, kX}); for (int e = 0; e < weights->lengthOf(); e++) weights->p(e, e+1); weights->permutei({2,3,1,0}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); block->fillInputs({-1, -2}); block->getIArguments()->push_back(kY); block->getIArguments()->push_back(kX); block->getIArguments()->push_back(sY); block->getIArguments()->push_back(sX); block->getIArguments()->push_back(pY); block->getIArguments()->push_back(pX); // dilation block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); // NOT same mode block->getIArguments()->push_back(0); nd4j::ops::sconv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto output = variableSpace->getVariable(1)->getNDArray(); //exp.printShapeInfo("Expected shape"); //output->printShapeInfo("Result shape"); ASSERT_TRUE(exp.isSameShape(output)); //exp.printBuffer("Expctd buffer"); //output->printBuffer("Result buffer"); ASSERT_TRUE(exp.equalsTo(output)); delete block; delete variableSpace; } TYPED_TEST(TypedConvolutionTests1, deconv2D_FF_NoBias_1) { Nd4jLong _expS[] = {4, 2, 3, 8, 8, 192, 64, 8, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; TypeParam _expB[] = {6276.0, 12831.0, 19668.0, 26790.0, 27012.0, 20703.0, 14100.0, 7200.0, 13719.0, 28023.0, 42918.0, 58410.0, 58902.0, 45105.0, 30693.0, 15660.0, 22389.0, 45696.0, 69930.0, 95100.0, 95910.0, 73386.0, 49899.0, 25440.0, 32346.0, 65970.0, 100884.0, 137100.0, 138276.0, 105726.0, 71838.0, 36600.0, 33726.0, 68790.0, 105204.0, 142980.0, 144156.0, 110226.0, 74898.0, 38160.0, 27555.0, 56154.0, 85806.0, 116520.0, 117474.0, 89748.0, 60933.0, 31020.0, 19917.0, 40557.0, 61926.0, 84030.0, 84714.0, 64671.0, 43875.0, 22320.0, 10752.0, 21879.0, 33384.0, 45270.0, 45636.0, 34815.0, 23604.0, 12000.0, 7551.0, 15456.0, 23718.0, 32340.0, 32562.0, 24978.0, 17025.0, 8700.0, 16569.0, 33873.0, 51918.0, 70710.0, 71202.0, 54555.0, 37143.0, 18960.0, 27114.0, 55371.0, 84780.0, 115350.0, 116160.0, 88911.0, 60474.0, 30840.0, 39246.0, 80070.0, 122484.0, 166500.0, 167676.0, 128226.0, 87138.0, 44400.0, 40626.0, 82890.0, 126804.0, 172380.0, 173556.0, 132726.0, 90198.0, 45960.0, 33180.0, 67629.0, 103356.0, 140370.0, 141324.0, 107973.0, 73308.0, 37320.0, 23967.0, 48807.0, 74526.0, 101130.0, 101814.0, 77721.0, 52725.0, 26820.0, 12927.0, 26304.0, 40134.0, 54420.0, 54786.0, 41790.0, 28329.0, 14400.0, 8826.0, 18081.0, 27768.0, 37890.0, 38112.0, 29253.0, 19950.0, 10200.0, 19419.0, 39723.0, 60918.0, 83010.0, 83502.0, 64005.0, 43593.0, 22260.0, 31839.0, 65046.0, 99630.0, 135600.0, 136410.0, 104436.0, 71049.0, 36240.0, 46146.0, 94170.0, 144084.0, 195900.0, 197076.0, 150726.0, 102438.0, 52200.0, 47526.0, 96990.0, 148404.0, 201780.0, 202956.0, 155226.0, 105498.0, 53760.0, 38805.0, 79104.0, 120906.0, 164220.0, 165174.0, 126198.0, 85683.0, 43620.0, 28017.0, 57057.0, 87126.0, 118230.0, 118914.0, 90771.0, 61575.0, 31320.0, 15102.0, 30729.0, 46884.0, 63570.0, 63936.0, 48765.0, 33054.0, 16800.0, 17220.0, 34863.0, 52932.0, 71430.0, 72228.0, 54831.0, 36996.0, 18720.0, 36327.0, 73527.0, 111606.0, 150570.0, 152214.0, 115521.0, 77925.0, 39420.0, 57381.0, 116112.0, 176202.0, 237660.0, 240198.0, 182250.0, 122907.0, 62160.0, 80442.0, 162738.0, 246900.0, 332940.0, 336420.0, 255198.0, 172062.0, 87000.0, 84702.0, 171318.0, 259860.0, 350340.0, 353820.0, 268338.0, 180882.0, 91440.0, 66867.0, 135210.0, 205038.0, 276360.0, 279042.0, 211572.0, 142581.0, 72060.0, 46845.0, 94701.0, 143574.0, 193470.0, 195306.0, 148047.0, 99747.0, 50400.0, 24576.0, 49671.0, 75288.0, 101430.0, 102372.0, 77583.0, 52260.0, 26400.0, 22095.0, 44688.0, 67782.0, 91380.0, 92178.0, 69906.0, 47121.0, 23820.0, 46377.0, 93777.0, 142206.0, 191670.0, 193314.0, 146571.0, 98775.0, 49920.0, 72906.0, 147387.0, 223452.0, 301110.0, 303648.0, 230175.0, 155082.0, 78360.0, 101742.0, 205638.0, 311700.0, 419940.0, 423420.0, 320898.0, 216162.0, 109200.0, 106002.0, 214218.0, 324660.0, 437340.0, 440820.0, 334038.0, 224982.0, 113640.0, 83292.0, 168285.0, 254988.0, 343410.0, 346092.0, 262197.0, 176556.0, 89160.0, 58095.0, 117351.0, 177774.0, 239370.0, 241206.0, 182697.0, 122997.0, 62100.0, 30351.0, 61296.0, 92838.0, 124980.0, 125922.0, 95358.0, 64185.0, 32400.0, 26970.0, 54513.0, 82632.0, 111330.0, 112128.0, 84981.0, 57246.0, 28920.0, 56427.0, 114027.0, 172806.0, 232770.0, 234414.0, 177621.0, 119625.0, 60420.0, 88431.0, 178662.0, 270702.0, 364560.0, 367098.0, 278100.0, 187257.0, 94560.0, 123042.0, 248538.0, 376500.0, 506940.0, 510420.0, 386598.0, 260262.0, 131400.0, 127302.0, 257118.0, 389460.0, 524340.0, 527820.0, 399738.0, 269082.0, 135840.0, 99717.0, 201360.0, 304938.0, 410460.0, 413142.0, 312822.0, 210531.0, 106260.0, 69345.0, 140001.0, 211974.0, 285270.0, 287106.0, 217347.0, 146247.0, 73800.0, 36126.0, 72921.0, 110388.0, 148530.0, 149472.0, 113133.0, 76110.0, 38400.0,}; NDArray exp(_expB, _expS); auto input = NDArrayFactory::create_<TypeParam>('c', {2, 3, 4, 4}); auto weights = NDArrayFactory::create_<TypeParam>('c', {3, 3, 5, 5}); input->linspace(1); weights->linspace(1); weights->permutei({2,3,1,0}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); block->fillInputs({-1, -2}); block->getIArguments()->push_back(5); block->getIArguments()->push_back(5); block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); block->getIArguments()->push_back(0); block->getIArguments()->push_back(0); // dilation block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); // NOT same mode block->getIArguments()->push_back(0); block->getIArguments()->push_back(0); nd4j::ops::deconv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto output = variableSpace->getVariable(1)->getNDArray(); ASSERT_TRUE(exp.isSameShape(output)); // exp.printBuffer("Expctd buffer"); //output->printBuffer("Result buffer"); ASSERT_TRUE(exp.equalsTo(output)); delete variableSpace; delete block; } TYPED_TEST(TypedConvolutionTests1, conv2D_BP_Bias_1) { TypeParam _expWGradB[] = {9312.0, 12580.0, 9528.0, 13168.0, 17712.0, 13360.0, 9960.0, 13348.0, 10032.0, 13344.0, 18148.0, 13848.0, 19312.0, 26160.0, 19888.0, 15144.0, 20452.0, 15504.0}; Nd4jLong _expWGradS[] = {4, 2, 1, 3, 3, 9, 9, 3, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expWGrad(_expWGradB, _expWGradS); expWGrad.permutei({2,3,1,0}); TypeParam _expBGradB[] = {784.0, 1296.0}; Nd4jLong _expBGradS[] = {2, 2, 1, 1, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expBGrad(_expBGradB, _expBGradS); auto input = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto bias = NDArrayFactory::create<TypeParam>('c', {2, 1}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, input.getShapeInfo()); input.linspace(1); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}, {}); ASSERT_TRUE(results->size() == 3); auto epsilon = results->at(0); auto gradW = results->at(1); auto gradB = results->at(2); ASSERT_TRUE(expWGrad.isSameShape(gradW)); //expWGrad.printBuffer("Expctd buffer"); // gradW->printBuffer("Result buffer"); ASSERT_TRUE(expWGrad.equalsTo(gradW)); ASSERT_TRUE(input.isSameShape(epsilon)); // expEps.printBuffer("Expctd buffer"); //epsilon->printBuffer("Result buffer"); ASSERT_TRUE(expEps.equalsTo(epsilon)); ASSERT_TRUE(expBGrad.isSameShape(gradB)); ASSERT_TRUE(expBGrad.equalsTo(gradB)); delete results; } TYPED_TEST(TypedConvolutionTests1, conv2D_BP_NoBias_1) { TypeParam _expWGradB[] = {9312.0, 12580.0, 9528.0, 13168.0, 17712.0, 13360.0, 9960.0, 13348.0, 10032.0, 13344.0, 18148.0, 13848.0, 19312.0, 26160.0, 19888.0, 15144.0, 20452.0, 15504.0}; Nd4jLong _expWGradS[] = {4, 2, 1, 3, 3, 9, 9, 3, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expWGrad(_expWGradB, _expWGradS); expWGrad.permutei({2,3,1,0}); auto input = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, input.getShapeInfo()); input.linspace(1); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}, {}); ASSERT_TRUE(results->size() == 2); auto epsilon = results->at(0); auto gradW = results->at(1); ASSERT_TRUE(expWGrad.isSameShape(gradW)); //expWGrad.printBuffer("Expctd buffer"); // gradW->printBuffer("Result buffer"); ASSERT_TRUE(expWGrad.equalsTo(gradW)); ASSERT_TRUE(input.isSameShape(epsilon)); // expEps.printBuffer("Expctd buffer"); //epsilon->printBuffer("Result buffer"); ASSERT_TRUE(expEps.equalsTo(epsilon)); delete results; } TYPED_TEST(TypedConvolutionTests1, sconv2D_FF_NoBias_2) { TypeParam _expBFF[] = {10025.0f, 10350.0f, 10675.0f, 11000.0f, 11325.0f, 11650.0f, 13275.0f, 13600.0f, 13925.0f, 14250.0f, 14575.0f, 14900.0f, 16525.0f, 16850.0f, 17175.0f, 17500.0f, 17825.0f, 18150.0f, 19775.0f, 20100.0f, 20425.0f, 20750.0f, 21075.0f, 21400.0f, 23025.0f, 23350.0f, 23675.0f, 24000.0f, 24325.0f, 24650.0f, 26275.0f, 26600.0f, 26925.0f, 27250.0f, 27575.0f, 27900.0f, 53150.0f, 55350.0f, 57550.0f, 59750.0f, 61950.0f, 64150.0f, 75150.0f, 77350.0f, 79550.0f, 81750.0f, 83950.0f, 86150.0f, 97150.0f, 99350.0f, 101550.0f, 103750.0f, 105950.0f, 108150.0f, 119150.0f, 121350.0f, 123550.0f, 125750.0f, 127950.0f, 130150.0f, 141150.0f, 143350.0f, 145550.0f, 147750.0f, 149950.0f, 152150.0f, 163150.0f, 165350.0f, 167550.0f, 169750.0f, 171950.0f, 174150.0f, 119400.0f, 120350.0f, 121300.0f, 122250.0f, 123200.0f, 124150.0f, 128900.0f, 129850.0f, 130800.0f, 131750.0f, 132700.0f, 133650.0f, 138400.0f, 139350.0f, 140300.0f, 141250.0f, 142200.0f, 143150.0f, 147900.0f, 148850.0f, 149800.0f, 150750.0f, 151700.0f, 152650.0f, 157400.0f, 158350.0f, 159300.0f, 160250.0f, 161200.0f, 162150.0f, 166900.0f, 167850.0f, 168800.0f, 169750.0f, 170700.0f, 171650.0f, 350025.0f, 352850.0f, 355675.0f, 358500.0f, 361325.0f, 364150.0f, 378275.0f, 381100.0f, 383925.0f, 386750.0f, 389575.0f, 392400.0f, 406525.0f, 409350.0f, 412175.0f, 415000.0f, 417825.0f, 420650.0f, 434775.0f, 437600.0f, 440425.0f, 443250.0f, 446075.0f, 448900.0f, 463025.0f, 465850.0f, 468675.0f, 471500.0f, 474325.0f, 477150.0f, 491275.0f, 494100.0f, 496925.0f, 499750.0f, 502575.0f, 505400.0f, 353775.0f, 355350.0f, 356925.0f, 358500.0f, 360075.0f, 361650.0f, 369525.0f, 371100.0f, 372675.0f, 374250.0f, 375825.0f, 377400.0f, 385275.0f, 386850.0f, 388425.0f, 390000.0f, 391575.0f, 393150.0f, 401025.0f, 402600.0f, 404175.0f, 405750.0f, 407325.0f, 408900.0f, 416775.0f, 418350.0f, 419925.0f, 421500.0f, 423075.0f, 424650.0f, 432525.0f, 434100.0f, 435675.0f, 437250.0f, 438825.0f, 440400.0f, 771900.0f, 775350.0f, 778800.0f, 782250.0f, 785700.0f, 789150.0f, 806400.0f, 809850.0f, 813300.0f, 816750.0f, 820200.0f, 823650.0f, 840900.0f, 844350.0f, 847800.0f, 851250.0f, 854700.0f, 858150.0f, 875400.0f, 878850.0f, 882300.0f, 885750.0f, 889200.0f, 892650.0f, 909900.0f, 913350.0f, 916800.0f, 920250.0f, 923700.0f, 927150.0f, 944400.0f, 947850.0f, 951300.0f, 954750.0f, 958200.0f, 961650.0f, 107525.0f, 107850.0f, 108175.0f, 108500.0f, 108825.0f, 109150.0f, 110775.0f, 111100.0f, 111425.0f, 111750.0f, 112075.0f, 112400.0f, 114025.0f, 114350.0f, 114675.0f, 115000.0f, 115325.0f, 115650.0f, 117275.0f, 117600.0f, 117925.0f, 118250.0f, 118575.0f, 118900.0f, 120525.0f, 120850.0f, 121175.0f, 121500.0f, 121825.0f, 122150.0f, 123775.0f, 124100.0f, 124425.0f, 124750.0f, 125075.0f, 125400.0f, 713150.0f, 715350.0f, 717550.0f, 719750.0f, 721950.0f, 724150.0f, 735150.0f, 737350.0f, 739550.0f, 741750.0f, 743950.0f, 746150.0f, 757150.0f, 759350.0f, 761550.0f, 763750.0f, 765950.0f, 768150.0f, 779150.0f, 781350.0f, 783550.0f, 785750.0f, 787950.0f, 790150.0f, 801150.0f, 803350.0f, 805550.0f, 807750.0f, 809950.0f, 812150.0f, 823150.0f, 825350.0f, 827550.0f, 829750.0f, 831950.0f, 834150.0f, 404400.0f, 405350.0f, 406300.0f, 407250.0f, 408200.0f, 409150.0f, 413900.0f, 414850.0f, 415800.0f, 416750.0f, 417700.0f, 418650.0f, 423400.0f, 424350.0f, 425300.0f, 426250.0f, 427200.0f, 428150.0f, 432900.0f, 433850.0f, 434800.0f, 435750.0f, 436700.0f, 437650.0f, 442400.0f, 443350.0f, 444300.0f, 445250.0f, 446200.0f, 447150.0f, 451900.0f, 452850.0f, 453800.0f, 454750.0f, 455700.0f, 456650.0f, 1197525.0f, 1200350.0f, 1203175.0f, 1206000.0f, 1208825.0f, 1211650.0f, 1225775.0f, 1228600.0f, 1231425.0f, 1234250.0f, 1237075.0f, 1239900.0f, 1254025.0f, 1256850.0f, 1259675.0f, 1262500.0f, 1265325.0f, 1268150.0f, 1282275.0f, 1285100.0f, 1287925.0f, 1290750.0f, 1293575.0f, 1296400.0f, 1310525.0f, 1313350.0f, 1316175.0f, 1319000.0f, 1321825.0f, 1324650.0f, 1338775.0f, 1341600.0f, 1344425.0f, 1347250.0f, 1350075.0f, 1352900.0f, 826275.0f, 827850.0f, 829425.0f, 831000.0f, 832575.0f, 834150.0f, 842025.0f, 843600.0f, 845175.0f, 846750.0f, 848325.0f, 849900.0f, 857775.0f, 859350.0f, 860925.0f, 862500.0f, 864075.0f, 865650.0f, 873525.0f, 875100.0f, 876675.0f, 878250.0f, 879825.0f, 881400.0f, 889275.0f, 890850.0f, 892425.0f, 894000.0f, 895575.0f, 897150.0f, 905025.0f, 906600.0f, 908175.0f, 909750.0f, 911325.0f, 912900.0f, 1806900.0f, 1810350.0f, 1813800.0f, 1817250.0f, 1820700.0f, 1824150.0f, 1841400.0f, 1844850.0f, 1848300.0f, 1851750.0f, 1855200.0f, 1858650.0f, 1875900.0f, 1879350.0f, 1882800.0f, 1886250.0f, 1889700.0f, 1893150.0f, 1910400.0f, 1913850.0f, 1917300.0f, 1920750.0f, 1924200.0f, 1927650.0f, 1944900.0f, 1948350.0f, 1951800.0f, 1955250.0f, 1958700.0f, 1962150.0f, 1979400.0f, 1982850.0f, 1986300.0f, 1989750.0f, 1993200.0f, 1996650.}; Nd4jLong _expSFF[] = {4, 2, 6, 6, 6, 216, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray expFF(_expBFF, _expSFF); TypeParam _exp2BFF[] = {827.4900282f, 832.2350283f, 836.9800284f, 841.725028f, 846.4700287f, 851.2150288f, 874.9400293f, 879.6850294f, 884.4300295f, 889.1750296f, 893.9200297f, 898.665029f, 922.3900304f, 927.1350305f, 931.8800306f, 936.6250307f, 941.3700308f, 946.1150309f, 969.8400315f, 974.5850316f, 979.3300317f, 984.0750318f, 988.8200319f, 993.5650320f, 1017.2900326f, 1022.0350327f, 1026.7800328f, 1031.5250329f, 1036.2700330f, 1041.0150331f, 1064.7400337f, 1069.4850338f, 1074.2300339f, 1078.9750340f, 1083.7200341f, 1088.4650342f, 1822.4550553f, 1833.995055f, 1845.5350558f, 1857.075056f, 1868.6150563f, 1880.1550566f, 1937.8550578f, 1949.3950581f, 1960.9350583f, 1972.4750586f, 1984.015058f, 1995.5550591f, 2053.2550604f, 2064.7950606f, 2076.3350609f, 2087.8750611f, 2099.4150614f, 2110.955061f, 2168.6550629f, 2180.1950632f, 2191.7350634f, 2203.2750637f, 2214.8150639f, 2226.3550642f, 2284.0550655f, 2295.5950657f, 2307.1350660f, 2318.6750662f, 2330.2150665f, 2341.7550667f, 2399.4550680f, 2410.9950683f, 2422.5350685f, 2434.0750688f, 2445.6150690f, 2457.1550693f, 2817.419968f, 2835.7549686f, 2854.0899683f, 2872.4249680f, 2890.7599677f, 2909.0949674f, 3000.7699660f, 3019.104965f, 3037.4399655f, 3055.7749652f, 3074.1099649f, 3092.4449646f, 3184.1199632f, 3202.4549629f, 3220.789962f, 3239.1249624f, 3257.4599621f, 3275.7949618f, 3367.4699604f, 3385.8049601f, 3404.1399598f, 3422.474959f, 3440.8099593f, 3459.1449590f, 3550.8199576f, 3569.1549573f, 3587.4899570f, 3605.8249567f, 3624.1599565f, 3642.4949562f, 3734.1699548f, 3752.5049545f, 3770.8399542f, 3789.1749539f, 3807.5099536f, 3825.8449534f, 3812.385098f, 3837.5150988f, 3862.6450994f, 3887.7751000f, 3912.9051006f, 3938.0351012f, 4063.6851041f, 4088.8151047f, 4113.9451053f, 4139.0751059f, 4164.2051065f, 4189.3351071f, 4314.9851100f, 4340.1151106f, 4365.2451112f, 4390.3751118f, 4415.5051124f, 4440.6351130f, 4566.2851159f, 4591.4151165f, 4616.5451171f, 4641.6751177f, 4666.805118f, 4691.9351188f, 4817.5851218f, 4842.7151224f, 4867.8451230f, 4892.975123f, 4918.1051241f, 4943.2351247f, 5068.8851277f, 5094.0151283f, 5119.1451288f, 5144.2751294f, 5169.4051300f, 5194.5351306f, 4807.3499803f, 4839.2749801f, 4871.1999799f, 4903.1249797f, 4935.0499795f, 4966.9749793f, 5126.5999784f, 5158.5249782f, 5190.4499780f, 5222.3749778f, 5254.2999777f, 5286.2249775f, 5445.8499765f, 5477.774976f, 5509.6999762f, 5541.6249760f, 5573.5499758f, 5605.4749756f, 5765.0999747f, 5797.0249745f, 5828.9499743f, 5860.8749741f, 5892.7999739f, 5924.724973f, 6084.3499728f, 6116.2749726f, 6148.1999724f, 6180.1249723f, 6212.0499721f, 6243.9749719f, 6403.59997f, 6435.5249708f, 6467.4499706f, 6499.3749704f, 6531.2999702f, 6563.2249700f, 5802.3150007f, 5841.0350006f, 5879.7550005f, 5918.4750004f, 5957.195000f, 5995.9150003f, 6189.5149999f, 6228.2349998f, 6266.9549997f, 6305.6749996f, 6344.3949995f, 6383.114999f, 6576.7149990f, 6615.4349990f, 6654.1549989f, 6692.8749988f, 6731.5949987f, 6770.3149986f, 6963.9149982f, 7002.6349981f, 7041.3549981f, 7080.0749980f, 7118.7949979f, 7157.5149978f, 7351.1149974f, 7389.8349973f, 7428.5549972f, 7467.2749972f, 7505.9949971f, 7544.7149970f, 7738.3149966f, 7777.0349965f, 7815.7549964f, 7854.4749963f, 7893.1949963f, 7931.9149962f, 6797.2799488f, 6842.794948f, 6888.3099489f, 6933.8249490f, 6979.3399491f, 7024.8549492f, 7252.4299497f, 7297.9449498f, 7343.4599499f, 7388.9749500f, 7434.489950f, 7480.0049501f, 7707.5799506f, 7753.0949507f, 7798.6099508f, 7844.1249509f, 7889.6399510f, 7935.1549511f, 8162.7299515f, 8208.2449516f, 8253.7599517f, 8299.2749518f, 8344.7899519f, 8390.3049520f, 8617.8799525f, 8663.394952f, 8708.9099526f, 8754.4249527f, 8799.9399528f, 8845.4549529f, 9073.0299534f, 9118.5449535f, 9164.0599536f, 9209.5749537f, 9255.089953f, 9300.604953f, 7792.2451647f, 7844.5551655f, 7896.8651663f, 7949.1751671f, 8001.4851679f, 8053.7951686f, 8315.3451725f, 8367.6551733f, 8419.9651741f, 8472.2751749f, 8524.585175f, 8576.8951764f, 8838.4451803f, 8890.7551811f, 8943.0651819f, 8995.3751827f, 9047.6851834f, 9099.9951842f, 9361.5451881f, 9413.8551889f, 9466.1651897f, 9518.475190f, 9570.7851912f, 9623.0951920f, 9884.6451959f, 9936.9551967f, 9989.2651975f, 10041.5751982f, 10093.8851990f, 10146.1951998f, 10407.7452037f, 10460.0552045f, 10512.3652053f, 10564.6752060f, 10616.9852068f, 10669.2952076f, 8787.210074f, 8846.3150748f, 8905.4200750f, 8964.5250752f, 9023.6300755f, 9082.7350757f, 9378.2600768f, 9437.3650770f, 9496.4700773f, 9555.5750775f, 9614.6800777f, 9673.7850779f, 9969.3100791f, 10028.4150793f, 10087.5200795f, 10146.625079f, 10205.7300800f, 10264.8350802f, 10560.3600813f, 10619.465081f, 10678.5700818f, 10737.6750820f, 10796.7800822f, 10855.8850825f, 11151.4100836f, 11210.5150838f, 11269.6200840f, 11328.7250843f, 11387.8300845f, 11446.9350847f, 11742.4600858f, 11801.5650861f, 11860.6700863f, 11919.7750865f, 11978.880086f, 12037.9850870f, 9782.1750935f, 9848.0750935f, 9913.9750934f, 9979.8750934f, 10045.7750934f, 10111.6750933f, 10441.1750931f, 10507.0750931f, 10572.9750931f, 10638.8750930f, 10704.7750930f, 10770.6750930f, 11100.1750928f, 11166.0750927f, 11231.9750927f, 11297.8750927f, 11363.7750926f, 11429.6750926f, 11759.1750924f, 11825.0750924f, 11890.9750923f, 11956.8750923f, 12022.7750923f, 12088.6750922f, 12418.175092f, 12484.0750920f, 12549.9750920f, 12615.8750919f, 12681.7750919f, 12747.6750919f, 13077.1750917f, 13143.0750916f, 13208.9750916f, 13274.8750916f, 13340.7750915f, 13406.6750915f, 2250.990060f, 2255.7350610f, 2260.4800611f, 2265.2250612f, 2269.9700613f, 2274.7150614f, 2298.4400619f, 2303.185062f, 2307.9300622f, 2312.6750623f, 2317.4200624f, 2322.1650625f, 2345.8900630f, 2350.6350631f, 2355.380063f, 2360.1250634f, 2364.8700635f, 2369.6150636f, 2393.3400641f, 2398.0850642f, 2402.8300643f, 2407.5750644f, 2412.320064f, 2417.0650647f, 2440.7900652f, 2445.5350653f, 2450.2800654f, 2455.0250655f, 2459.7700656f, 2464.515065f, 2488.2400663f, 2492.9850664f, 2497.7300665f, 2502.4750666f, 2507.2200667f, 2511.9650668f, 5284.4551315f, 5295.9951318f, 5307.535132f, 5319.0751323f, 5330.6151326f, 5342.1551328f, 5399.8551341f, 5411.3951343f, 5422.9351346f, 5434.475134f, 5446.0151351f, 5457.5551354f, 5515.2551366f, 5526.7951369f, 5538.3351371f, 5549.8751374f, 5561.4151376f, 5572.9551379f, 5630.6551392f, 5642.1951394f, 5653.7351397f, 5665.2751399f, 5676.8151402f, 5688.3551404f, 5746.0551417f, 5757.5951420f, 5769.1351422f, 5780.6751425f, 5792.2151427f, 5803.7551430f, 5861.455144f, 5872.9951445f, 5884.5351448f, 5896.0751450f, 5907.6151453f, 5919.1551455f, 8317.919884f, 8336.2548841f, 8354.5898838f, 8372.9248835f, 8391.2598832f, 8409.59488f, 8501.2698815f, 8519.6048813f, 8537.9398810f, 8556.2748807f, 8574.6098804f, 8592.9448801f, 8684.6198787f, 8702.9548784f, 8721.2898782f, 8739.6248779f, 8757.9598776f, 8776.2948773f, 8867.9698759f, 8886.3048756f, 8904.6398753f, 8922.9748751f, 8941.3098748f, 8959.6448745f, 9051.3198731f, 9069.6548728f, 9087.9898725f, 9106.3248722f, 9124.6598720f, 9142.9948717f, 9234.6698703f, 9253.0048700f, 9271.3398697f, 9289.6748694f, 9308.0098691f, 9326.3448689f, 11351.3852747f, 11376.5152753f, 11401.6452759f, 11426.7752765f, 11451.9052771f, 11477.0352777f, 11602.6852806f, 11627.8152812f, 11652.9452818f, 11678.0752824f, 11703.2052830f, 11728.335283f, 11853.9852865f, 11879.1152871f, 11904.2452877f, 11929.3752883f, 11954.505288f, 11979.6352894f, 12105.2852924f, 12130.4152930f, 12155.545293f, 12180.6752941f, 12205.8052947f, 12230.9352953f, 12356.5852983f, 12381.715298f, 12406.8452994f, 12431.9753000f, 12457.1053006f, 12482.2353012f, 12607.8853041f, 12633.0153047f, 12658.1453053f, 12683.2753059f, 12708.4053065f, 12733.5353071f, 14384.8499244f, 14416.7749242f, 14448.6999240f, 14480.6249238f, 14512.549923f, 14544.4749235f, 14704.0999225f, 14736.024922f, 14767.9499222f, 14799.8749220f, 14831.7999218f, 14863.7249216f, 15023.3499207f, 15055.2749205f, 15087.1999203f, 15119.1249201f, 15151.0499199f, 15182.9749197f, 15342.5999188f, 15374.5249186f, 15406.4499184f, 15438.374918f, 15470.2999181f, 15502.2249179f, 15661.84991f, 15693.7749168f, 15725.6999166f, 15757.6249164f, 15789.5499162f, 15821.4749160f, 15981.0999151f, 16013.0249149f, 16044.9499147f, 16076.8749145f, 16108.7999143f, 16140.7249142f, 17418.314976f, 17457.0349761f, 17495.7549760f, 17534.4749759f, 17573.1949758f, 17611.9149757f, 17805.5149753f, 17844.234975f, 17882.9549752f, 17921.6749751f, 17960.3949750f, 17999.1149749f, 18192.7149745f, 18231.4349744f, 18270.154974f, 18308.8749743f, 18347.5949742f, 18386.3149741f, 18579.9149737f, 18618.6349736f, 18657.3549735f, 18696.074973f, 18734.7949734f, 18773.5149733f, 18967.1149729f, 19005.8349728f, 19044.5549727f, 19083.2749726f, 19121.994972f, 19160.7149725f, 19354.3149721f, 19393.0349720f, 19431.7549719f, 19470.4749718f, 19509.1949717f, 19547.914971f, 20451.7799765f, 20497.2949766f, 20542.8099767f, 20588.3249768f, 20633.8399769f, 20679.3549770f, 20906.929977f, 20952.4449775f, 20997.9599776f, 21043.4749777f, 21088.9899778f, 21134.5049779f, 21362.0799784f, 21407.5949785f, 21453.1099786f, 21498.624978f, 21544.139978f, 21589.6549788f, 21817.2299793f, 21862.7449794f, 21908.2599795f, 21953.7749796f, 21999.2899797f, 22044.8049798f, 22272.3799802f, 22317.8949803f, 22363.4099804f, 22408.9249805f, 22454.4399806f, 22499.9549807f, 22727.529981f, 22773.044981f, 22818.5599813f, 22864.0749814f, 22909.5899815f, 22955.1049816f, 23485.2453985f, 23537.555399f, 23589.8654000f, 23642.1754008f, 23694.4854016f, 23746.7954024f, 24008.3454063f, 24060.655407f, 24112.9654078f, 24165.2754086f, 24217.5854094f, 24269.8954102f, 24531.4454141f, 24583.7554148f, 24636.0654156f, 24688.3754164f, 24740.6854172f, 24792.99541f, 25054.545421f, 25106.8554226f, 25159.1654234f, 25211.4754242f, 25263.7854250f, 25316.0954257f, 25577.6454296f, 25629.9554304f, 25682.2654312f, 25734.5754320f, 25786.8854328f, 25839.1954335f, 26100.7454374f, 26153.0554382f, 26205.3654390f, 26257.6754398f, 26309.985440f, 26362.2954413f, 26518.7101423f, 26577.8151425f, 26636.920142f, 26696.0251430f, 26755.1301432f, 26814.2351434f, 27109.7601446f, 27168.8651448f, 27227.9701450f, 27287.0751452f, 27346.1801455f, 27405.2851457f, 27700.8101468f, 27759.9151470f, 27819.0201473f, 27878.1251475f, 27937.2301477f, 27996.33514f, 28291.8601491f, 28350.9651493f, 28410.0701495f, 28469.175149f, 28528.2801500f, 28587.3851502f, 28882.9101513f, 28942.0151516f, 29001.1201518f, 29060.2251520f, 29119.3301522f, 29178.4351525f, 29473.9601536f, 29533.0651538f, 29592.1701540f, 29651.2751543f, 29710.3801545f, 29769.4851547f, 29552.1750826f, 29618.0750825f, 29683.9750825f, 29749.8750825f, 29815.7750824f, 29881.6750824f, 30211.1750822f, 30277.0750822f, 30342.9750821f, 30408.8750821f, 30474.7750821f, 30540.6750820f, 30870.175081f, 30936.0750818f, 31001.9750818f, 31067.8750817f, 31133.7750817f, 31199.6750817f, 31529.1750815f, 31595.075081f, 31660.9750814f, 31726.8750814f, 31792.7750813f, 31858.6750813f, 32188.1750811f, 32254.0750811f, 32319.975081f, 32385.8750810f, 32451.7750810f, 32517.6750809f, 32847.1750808f, 32913.0750807f, 32978.9750807f, 33044.875080f, 33110.7750806f, 33176.67508062}; Nd4jLong _exp2SFF[] = {4, 2, 10, 6, 6, 360, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray exp2FF(_exp2BFF, _exp2SFF); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {2, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 6, 1, 1}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); weightsP.applyScalar(scalar::Divide, 10000.0); nd4j::ops::sconv2d op; auto resultFF = op.execute({&input, &weightsD}, {}, {5, 5, 1, 1, 0, 0, 1, 1, 0}, {}); auto z = resultFF->at(0); ASSERT_TRUE(z->isSameShape(&expFF)); ASSERT_TRUE(z->equalsTo(&expFF, 1)); nd4j::ops::conv2d op2d; weightsP.printShapeInfo(); auto result2D = op2d.execute({z, &weightsP}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0, 0}, {}); auto z2d = result2D->at(0); ASSERT_TRUE(z2d->isSameShape(&exp2FF)); ASSERT_TRUE(z2d->equalsTo(&exp2FF)); delete resultFF; delete result2D; } TYPED_TEST(TypedConvolutionTests1, sconv2D_FF_pointwise_1) { TypeParam _expBFF[] = {108.9405008, 109.5920008, 110.2435008, 110.8950008, 111.5465008, 112.1980008, 115.4555008, 116.1070008, 116.7585008, 117.410000, 118.061500, 118.7130009, 121.9705009, 122.6220009, 123.2735009, 123.9250009, 124.5765009, 125.2280009, 128.4855009, 129.1370009, 129.7885009, 130.4400009, 131.09150, 131.74300, 135.0005010, 135.6520010, 136.3035010, 136.9550010, 137.6065010, 138.2580010, 141.5155010, 142.1670010, 142.8185010, 143.4700010, 144.1215010, 144.7730010, 248.9617514, 250.670751, 252.3797515, 254.0887515, 255.7977515, 257.5067515, 266.0517515, 267.7607515, 269.469751, 271.1787516, 272.8877516, 274.5967516, 283.1417516, 284.8507516, 286.5597516, 288.268751, 289.9777517, 291.6867517, 300.2317517, 301.9407517, 303.6497517, 305.3587517, 307.067751, 308.7767518, 317.3217518, 319.0307518, 320.7397518, 322.4487518, 324.157751, 325.866751, 334.4117519, 336.1207519, 337.8297519, 339.5387519, 341.2477519, 342.95675, 388.9829964, 391.7494964, 394.5159964, 397.2824964, 400.048996, 402.8154963, 416.647996, 419.4144962, 422.1809962, 424.9474962, 427.7139962, 430.4804962, 444.3129961, 447.0794961, 449.8459961, 452.6124960, 455.3789960, 458.1454960, 471.9779959, 474.7444959, 477.5109959, 480.2774959, 483.0439959, 485.8104958, 499.6429958, 502.4094957, 505.1759957, 507.9424957, 510.7089957, 513.4754957, 527.3079956, 530.0744956, 532.8409956, 535.607495, 538.3739955, 541.1404955, 529.0042487, 532.8282487, 536.6522487, 540.4762487, 544.3002487, 548.1242487, 567.2442487, 571.068248, 574.892248, 578.716248, 582.540248, 586.3642486, 605.4842486, 609.3082486, 613.1322486, 616.9562486, 620.7802486, 624.6042486, 643.7242486, 647.5482486, 651.3722486, 655.1962486, 659.0202486, 662.8442486, 681.9642486, 685.7882486, 689.6122486, 693.4362486, 697.2602486, 701.0842486, 720.2042486, 724.0282486, 727.852248, 731.676248, 735.500248, 739.324248, 669.0255044, 673.9070044, 678.7885044, 683.6700044, 688.5515044, 693.4330044, 717.8405044, 722.7220044, 727.6035044, 732.4850044, 737.3665044, 742.2480044, 766.6555043, 771.5370043, 776.4185043, 781.3000043, 786.1815043, 791.0630043, 815.4705043, 820.3520043, 825.2335043, 830.1150043, 834.9965043, 839.8780043, 864.2855042, 869.1670042, 874.0485042, 878.9300042, 883.8115042, 888.6930042, 913.1005042, 917.9820042, 922.8635042, 927.7450042, 932.6265042, 937.5080042, 809.0467424, 814.9857424, 820.9247424, 826.8637423, 832.8027423, 838.7417423, 868.4367421, 874.3757421, 880.3147420, 886.2537420, 892.1927420, 898.13174, 927.8267418, 933.7657418, 939.7047417, 945.6437417, 951.5827417, 957.5217416, 987.2167415, 993.155741, 999.0947414, 1005.0337414, 1010.972741, 1016.9117413, 1046.6067412, 1052.5457411, 1058.4847411, 1064.4237411, 1070.3627410, 1076.3017410, 1105.996740, 1111.9357408, 1117.8747408, 1123.8137408, 1129.7527407, 1135.6917407, 949.0679815, 956.0644814, 963.060981, 970.0574813, 977.0539812, 984.0504811, 1019.0329807, 1026.0294807, 1033.0259806, 1040.0224805, 1047.0189804, 1054.0154804, 1088.9979800, 1095.9944799, 1102.9909798, 1109.987479, 1116.9839797, 1123.9804796, 1158.9629792, 1165.9594791, 1172.9559791, 1179.9524790, 1186.9489789, 1193.9454788, 1228.9279785, 1235.9244784, 1242.9209783, 1249.9174782, 1256.913978, 1263.9104781, 1298.8929777, 1305.8894776, 1312.8859775, 1319.8824775, 1326.8789774, 1333.8754773, 1089.0892560, 1097.1432561, 1105.1972562, 1113.251256, 1121.3052563, 1129.3592564, 1169.6292568, 1177.6832568, 1185.7372569, 1193.7912570, 1201.845257, 1209.8992571, 1250.1692575, 1258.2232576, 1266.2772576, 1274.3312577, 1282.3852578, 1290.4392579, 1330.7092582, 1338.7632583, 1346.8172584, 1354.8712584, 1362.9252585, 1370.9792586, 1411.24925, 1419.3032590, 1427.3572591, 1435.4112592, 1443.465259, 1451.5192593, 1491.7892597, 1499.8432598, 1507.8972598, 1515.9512599, 1524.0052600, 1532.059260, 1229.1105073, 1238.2220073, 1247.3335073, 1256.4450073, 1265.5565073, 1274.668007, 1320.2255074, 1329.3370074, 1338.4485074, 1347.5600075, 1356.6715075, 1365.7830075, 1411.340507, 1420.4520076, 1429.5635076, 1438.6750076, 1447.7865076, 1456.8980076, 1502.4555077, 1511.5670077, 1520.6785077, 1529.7900077, 1538.9015077, 1548.013007, 1593.5705078, 1602.6820078, 1611.793507, 1620.9050079, 1630.0165079, 1639.1280079, 1684.6855080, 1693.7970080, 1702.9085080, 1712.0200080, 1721.1315080, 1730.2430080, 1369.1317613, 1379.3007614, 1389.4697614, 1399.6387615, 1409.8077615, 1419.976761, 1470.8217618, 1480.9907618, 1491.159761, 1501.3287619, 1511.4977619, 1521.6667620, 1572.5117622, 1582.6807622, 1592.8497623, 1603.0187623, 1613.1877624, 1623.3567624, 1674.2017626, 1684.3707627, 1694.5397627, 1704.7087628, 1714.8777628, 1725.046762, 1775.8917631, 1786.0607631, 1796.229763, 1806.3987632, 1816.5677632, 1826.7367633, 1877.5817635, 1887.7507635, 1897.9197636, 1908.0887636, 1918.2577637, 1928.4267637, 304.3905022, 305.0420022, 305.6935022, 306.3450022, 306.9965022, 307.6480022, 310.9055022, 311.5570022, 312.208502, 312.860002, 313.5115023, 314.1630023, 317.4205023, 318.0720023, 318.7235023, 319.3750023, 320.0265023, 320.6780023, 323.9355023, 324.5870023, 325.2385023, 325.8900023, 326.541502, 327.193002, 330.4505024, 331.1020024, 331.7535024, 332.4050024, 333.0565024, 333.7080024, 336.9655024, 337.6170024, 338.2685024, 338.9200024, 339.5715024, 340.223002, 761.6617542, 763.3707542, 765.0797542, 766.7887542, 768.4977542, 770.206754, 778.7517543, 780.4607543, 782.1697543, 783.8787543, 785.5877543, 787.2967543, 795.8417544, 797.5507544, 799.2597544, 800.9687544, 802.6777544, 804.3867544, 812.9317545, 814.6407545, 816.3497545, 818.0587545, 819.7677545, 821.4767545, 830.0217546, 831.7307546, 833.4397546, 835.1487546, 836.8577546, 838.5667546, 847.1117547, 848.8207547, 850.5297547, 852.2387547, 853.9477547, 855.6567547, 1218.9329915, 1221.6994915, 1224.4659915, 1227.232491, 1229.9989914, 1232.7654914, 1246.5979913, 1249.3644913, 1252.1309913, 1254.8974913, 1257.6639913, 1260.430491, 1274.2629912, 1277.029491, 1279.7959911, 1282.5624911, 1285.3289911, 1288.0954911, 1301.9279910, 1304.6944910, 1307.4609910, 1310.22749, 1312.9939909, 1315.7604909, 1329.5929908, 1332.3594908, 1335.1259908, 1337.8924908, 1340.6589908, 1343.4254908, 1357.2579907, 1360.0244907, 1362.7909906, 1365.5574906, 1368.3239906, 1371.0904906, 1676.2042479, 1680.0282479, 1683.8522479, 1687.6762479, 1691.5002479, 1695.3242479, 1714.4442479, 1718.2682479, 1722.0922479, 1725.9162479, 1729.7402479, 1733.5642479, 1752.6842479, 1756.5082479, 1760.3322479, 1764.1562479, 1767.9802479, 1771.8042479, 1790.9242479, 1794.7482479, 1798.5722479, 1802.3962479, 1806.2202479, 1810.044247, 1829.1642478, 1832.9882478, 1836.8122478, 1840.6362478, 1844.4602478, 1848.2842478, 1867.4042478, 1871.2282478, 1875.0522478, 1878.8762478, 1882.7002478, 1886.5242478, 2133.4755029, 2138.3570029, 2143.2385029, 2148.1200029, 2153.0015029, 2157.8830029, 2182.2905028, 2187.1720028, 2192.0535028, 2196.9350028, 2201.8165028, 2206.6980028, 2231.1055028, 2235.9870028, 2240.8685028, 2245.7500028, 2250.6315028, 2255.5130028, 2279.9205027, 2284.8020027, 2289.6835027, 2294.5650027, 2299.4465027, 2304.3280027, 2328.7355027, 2333.6170027, 2338.4985027, 2343.3800027, 2348.2615027, 2353.1430027, 2377.5505026, 2382.4320026, 2387.3135026, 2392.1950026, 2397.0765026, 2401.9580026, 2590.7467330, 2596.6857330, 2602.6247329, 2608.5637329, 2614.5027329, 2620.441732, 2650.1367327, 2656.0757327, 2662.0147326, 2667.9537326, 2673.8927326, 2679.8317325, 2709.5267324, 2715.465732, 2721.4047323, 2727.3437323, 2733.282732, 2739.2217322, 2768.9167321, 2774.8557320, 2780.7947320, 2786.7337320, 2792.6727319, 2798.6117319, 2828.306731, 2834.2457317, 2840.1847317, 2846.1237317, 2852.0627316, 2858.0017316, 2887.6967314, 2893.6357314, 2899.5747314, 2905.5137313, 2911.4527313, 2917.3917313, 3048.0179587, 3055.0144586, 3062.0109585, 3069.0074584, 3076.0039584, 3083.0004583, 3117.9829579, 3124.9794578, 3131.9759578, 3138.9724577, 3145.9689576, 3152.9654575, 3187.947957, 3194.9444571, 3201.9409570, 3208.9374569, 3215.933956, 3222.9304568, 3257.9129564, 3264.9094563, 3271.9059562, 3278.9024562, 3285.8989561, 3292.8954560, 3327.8779556, 3334.874455, 3341.8709555, 3348.8674554, 3355.8639553, 3362.860455, 3397.8429549, 3404.8394548, 3411.8359547, 3418.8324546, 3425.8289546, 3432.8254545, 3505.28927, 3513.3432780, 3521.3972781, 3529.4512782, 3537.5052782, 3545.5592783, 3585.8292787, 3593.8832788, 3601.9372788, 3609.9912789, 3618.0452790, 3626.099279, 3666.3692794, 3674.4232795, 3682.4772796, 3690.5312796, 3698.5852797, 3706.6392798, 3746.9092801, 3754.9632802, 3763.0172803, 3771.0712804, 3779.1252804, 3787.1792805, 3827.4492809, 3835.50328, 3843.5572810, 3851.6112811, 3859.6652812, 3867.7192812, 3907.9892816, 3916.0432817, 3924.097281, 3932.1512818, 3940.2052819, 3948.2592820, 3962.5605113, 3971.6720113, 3980.783511, 3989.8950114, 3999.0065114, 4008.1180114, 4053.6755115, 4062.7870115, 4071.8985115, 4081.0100115, 4090.1215115, 4099.2330115, 4144.7905116, 4153.9020116, 4163.0135116, 4172.1250116, 4181.236511, 4190.3480117, 4235.9055117, 4245.0170117, 4254.128511, 4263.2400118, 4272.3515118, 4281.4630118, 4327.0205119, 4336.1320119, 4345.2435119, 4354.3550119, 4363.4665119, 4372.5780119, 4418.1355120, 4427.2470120, 4436.3585120, 4445.4700120, 4454.581512, 4463.6930121, 4419.8317743, 4430.0007744, 4440.1697744, 4450.338774, 4460.5077745, 4470.6767745, 4521.521774, 4531.6907748, 4541.8597748, 4552.0287749, 4562.1977749, 4572.3667750, 4623.2117752, 4633.3807752, 4643.5497753, 4653.7187753, 4663.8877754, 4674.0567754, 4724.9017756, 4735.0707757, 4745.2397757, 4755.4087757, 4765.5777758, 4775.7467758, 4826.591776, 4836.7607761, 4846.9297761, 4857.0987762, 4867.2677762, 4877.4367763, 4928.2817765, 4938.4507765, 4948.6197766, 4958.7887766, 4968.957776, 4979.12677675}; Nd4jLong _expSFF[] = {4, 2, 10, 6, 6, 360, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray expFF(_expBFF, _expSFF); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {5, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 15, 1, 1}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); input.applyScalar(scalar::Divide, 100.0); weightsD.applyScalar(scalar::Divide, 100.0); weightsP.applyScalar(scalar::Divide, 100.0); nd4j::ops::sconv2d op; auto resultFF = op.execute({&input, &weightsD, &weightsP}, {}, {5, 5, 1, 1, 0, 0, 1, 1, 0, 0}, {}); auto z = resultFF->at(0); //z->printShapeInfo("FF shape"); ASSERT_TRUE(z->isSameShape(&expFF)); //expFF.printBuffer("e"); //z->printBuffer("z"); ASSERT_TRUE(z->equalsTo(&expFF, 1e-3)); delete resultFF; } TYPED_TEST(TypedConvolutionTests1, sconv2D_BP_pointwise_1) { TypeParam _expGradWpB[] = {1603.7102981f, 10645.6278024f, 5975.4227995f, 17697.0903052f, 12133.6353024f, 26535.0528052f, 1779.221097f, 11795.5686029f, 6721.9835994f, 19904.0811062f, 13775.2461029f, 30123.0936062f, 1954.7318976f, 12945.5094033f, 7468.5443993f, 22111.071907f, 15416.8569033f, 33711.134407f, 2130.2426974f, 14095.4502038f, 8215.1051992f, 24318.0627081f, 17058.4677038f, 37299.1752081f, 2305.7534972f, 15245.3910042f, 8961.6659991f, 26525.0535091f, 18700.0785042f, 40887.2160091f, 2481.2642970f, 16395.3318047f, 9708.2267991f, 28732.0443100f, 20341.6893047f, 44475.2568100f, 2656.7750968f, 17545.2726051f, 10454.7875990f, 30939.0351110f, 21983.3001051f, 48063.2976110f, 2832.2858966f, 18695.2134056f, 11201.3483989f, 33146.0259119f, 23624.9109056f, 51651.3384119f, 3007.7966964f, 19845.1542060f, 11947.9091988f, 35353.0167129f, 25266.5217060f, 55239.3792129f, 3183.3074962f, 20995.095006f, 12694.4699987f, 37560.007513f, 26908.132506f, 58827.4200139}; Nd4jLong _expGradWpS[] {4, 10, 6, 1, 1, 6, 1, 1, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expGWP(_expGradWpB, _expGradWpS); expGWP.permutei({2,3,1,0}); TypeParam _expGradWdB[] = {2074.21032f, 2082.76104f, 2091.31176f, 2099.86248f, 2108.4132f, 2159.71752f, 2168.26824f, 2176.81896f, 2185.36968f, 2193.9204f, 2245.22472f, 2253.77544f, 2262.32616f, 2270.87688f, 2279.4276f, 2330.73192f, 2339.28264f, 2347.83336f, 2356.38408f, 2364.9348f, 2416.23912f, 2424.78984f, 2433.34056f, 2441.89128f, 2450.442f, 3112.99344f, 3122.06328f, 3131.13312f, 3140.20296f, 3149.2728f, 3203.69184f, 3212.76168f, 3221.83152f, 3230.90136f, 3239.9712f, 3294.39024f, 3303.46008f, 3312.52992f, 3321.59976f, 3330.6696f, 3385.08864f, 3394.15848f, 3403.22832f, 3412.29816f, 3421.368f, 3475.78704f, 3484.85688f, 3493.92672f, 3502.99656f, 3512.0664f, 4255.60056f, 4265.18952f, 4274.77848f, 4284.36744f, 4293.9564f, 4351.49016f, 4361.07912f, 4370.66808f, 4380.25704f, 4389.846f, 4447.37976f, 4456.96872f, 4466.55768f, 4476.14664f, 4485.7356f, 4543.26936f, 4552.85832f, 4562.44728f, 4572.03624f, 4581.6252f, 4639.15896f, 4648.74792f, 4658.33688f, 4667.92584f, 4677.5148f, 2140.10988f, 2148.92016f, 2157.73044f, 2166.54072f, 2175.351f, 2228.21268f, 2237.02296f, 2245.83324f, 2254.64352f, 2263.4538f, 2316.31548f, 2325.12576f, 2333.93604f, 2342.74632f, 2351.5566f, 2404.41828f, 2413.22856f, 2422.03884f, 2430.84912f, 2439.6594f, 2492.52108f, 2501.33136f, 2510.14164f, 2518.95192f, 2527.7622f, 3204.849f, 3214.1784f, 3223.5078f, 3232.8372f, 3242.1666f, 3298.143f, 3307.4724f, 3316.8018f, 3326.1312f, 3335.4606f, 3391.437f, 3400.7664f, 3410.0958f, 3419.4252f, 3428.7546f, 3484.731f, 3494.0604f, 3503.3898f, 3512.7192f, 3522.0486f, 3578.025f, 3587.3544f, 3596.6838f, 3606.0132f, 3615.3426f, 4373.41212f, 4383.26064f, 4393.10916f, 4402.95768f, 4412.8062f, 4471.89732f, 4481.74584f, 4491.59436f, 4501.44288f, 4511.2914f, 4570.38252f, 4580.23104f, 4590.07956f, 4599.92808f, 4609.7766f, 4668.86772f, 4678.71624f, 4688.56476f, 4698.41328f, 4708.2618f, 4767.35292f, 4777.20144f, 4787.04996f, 4796.89848f, 4806.747}; Nd4jLong _expGradWdS[] = {4, 2, 3, 5, 5, 75, 25, 5, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expGWD(_expGradWdB, _expGradWdS); expGWD.permutei({2,3,1,0}); TypeParam _expEB[] = {5.0103f, 10.17147f, 15.48408f, 20.9487f, 26.5659f, 26.6832f, 21.65628f, 16.47507f, 11.139f, 5.6475f, 10.79727f, 21.90255f, 33.31698f, 45.0417f, 57.07785f, 57.3267f, 46.49334f, 35.34513f, 23.88093f, 12.0996f, 17.37801f, 35.22744f, 53.55f, 72.3474f, 91.62135f, 92.016f, 74.57958f, 56.66148f, 38.25999f, 19.3734f, 24.76962f, 50.18034f, 76.23444f, 102.9342f, 130.2819f, 130.8366f, 105.9834f, 80.47542f, 54.31038f, 27.486f, 32.9892f, 66.79545f, 101.4216f, 136.8705f, 173.145f, 173.874f, 140.7732f, 106.83825f, 72.0663f, 36.4545f, 33.8298f, 68.49375f, 103.9947f, 140.3355f, 177.519f, 178.248f, 144.3066f, 109.51395f, 73.8672f, 37.3635f, 28.85658f, 58.39302f, 88.6116f, 119.5146f, 151.1043f, 151.716f, 122.76444f, 93.11934f, 62.77842f, 31.7394f, 23.00409f, 46.52748f, 70.57188f, 95.139f, 120.23055f, 120.7107f, 97.6311f, 74.02194f, 49.88151f, 25.2081f, 16.25523f, 32.86293f, 49.82424f, 67.1403f, 84.81225f, 85.1466f, 68.83818f, 52.17045f, 35.14227f, 17.7525f, 8.5929f, 17.36517f, 26.31738f, 35.4501f, 44.7639f, 44.9382f, 36.31728f, 27.51357f, 18.5265f, 9.3555f, 8.63807f, 17.45032f, 26.43736f, 35.5998f, 44.93825f, 45.1399f, 36.46882f, 27.6199f, 18.59253f, 9.3861f, 18.18615f, 36.72737f, 55.62488f, 74.8799f, 94.49365f, 94.9122f, 76.65698f, 58.03937f, 39.05815f, 19.7121f, 28.66254f, 57.86775f, 87.61746f, 117.9135f, 148.7577f, 149.4084f, 120.63768f, 91.31331f, 61.43346f, 30.9963f, 40.08554f, 80.90806f, 122.47f, 164.7738f, 207.8219f, 208.72f, 168.48412f, 127.49662f, 85.75506f, 43.257f, 52.47345f, 105.8849f, 160.2374f, 215.534f, 271.77775f, 272.9385f, 220.2695f, 166.6442f, 112.05955f, 56.5125f, 53.82975f, 108.6158f, 164.3612f, 221.069f, 278.74225f, 279.903f, 225.8777f, 170.8778f, 114.90025f, 57.942f, 45.14002f, 91.0585f, 137.75788f, 185.2406f, 233.5091f, 234.4682f, 189.16564f, 143.06998f, 96.17878f, 48.4896f, 35.43048f, 71.45487f, 108.075f, 145.2927f, 183.1098f, 183.852f, 148.29504f, 112.13319f, 75.36462f, 37.9875f, 24.68283f, 49.76831f, 75.25766f, 101.1521f, 127.45285f, 127.9629f, 103.1927f, 78.01253f, 52.42117f, 26.4174f, 12.87877f, 25.96222f, 39.25096f, 52.7456f, 66.44675f, 66.7094f, 53.78542f, 40.6531f, 27.31183f, 13.761f, 12.59184f, 25.38317f, 38.37464f, 51.5669f, 64.9606f, 65.2566f, 52.61336f, 39.76673f, 26.71606f, 13.4607f, 26.23903f, 52.88419f, 79.93678f, 107.3981f, 135.26945f, 135.8777f, 109.53262f, 82.77361f, 55.59937f, 28.0086f, 40.96107f, 82.54206f, 124.74492f, 167.5716f, 211.02405f, 211.9608f, 170.83578f, 129.07914f, 86.68893f, 43.6632f, 56.77746f, 114.39578f, 172.85756f, 232.1654f, 292.3219f, 293.6034f, 236.60084f, 178.74182f, 120.02374f, 60.444f, 73.7077f, 148.48435f, 224.3332f, 301.2575f, 379.2605f, 380.903f, 306.9058f, 231.82015f, 155.6428f, 78.3705f, 75.6397f, 152.36785f, 230.1877f, 309.1025f, 389.1155f, 390.758f, 314.8288f, 237.79165f, 159.6433f, 80.3805f, 62.89546f, 126.67598f, 191.34416f, 256.9026f, 323.3539f, 324.7004f, 261.56684f, 197.53262f, 132.59514f, 66.7518f, 48.97887f, 98.63226f, 148.96212f, 199.9704f, 251.65905f, 252.6933f, 203.53098f, 153.68244f, 103.14573f, 51.9189f, 33.87043f, 68.19769f, 102.98308f, 138.2279f, 173.93345f, 174.6392f, 140.64322f, 106.18261f, 71.25607f, 35.8623f, 17.55064f, 35.33327f, 53.34854f, 71.5971f, 90.0796f, 90.4406f, 72.82556f, 54.97463f, 36.88716f, 18.5625f, 13.0455f, 26.44707f, 40.20528f, 54.3207f, 68.7939f, 68.9112f, 55.84908f, 42.42747f, 28.6458f, 14.5035f, 27.89367f, 56.50575f, 85.83738f, 115.8897f, 146.66385f, 146.9127f, 118.98294f, 90.32793f, 60.94653f, 30.8376f, 44.56161f, 90.21024f, 136.9476f, 184.7754f, 233.69535f, 234.09f, 189.46998f, 143.75268f, 96.93639f, 49.0194f, 63.06642f, 127.59474f, 193.58724f, 261.0462f, 329.9739f, 330.5286f, 267.3786f, 202.75302f, 136.64958f, 69.066f, 83.4252f, 168.69345f, 255.8076f, 344.7705f, 435.585f, 436.314f, 352.7772f, 267.38025f, 180.1203f, 90.9945f, 84.2658f, 170.39175f, 258.3807f, 348.2355f, 439.959f, 440.688f, 356.3106f, 270.05595f, 181.9212f, 91.9035f, 71.25738f, 144.01542f, 218.2764f, 294.0426f, 371.3163f, 371.928f, 300.57564f, 227.70894f, 153.32562f, 77.4234f, 56.34369f, 113.82228f, 172.43748f, 232.191f, 293.08455f, 293.5647f, 237.1455f, 179.58114f, 120.86991f, 61.0101f, 39.50763f, 79.77813f, 120.81264f, 162.6123f, 205.17825f, 205.5126f, 165.95178f, 125.62125f, 84.51987f, 42.6465f, 20.7321f, 41.84877f, 63.35058f, 85.2381f, 107.5119f, 107.6862f, 86.92608f, 65.77797f, 44.2413f, 22.3155f, 22.71767f, 45.82912f, 69.33496f, 93.2358f, 117.53225f, 117.7339f, 94.98322f, 71.8351f, 48.28893f, 24.3441f, 47.44335f, 95.68097f, 144.71408f, 194.5439f, 245.17165f, 245.5902f, 198.07778f, 149.76377f, 100.64695f, 50.7261f, 74.19534f, 149.59215f, 226.19226f, 303.9975f, 383.0097f, 383.6604f, 309.35688f, 233.84091f, 157.11066f, 79.1643f, 102.99194f, 207.59926f, 313.8244f, 421.6698f, 531.1379f, 532.036f, 428.89372f, 324.12142f, 217.71666f, 109.677f, 133.85145f, 269.7389f, 407.6654f, 547.634f, 689.64775f, 690.8085f, 556.7615f, 420.6602f, 282.50155f, 142.2825f, 135.20775f, 272.4698f, 411.7892f, 553.169f, 696.61225f, 697.773f, 562.3697f, 424.8938f, 285.34225f, 143.712f, 112.43842f, 226.5337f, 342.28828f, 459.7046f, 578.7851f, 579.7442f, 467.14324f, 352.87078f, 236.92438f, 119.3016f, 87.55128f, 176.35527f, 266.4138f, 357.7287f, 450.3018f, 451.044f, 363.36624f, 274.42479f, 184.21782f, 92.7435f, 60.52803f, 121.89791f, 184.11086f, 247.1681f, 311.07085f, 311.5809f, 250.9655f, 189.50093f, 127.18597f, 64.0194f, 31.35037f, 63.12502f, 95.32456f, 127.9496f, 161.00075f, 161.2634f, 129.86782f, 98.0443f, 65.79223f, 33.111f, 33.43584f, 67.30517f, 101.60864f, 136.3469f, 171.5206f, 171.8166f, 138.32936f, 104.40473f, 70.04206f, 35.2407f, 69.09703f, 139.06819f, 209.91478f, 281.6381f, 354.23945f, 354.8477f, 285.64462f, 215.55961f, 144.59137f, 72.7386f, 107.00307f, 215.32806f, 324.97692f, 435.9516f, 548.25405f, 549.1908f, 442.02378f, 333.52314f, 223.68693f, 112.5132f, 147.17346f, 296.12378f, 446.85356f, 599.3654f, 753.6619f, 754.9434f, 607.54484f, 458.35382f, 307.36774f, 154.584f, 189.6277f, 381.49435f, 575.6032f, 771.9575f, 970.5605f, 972.203f, 782.2858f, 590.11015f, 395.6728f, 198.9705f, 191.5597f, 385.37785f, 581.4577f, 779.8025f, 980.4155f, 982.058f, 790.2088f, 596.08165f, 399.6733f, 200.9805f, 157.97146f, 317.76398f, 479.38016f, 642.8226f, 808.0939f, 809.4404f, 651.23084f, 491.18462f, 329.29914f, 165.5718f, 122.04087f, 245.45826f, 370.25412f, 496.4304f, 623.98905f, 625.0233f, 502.79898f, 379.18644f, 254.18373f, 127.7889f, 83.74843f, 168.42169f, 254.02108f, 340.5479f, 428.00345f, 428.7092f, 344.83522f, 260.02861f, 174.28807f, 87.6123f, 43.07464f, 86.61527f, 130.62254f, 175.0971f, 220.0396f, 220.4006f, 177.26156f, 133.65263f, 89.57316f, 45.0225f }; Nd4jLong _expES[] = {4, 2, 3, 10, 10, 300, 100, 10, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expE(_expEB, _expES); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {2, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 6, 1, 1}); auto epsilon = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 10, 6, 6}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); epsilonNext.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); input.applyScalar(scalar::Divide, 100.0); weightsD.applyScalar(scalar::Divide, 100.0); weightsP.applyScalar(scalar::Divide, 100.0); epsilonNext.applyScalar(scalar::Divide, 100.0); nd4j::ops::sconv2d_bp op; auto resultBP = op.execute({&input, &epsilonNext, &weightsD, &weightsP },{}, {5, 5, 1, 1, 0, 0, 1, 1, 0}, {}); ASSERT_EQ(3, resultBP->size()); auto _epsilon = resultBP->at(0); auto _gradWD = resultBP->at(1); auto _gradWP = resultBP->at(2); //_gradWP->printBuffer("gradWP"); ASSERT_TRUE(_gradWP->isSameShape(&expGWP)); ASSERT_TRUE(_gradWP->isSameShape(&weightsP)); ASSERT_TRUE(_gradWP->equalsTo(&expGWP)); //_gradWD->printShapeInfo("gradWD shape"); ASSERT_TRUE(_gradWD->isSameShape(&expGWD)); ASSERT_TRUE(_gradWD->isSameShape(&weightsD)); // _gradWD->printIndexedBuffer(); ASSERT_TRUE(_gradWD->equalsTo(&expGWD)); ASSERT_TRUE(_epsilon->isSameShape(&input)); ASSERT_TRUE(_epsilon->isSameShape(&expE)); ASSERT_TRUE(_epsilon->equalsTo(&expE)); delete resultBP; } TYPED_TEST(TypedConvolutionTests1, TestSconvCrash_max_1) { auto input = NDArrayFactory::create<TypeParam>('c', {3, 3, 8, 8}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {1, 3, 1, 1}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {2, 3, 1, 1}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 2}); auto output = NDArrayFactory::create<TypeParam>('c', {3, 2, 8, 8}); output.assign(0.0); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); bias.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {3, 2, 8, 8}); nd4j::ops::sconv2d op; Nd4jStatus status = op.execute({&input, &weightsD, &weightsP, &bias}, {&output}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0}, {}); auto result = op.execute({&input, &weightsD, &weightsP, &bias}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0}, {}); auto z = result->at(0); //printf("\n"); //output.printBuffer("output"); //z->printBuffer("z"); //ASSERT_TRUE(expOutput.isSameShape(z)); delete result; } TEST_F(ConvolutionTests1, Test_im2col_col2im_1) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; x.syncToDevice(); //ASSERT_TRUE(x.isActualOnDeviceSide()); ASSERT_TRUE(x.isActualOnHostSide()); //x.printBuffer("x", 64); nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, kY, kX, oY, oX}); ExtraArguments args({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args); nd4j::ops::im2col op; auto result2col = op.execute({&x}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}); auto im2col1 = result2col->at(0); //im2col0.printBuffer("transformed"); //im2col1->printBuffer("customized", 64); ASSERT_TRUE(im2col1->isSameShape(&im2col0)); ASSERT_TRUE(im2col1->equalsTo(&im2col0)); ExtraArguments args2({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2); nd4j::ops::col2im op2im; auto result2im = op2im.execute({im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2col; delete result2im; } TEST_F(ConvolutionTests1, Test_im2col_col2im_2) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col0.permutei({0, 1, 4, 5, 2, 3}); ExtraArguments args2col({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args2col); nd4j::ops::im2col op; auto result2col = op.execute({&x}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}); auto im2col1 = result2col->at(0); ASSERT_TRUE(im2col1->isSameShape(&im2col0)); ASSERT_TRUE(im2col1->equalsTo(&im2col0)); ExtraArguments args2im({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2im); nd4j::ops::col2im op2im; auto result2im = op2im.execute({im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2col; delete result2im; } TEST_F(ConvolutionTests1, Test_im2col_col2im_3) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col0.permutei({0, 1, 4, 5, 2, 3}); auto im2col1 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col1.permutei({0, 1, 4, 5, 2, 3}); ExtraArguments args2col({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args2col); nd4j::ops::im2col op; auto status = op.execute({&x}, {&im2col1}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}, {}); ASSERT_EQ(Status::OK(), status); ASSERT_TRUE(im2col1.isSameShape(&im2col0)); ASSERT_TRUE(im2col1.equalsTo(&im2col0)); ExtraArguments args2im({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2im); nd4j::ops::col2im op2im; auto result2im = op2im.execute({&im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2im; } TYPED_TEST(TypedConvolutionTests1, TestSconvCrash_max_2) { auto input = NDArrayFactory::create<TypeParam>('c', {3, 3, 16, 16}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {1, 3, 2, 2}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {2, 3, 1, 1}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 2}); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {3, 2, 14, 14}); auto epsilon = NDArrayFactory::create<TypeParam>('c', {3, 3, 16, 16}); nd4j::ops::sconv2d_bp op; auto result = op.execute({&input, &epsilonNext, &weightsD, &weightsP}, {}, {2, 2, 1, 1, 0, 0, 2, 2, 0}); auto eps = result->at(0); auto gWD = result->at(1); auto gWP = result->at(2); ASSERT_TRUE(epsilon.isSameShape(eps)); delete result; } TEST_F(ConvolutionTests1, TestDeconv_bp_1) { double _expb[] = { 35.f, 38.f, 41.f, 44.f, 47.f, 50.f, 53.f, 56.f, 59.f, 62.f, 65.f, 68.f, 71.f, 74.f, 77.f, 80.f, 71.f, 78.f, 85.f, 92.f, 99.f, 106.f, 113.f, 120.f, 127.f, 134.f, 141.f, 148.f, 155.f, 162.f, 169.f, 176.f, 107.f, 118.f, 129.f, 140.f, 151.f, 162.f, 173.f, 184.f, 195.f, 206.f, 217.f, 228.f, 239.f, 250.f, 261.f, 272.f, 131.f, 134.f, 137.f, 140.f, 143.f, 146.f, 149.f, 152.f, 155.f, 158.f, 161.f, 164.f, 167.f, 170.f, 173.f, 176.f, 295.f, 302.f, 309.f, 316.f, 323.f, 330.f, 337.f, 344.f, 351.f, 358.f, 365.f, 372.f, 379.f, 386.f, 393.f, 400.f, 459.f, 470.f, 481.f, 492.f, 503.f, 514.f, 525.f, 536.f, 547.f, 558.f, 569.f, 580.f, 591.f, 602.f, 613.f, 624.f, 227.f, 230.f, 233.f, 236.f, 239.f, 242.f, 245.f, 248.f, 251.f, 254.f, 257.f, 260.f, 263.f, 266.f, 269.f, 272.f, 519.f, 526.f, 533.f, 540.f, 547.f, 554.f, 561.f, 568.f, 575.f, 582.f, 589.f, 596.f, 603.f, 610.f, 617.f, 624.f, 811.f, 822.f, 833.f, 844.f, 855.f, 866.f, 877.f, 888.f, 899.f, 910.f, 921.f, 932.f, 943.f, 954.f, 965.f, 976.f}; std::shared_ptr<DataBuffer> pBuffer1 = std::make_shared<DataBuffer>(_expb, sizeof(_expb), nd4j::DataType::DOUBLE, false); NDArray expEpsilon(pBuffer1, 'c', {3, 3, 4, 4}); double _expwb[] = { 160008.f, 203400.f, 191112.f, 246792.f, 222216.f, 290184.f}; std::shared_ptr<DataBuffer> pBuffer2 = std::make_shared<DataBuffer>(_expwb, sizeof(_expwb), nd4j::DataType::DOUBLE, false); NDArray expGradW(pBuffer2, 'c', {3, 2, 1, 1}); expGradW.permutei({2,3,1,0}); double _expbb[] = {1944.f, 2712.f}; std::shared_ptr<DataBuffer> pBuffer3 = std::make_shared<DataBuffer>(_expbb, sizeof(_expbb), nd4j::DataType::DOUBLE, false); NDArray expGradB(pBuffer3, 'c', {1, 2}); auto input = NDArrayFactory::create<double>('c', {3, 3, 4, 4}); auto bias = NDArrayFactory::create<double>('c', {1, 2}); auto weights = NDArrayFactory::create<double>('c',{3, 2, 1, 1}); auto epsilon = NDArrayFactory::create<double>('c', {3, 2, 4, 4}); /* Input shape (3, 3, 4, 4) Weights shape (3, 2, 1, 1) Epsilon shape (3, 2, 4, 4) */ input.linspace(1); weights.linspace(1); bias.linspace(1); epsilon.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::deconv2d_bp op; auto result = op.execute({&input, &weights, &bias, &epsilon}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto expNext = result->at(0); ASSERT_TRUE(expEpsilon.isSameShape(expNext)); ASSERT_TRUE(expEpsilon.equalsTo(expNext)); auto gradW = result->at(1); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); auto gradB = result->at(2); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete result; } TEST_F(ConvolutionTests1, TestDeconv_bp_2) { /* Input shape: [3, 3, 14, 14] Output shape: [3, 2, 15, 15] Weights shape: [3, 2, 2, 2] Bias shape: [1, 2] weight shape: [3, 2, 2, 2] weight grad shape: [3, 2, 2, 2] bias grad shape: [2] input epsilon shape: [3, 2, 15, 15] output epsilon shape: [3, 3, 14, 14] */ /* auto input('c', {3, 3, 14, 14}); auto bias('c', {2}); auto weights('c',{3, 2, 2, 2}); auto epsilon('c', {3, 2, 15, 15}); input.linspace(1); weights.linspace(1); bias.linspace(1); epsilon.linspace(1); nd4j::ops::deconv2d_bp<double> op; auto result = op.execute({&input, &weights, &bias, &epsilon}, {}, {2, 2, 1, 1, 0, 0, 2, 2, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); delete result;*/ } TEST_F(ConvolutionTests1, TestDeconv_ff_2) { double expB[] = {218.f, 227.f, 236.f, 245.f, 254.f, 263.f, 272.f, 281.f, 290.f, 299.f, 308.f, 317.f, 326.f, 335.f, 344.f, 353.f, 270.f, 282.f, 294.f, 306.f, 318.f, 330.f, 342.f, 354.f, 366.f, 378.f, 390.f, 402.f, 414.f, 426.f, 438.f, 450.f, 650.f, 659.f, 668.f, 677.f, 686.f, 695.f, 704.f, 713.f, 722.f, 731.f, 740.f, 749.f, 758.f, 767.f, 776.f, 785.f, 846.f, 858.f, 870.f, 882.f, 894.f, 906.f, 918.f, 930.f, 942.f, 954.f, 966.f, 978.f, 990.f, 1002.f, 1014.f, 1026.f, 1082.f, 1091.f, 1100.f, 1109.f, 1118.f, 1127.f, 1136.f, 1145.f, 1154.f, 1163.f, 1172.f, 1181.f, 1190.f, 1199.f, 1208.f, 1217.f, 1422.f, 1434.f, 1446.f, 1458.f, 1470.f, 1482.f, 1494.f, 1506.f, 1518.f, 1530.f, 1542.f, 1554.f, 1566.f, 1578.f, 1590.f, 1602.f,}; std::shared_ptr<DataBuffer> buffer = std::make_shared<DataBuffer>(expB, sizeof(double), nd4j::DataType::DOUBLE, false); NDArray exp(buffer, 'c', {3, 2, 4, 4}); auto input = NDArrayFactory::create<double>('c', {3, 3, 4, 4}); auto weights = NDArrayFactory::create<double>('c',{3, 2, 1, 1}); auto bias = NDArrayFactory::create<double>('c', {1, 2}); input.linspace(1); weights.linspace(1); bias.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::deconv2d op; auto result = op.execute({&input, &weights, &bias}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } TYPED_TEST(TypedConvolutionTests1, Test_Conv1D_ff_1) { auto input = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 2, 3}, {1,5,9,3,7,11,2,6,10,4,8,12}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 3}); auto expFF = NDArrayFactory::create<TypeParam>('c', {2, 3, 5}, {59.0, 69.0, 79.0, 89.0, 99.0, 132.0, 158.0, 184.0, 210.0, 236.0, 205.0, 247.0, 289.0, 331.0, 373.0, 179.0, 189.0, 199.0, 209.0, 219.0, 444.0, 470.0, 496.0, 522.0, 548.0, 709.0, 751.0, 793.0, 835.0, 877.0}); auto expEps = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}, {130.0, 293.0, 326.0, 359.0, 392.0, 220.0, 166.0, 371.0, 416.0, 461.0, 506.0, 280.0, 355.0, 788.0, 821.0, 854.0, 887.0, 490.0, 481.0, 1046.0, 1091.0, 1136.0, 1181.0, 640.0}); auto expGW = NDArrayFactory::create<TypeParam>('c', {3, 2, 2}, {1415.0, 1520.0, 2045.0, 2150.0, 1865.0, 2020.0, 2795.0, 2950.0, 2315.0, 2520.0, 3545.0, 3750.0}); auto expGB = NDArrayFactory::create<TypeParam>('c', {1, 3}, {105.0, 155.0, 205.0}); expGW.permutei({2,1,0}); input.linspace(1); bias.linspace(1); nd4j::ops::conv1d op; auto result_FF = op.execute({&input, &weights, &bias}, {}, {2, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result_FF->status()); auto z = result_FF->at(0); ASSERT_TRUE(expFF.isSameShape(z)); ASSERT_TRUE(expFF.equalsTo(z)); nd4j::ops::conv1d_bp op_bp; auto epsilonNxt = z->dup(); epsilonNxt->linspace(1); auto result_BP = op_bp.execute({&input, &weights, &bias, epsilonNxt}, {}, {2, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result_BP->status()); auto eps = result_BP->at(0); auto gradW = result_BP->at(1); auto gradB = result_BP->at(2); ASSERT_TRUE(expEps.isSameShape(eps)); ASSERT_TRUE(expGW.isSameShape(gradW)); ASSERT_TRUE(expGB.isSameShape(gradB)); ASSERT_TRUE(expEps.equalsTo(eps)); ASSERT_TRUE(expGW.equalsTo(gradW)); ASSERT_TRUE(expGB.equalsTo(gradB)); delete result_FF; delete result_BP; delete epsilonNxt; } TYPED_TEST(TypedConvolutionTests1, Test_Conv1D_ff_2) { auto input = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 2, 3}, {1,5,9,3,7,11,2,6,10,4,8,12}); input.linspace(1); nd4j::ops::conv1d op; auto result = op.execute({&input, &weights}, {}, {2, 1, 0, 1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto z = result->at(0); delete result; } TYPED_TEST(TypedConvolutionTests1, Test_Conv2D_4_1) { auto input = NDArrayFactory::create<TypeParam>('c', {1, 1, 1, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {1, 1, 1, 4}); auto exp = NDArrayFactory::create<TypeParam>('c', {1, 4, 1, 4}, {2., 4., 6., 8., 2., 4., 6., 8., 2., 4., 6., 8., 2., 4., 6., 8.}); weights.assign(2.0); input.linspace(1); nd4j::ops::conv2d op; auto result = op.execute({&input, &weights}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, Test_Dilation2D_1) { auto input = NDArrayFactory::create<double>('c', {2, 6, 6, 3}); auto weights = NDArrayFactory::create<double>('c', {3, 2, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 3, 3, 3}, {77, 79, 81, 83, 85, 87, 80, 82, 84, 113, 115, 117, 119, 121, 123, 116, 118, 120, 107, 109, 111, 113, 115, 117, 110, 112, 114, 185, 187, 189, 191, 193, 195, 188, 190, 192, 221, 223, 225, 227, 229, 231, 224, 226, 228, 215, 217, 219, 221, 223, 225, 218, 220, 222,}); input.linspace(1); weights.linspace(1); nd4j::ops::dilation2d op; auto result = op.execute({&input, &weights}, {}, {1, 1,2,2,1, 1,2,2,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, Test_Dilation2D_2) { auto input = NDArrayFactory::create<double>('c', {2, 6, 6, 3}); auto weights = NDArrayFactory::create<double>('c', {3, 2, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 1, 2, 3}, {95, 97, 99, 101, 103, 105, 203, 205, 207, 209, 211, 213}); input.linspace(1); weights.linspace(1); nd4j::ops::dilation2d op; auto result = op.execute({&input, &weights}, {}, {0, 1,2,2,1, 1,2,2,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{ 0.226, 0.343, 0.46 , 0.577, 1.172, 1.46 , 1.748, 2.036, 1.892, 2.288, 2.684, 3.08 , 1.284, 1.581, 1.878, 2.175, 4.458, 5.133, 5.808, 6.483, 6.186, 7.023, 7.86 , 8.697, 3.39 , 3.93 , 4.47 , 5.01 , 9.642, 10.803, 11.964, 13.125,11.37 , 12.693, 14.016, 15.339, 5.266, 5.707, 6.148, 6.589,12.98 , 13.916, 14.852, 15.788,14.564, 15.608, 16.652, 17.696, 3.25 , 4.015, 4.78 , 5.545, 9.812, 11.396, 12.98 , 14.564,10.532, 12.224, 13.916, 15.608, 9.708, 10.977, 12.246, 13.515,25.194, 27.813, 30.432, 33.051,26.922, 29.703, 32.484, 35.265, 11.814, 13.326, 14.838, 16.35 ,30.378, 33.483, 36.588, 39.693,32.106, 35.373, 38.64 , 41.907,13.474, 14.563, 15.652, 16.741,31.988, 34.22 , 36.452, 38.684,33.572, 35.912, 38.252, 40.592}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC},{14.4 , 14.76, 15.12,14.4 , 14.76, 15.12,14.4 , 14.76, 15.12,14.4 , 14.76, 15.12, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 17.04, 17.52, 18. ,17.04, 17.52, 18. ,17.04, 17.52, 18. ,17.04, 17.52, 18. ,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52, 11.16, 11.52, 11.88,11.16, 11.52, 11.88,11.16, 11.52, 11.88,11.16, 11.52, 11.88, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test2) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{ 0.014,0.032, 0.05 , 0.068,0.118,0.181, 0.244, 0.307,0.212,0.257, 0.302, 0.347,0.208,0.298, 0.388, 0.478,1.028,1.262, 1.496, 1.73 ,1.036,1.18 , 1.324, 1.468, 0.928,1.018, 1.108, 1.198,2.9 ,3.134, 3.368, 3.602,2.188,2.332, 2.476, 2.62 ,1.202,1.274, 1.346, 1.418,3.142,3.313, 3.484, 3.655,2.048,2.147, 2.246, 2.345, 0.086,0.212, 0.338, 0.464,0.694,0.973, 1.252, 1.531,0.716,0.869, 1.022, 1.175,1.216,1.522, 1.828, 2.134,3.908,4.574, 5.24 , 5.906,2.908,3.268, 3.628, 3.988, 3.664,3.97 , 4.276, 4.582,9.236,9.902,10.568,11.234,5.788,6.148, 6.508, 6.868,3.002,3.182, 3.362, 3.542,7.174,7.561, 7.948, 8.335,4.28 ,4.487, 4.694, 4.901}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC},{1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16, 1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16, 1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test3) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oC, oH, oW}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW},{ 0.567, 1.224,0.66 ,1.314, 2.82 ,1.512,1.386, 2.976,1.596,0.801, 1.71 ,0.912,0.657, 1.422,0.768,1.53 , 3.288,1.764,1.602, 3.444,1.848,0.927, 1.98 ,1.056, 0.747, 1.62 ,0.876,1.746, 3.756,2.016,1.818, 3.912,2.1 ,1.053, 2.25 ,1.2 ,0.837, 1.818,0.984,1.962, 4.224,2.268,2.034, 4.38 ,2.352,1.179, 2.52 ,1.344, 1.467, 3.06 ,1.596,3.186, 6.636,3.456,3.402, 7.08 ,3.684,1.845, 3.834,1.992,1.773, 3.69 ,1.92 ,3.834, 7.968,4.14 ,4.05 , 8.412,4.368,2.187, 4.536,2.352, 2.079, 4.32 ,2.244,4.482, 9.3 ,4.824,4.698, 9.744,5.052,2.529, 5.238,2.712,2.385, 4.95 ,2.568,5.13 ,10.632,5.508,5.346,11.076,5.736,2.871, 5.94 ,3.072}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW},{1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00, 1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00, 2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00, 2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00}); auto expGradB = NDArrayFactory::create<TypeParam>('c', {oC},{0.68, 1., 1.32}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); weights.permutei({2,3,1,0}); expGradW.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); auto gradB = results->at(2); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{ 152. , 155.2, 158.4,152. , 155.2, 158.4, 66.4, 68. , 69.6,170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2, 152. , 155.2, 158.4,152. , 155.2, 158.4, 66.4, 68. , 69.6,170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test2) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{ 170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test3) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oC, oH, oW}, {61. , 61. , 61. , 61. ,177.2, 177.2,177.2, 177.2,293.4, 293.4,293.4, 293.4, 61. , 61. , 61. , 61. ,177.2, 177.2,177.2, 177.2,293.4, 293.4,293.4, 293.4}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights, &bias}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test1) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=3,oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oD, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC},{0.226, 0.343, 0.46 , 0.577, 1.172, 1.46 , 1.748, 2.036, 1.892, 2.288, 2.684, 3.08 , 1.284, 1.581, 1.878, 2.175, 4.458, 5.133, 5.808, 6.483, 6.186, 7.023, 7.86 , 8.697, 3.39 , 3.93 , 4.47 , 5.01 , 9.642, 10.803, 11.964, 13.125, 11.37 , 12.693, 14.016, 15.339, 5.266, 5.707, 6.148, 6.589, 12.98 , 13.916, 14.852, 15.788, 14.564, 15.608, 16.652, 17.696, 6.284, 7.166, 8.048, 8.93 , 17.896, 19.768, 21.64 , 23.512, 21.928, 24.016, 26.104, 28.192, 18.12 , 19.686, 21.252, 22.818, 45.852, 49.146, 52.44 , 55.734, 53.196, 56.814, 60.432, 64.05 , 28.164, 30.216, 32.268, 34.32 , 67.884, 72.15 , 76.416, 80.682, 75.228, 79.818, 84.408, 88.998, 29.324, 30.854, 32.384, 33.914, 67.432, 70.6 , 73.768, 76.936, 73.192, 76.576, 79.96 , 83.344, 27.884, 30.062, 32.24 , 34.418, 66.28 , 70.744, 75.208, 79.672, 70.312, 74.992, 79.672, 84.352, 58.296, 61.806, 65.316, 68.826,133.98 , 141.162, 148.344, 155.526,141.324, 148.83 , 156.336, 163.842, 68.34 , 72.336, 76.332, 80.328,156.012, 164.166, 172.32 , 180.474,163.356, 171.834, 180.312, 188.79 , 61.292, 64.118, 66.944, 69.77 ,136.552, 142.312, 148.072, 153.832,142.312, 148.288, 154.264, 160.24 , 9.298, 11.359, 13.42 , 15.481, 27.092, 31.268, 35.444, 39.62 , 27.812, 32.096, 36.38 , 40.664, 26.556, 29.769, 32.982, 36.195, 66.666, 73.173, 79.68 , 86.187, 68.394, 75.063, 81.732, 88.401, 28.662, 32.118, 35.574, 39.03 , 71.85 , 78.843, 85.836, 92.829, 73.578, 80.733, 87.888, 95.043, 29.89 , 32.275, 34.66 , 37.045, 70.004, 74.828, 79.652, 84.476, 71.588, 76.52 , 81.452, 86.384, 71.084, 75.854, 80.624, 85.394,163.048, 172.696, 182.344, 191.992,167.08 , 176.944, 186.808, 196.672,138.648, 146.046, 153.444, 160.842,310.236, 325.194, 340.152, 355.11 ,317.58 , 332.862, 348.144, 363.426, 148.692, 156.576, 164.46 , 172.344,332.268, 348.198, 364.128, 380.058,339.612, 355.866, 372.12 , 388.374,125.228, 130.646, 136.064, 141.482,274.792, 285.736, 296.68 , 307.624,280.552, 291.712, 302.872, 314.032, 92.684, 98.75 , 104.816, 110.882,211.432, 223.672, 235.912, 248.152,215.464, 227.92 , 240.376, 252.832, 178.824, 188.166, 197.508, 206.85 ,398.364, 417.21 , 436.056, 454.902,405.708, 424.878, 444.048, 463.218,188.868, 198.696, 208.524, 218.352,420.396, 440.214, 460.032, 479.85 ,427.74 , 447.882, 468.024, 488.166,157.196, 163.91 , 170.624, 177.338,343.912, 357.448, 370.984, 384.52 ,349.672, 363.424, 377.176, 390.928}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC},{120.96, 122.04, 123.12,120.96, 122.04, 123.12,120.96, 122.04, 123.12,120.96, 122.04, 123.12, 79.56, 80.28, 81. , 79.56, 80.28, 81. , 79.56, 80.28, 81. , 79.56, 80.28, 81. , 154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68, 111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 , 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test2) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oD, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC},{ 0.014, 0.032, 0.05 , 0.068, 0.118, 0.181, 0.244, 0.307, 0.212, 0.257, 0.302, 0.347, 0.208, 0.298, 0.388, 0.478, 1.028, 1.262, 1.496, 1.73 , 1.036, 1.18 , 1.324, 1.468, 0.928, 1.018, 1.108, 1.198, 2.9 , 3.134, 3.368, 3.602, 2.188, 2.332, 2.476, 2.62 , 1.202, 1.274, 1.346, 1.418, 3.142, 3.313, 3.484, 3.655, 2.048, 2.147, 2.246, 2.345, 0.532, 0.676, 0.82 , 0.964, 2.324, 2.666, 3.008, 3.35 , 2.008, 2.206, 2.404, 2.602, 3.584, 3.98 , 4.376, 4.772,10.552,11.452,12.352,13.252, 7.4 , 7.904, 8.408, 8.912, 6.752, 7.148, 7.544, 7.94 ,17.752,18.652,19.552,20.452,11.432,11.936,12.44 ,12.944, 5.932, 6.184, 6.436, 6.688,14.42 ,14.978,15.536,16.094, 8.704, 9.01 , 9.316, 9.622, 3.11 , 3.236, 3.362, 3.488, 7.39 , 7.669, 7.948, 8.227, 4.388, 4.541, 4.694, 4.847, 8.56 , 8.866, 9.172, 9.478,19.892,20.558,21.224,21.89 ,11.548,11.908,12.268,12.628,11.008,11.314,11.62 ,11.926,25.22 ,25.886,26.552,27.218,14.428,14.788,15.148,15.508, 7.322, 7.502, 7.682, 7.862,16.462,16.849,17.236,17.623, 9.248, 9.455, 9.662, 9.869, 0.158, 0.392, 0.626, 0.86 , 1.27 , 1.765, 2.26 , 2.755, 1.22 , 1.481, 1.742, 2.003, 2.224, 2.746, 3.268, 3.79 , 6.788, 7.886, 8.984,10.082, 4.78 , 5.356, 5.932, 6.508, 6.4 , 6.922, 7.444, 7.966,15.572,16.67 ,17.768,18.866, 9.388, 9.964,10.54 ,11.116, 4.802, 5.09 , 5.378, 5.666,11.206,11.809,12.412,13.015, 6.512, 6.827, 7.142, 7.457, 6.004, 6.58 , 7.156, 7.732,14.996,16.202,17.408,18.614, 9.208, 9.838,10.468,11.098,17.984,19.244,20.504,21.764,42.808,45.436,48.064,50.692,25.256,26.624,27.992,29.36 , 28.064,29.324,30.584,31.844,63.832,66.46 ,69.088,71.716,36.2 ,37.568,38.936,40.304,18.316,19. ,19.684,20.368,40.916,42.338,43.76 ,45.182,22.816,23.554,24.292,25.03 , 8.438, 8.78 , 9.122, 9.464,18.91 ,19.621,20.332,21.043,10.58 ,10.949,11.318,11.687, 20.944,21.682,22.42 ,23.158,46.388,47.918,49.448,50.978,25.66 ,26.452,27.244,28.036,26.848,27.586,28.324,29.062,58.628,60.158,61.688,63.218,31.996,32.788,33.58 ,34.372,16.106,16.502,16.898,17.294,34.894,35.713,36.532,37.351,18.896,19.319,19.742,20.165}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC},{7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test3) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oC, oD, oH, oW}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW},{2.091, 4.356, 2.268, 4.53 , 9.42 , 4.896, 4.65 , 9.672, 5.028, 2.517, 5.226, 2.712, 4.932,10.242, 5.316,10.62 ,22.02 ,11.412,10.908,22.62 ,11.724, 5.868,12.15 , 6.288, 2.913, 6.03 , 3.12 , 6.234,12.888, 6.66 , 6.402,13.236, 6.84 , 3.423, 7.068, 3.648, 2.415, 5.04 , 2.628, 5.25 ,10.932, 5.688, 5.37 ,11.184, 5.82 , 2.913, 6.054, 3.144, 5.724,11.898, 6.18 ,12.348,25.62 ,13.284,12.636,26.22 ,13.596, 6.804,14.094, 7.296, 3.381, 7.002, 3.624, 7.242,14.976, 7.74 , 7.41 ,15.324, 7.92 , 3.963, 8.184, 4.224, 2.739, 5.724, 2.988, 5.97 ,12.444, 6.48 , 6.09 ,12.696, 6.612, 3.309, 6.882, 3.576, 6.516,13.554, 7.044,14.076,29.22 ,15.156,14.364,29.82 ,15.468, 7.74 ,16.038, 8.304, 3.849, 7.974, 4.128, 8.25 ,17.064, 8.82 , 8.418,17.412, 9. , 4.503, 9.3 , 4.8 , 3.063, 6.408, 3.348, 6.69 ,13.956, 7.272, 6.81 ,14.208, 7.404, 3.705, 7.71 , 4.008, 7.308,15.21 , 7.908,15.804,32.82 ,17.028,16.092,33.42 ,17.34 , 8.676,17.982, 9.312, 4.317, 8.946, 4.632, 9.258,19.152, 9.9 , 9.426,19.5 ,10.08 , 5.043,10.416, 5.376, 5.619,11.484, 5.868,11.73 ,23.964,12.24 ,12.138,24.792,12.66 , 6.333,12.93 , 6.6 ,12.42 ,25.362,12.948,25.884,52.836,26.964,26.748,54.588,27.852,13.932,28.422,14.496, 6.873,14.022, 7.152,14.298,29.16 ,14.868,14.754,30.084,15.336, 7.671,15.636, 7.968, 6.807,13.896, 7.092,14.178,28.932,14.76 ,14.586,29.76 ,15.18 , 7.593,15.486, 7.896,14.94 ,30.474,15.54 ,31.068,63.348,32.292,31.932,65.1 ,33.18 ,16.596,33.822,17.232, 8.205,16.722, 8.52 ,17.034,34.704,17.676,17.49 ,35.628,18.144, 9.075,18.48 , 9.408, 7.995,16.308, 8.316,16.626,33.9 ,17.28 ,17.034,34.728,17.7 , 8.853,18.042, 9.192,17.46 ,35.586,18.132,36.252,73.86 ,37.62 ,37.116,75.612,38.508,19.26 ,39.222,19.968, 9.537,19.422, 9.888,19.77 ,40.248,20.484,20.226,41.172,20.952,10.479,21.324,10.848, 9.183,18.72 , 9.54 ,19.074,38.868,19.8 ,19.482,39.696,20.22 ,10.113,20.598,10.488,19.98 ,40.698,20.724,41.436,84.372,42.948,42.3 ,86.124,43.836,21.924,44.622,22.704,10.869,22.122,11.256,22.506,45.792,23.292,22.962,46.716,23.76 ,11.883,24.168,12.288}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW},{5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4}); auto expGradB = NDArrayFactory::create<TypeParam>('c', {oC},{2.64, 3.92, 5.2 }); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); weights.permutei({2, 3, 4, 1, 0}); expGradW.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); auto* gradB = results->at(2); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, depthwise_conv2d_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{12. , 12.8, 13.6, 14.4,12. , 12.8, 13.6, 14.4, 5.2, 5.6, 6. , 6.4,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 5.6, 6.4, 7.2, 8. , 5.6, 6.4, 7.2, 8. , 2. , 2.4, 2.8, 3.2, 12. , 12.8, 13.6, 14.4,12. , 12.8, 13.6, 14.4, 5.2, 5.6, 6. , 6.4,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 5.6, 6.4, 7.2, 8. , 5.6, 6.4, 7.2, 8. , 2. , 2.4, 2.8, 3.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test2) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oH, oW, oC},{13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test3) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<double>('c', {mC, iC, kH, kW}); auto biases = NDArrayFactory::create<double>('c', {iC*mC}, {1,2,3,4}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oC, oH, oW},{5.2, 5.2, 5.2, 5.2,20.6,20.6,20.6,20.6,14.4,14.4,14.4,14.4,29.8,29.8,29.8,29.8, 5.2, 5.2, 5.2, 5.2,20.6,20.6,20.6,20.6,14.4,14.4,14.4,14.4,29.8,29.8,29.8,29.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2,3,1,0}); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights, &biases}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int oC=iC*mC; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<double>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<double>('c', {bS, iH, iW, iC},{0.07 , 0.19 , 0.348, 0.652, 0.588, 0.956, 0.387, 0.687, 1.326, 2.022, 1.878, 2.67 , 1.071, 1.515, 2.982, 3.966, 3.534, 4.614, 1.606, 1.982, 3.932, 4.748, 4.428, 5.308, 1.126, 1.63 , 3.228, 4.3 , 3.468, 4.604, 3.123, 3.999, 7.95 , 9.798, 8.502, 10.446, 3.807, 4.827, 9.606, 11.742,10.158, 12.39 , 4.198, 4.958, 9.884, 11.468,10.38 , 12.028}); auto expGradW = NDArrayFactory::create<double>('c', {kH, kW, iC, mC},{19.08, 19.44,19.8 , 20.16,12.24, 12.48,12.72, 12.96,22.56, 23.04,23.52, 24. ,14.4 , 14.72,15.04, 15.36,14.76, 15.12,15.48, 15.84, 9.36, 9.6 , 9.84, 10.08}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::depthwise_conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_bp_test2) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int oC=iC*mC; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<double>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<double>('c', {bS, iH, iW, iC},{0.005, 0.025,0.034, 0.106,0.061, 0.113,0.058, 0.162,0.292, 0.564,0.298, 0.466,0.234, 0.402,0.772, 1.172,0.602, 0.834,0.333, 0.449,0.882, 1.146,0.581, 0.729, 0.053, 0.137,0.258, 0.458,0.237, 0.353,0.41 , 0.642,1.252, 1.78 ,0.906, 1.202,1.098, 1.394,2.756, 3.412,1.722, 2.082,0.893, 1.073,2.13 , 2.522,1.269, 1.481}); auto expGradW = NDArrayFactory::create<double>('c', {kH, kW, iC, mC},{2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::depthwise_conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test1) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 4, 3, 3}, {64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48.,96.,96.,96.,96.,96.,96.,48.,48.,48., 64.,64.,64.,64.,64.,64.,32.,32.,32.,64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48., 96.,96.,96.,96.,96.,96.,48.,48.,48.,64.,64.,64.,64.,64.,64.,32.,32.,32.,32.,32.,32.,32.,32.,32.,16.,16.,16., 48.,48.,48.,48.,48.,48.,24.,24.,24.,48.,48.,48.,48.,48.,48.,24.,24.,24.,32.,32.,32.,32.,32.,32.,16.,16.,16., 64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48.,96.,96.,96.,96.,96.,96.,48.,48.,48., 64.,64.,64.,64.,64.,64.,32.,32.,32.,64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48., 96.,96.,96.,96.,96.,96.,48.,48.,48.,64.,64.,64.,64.,64.,64.,32.,32.,32.,32.,32.,32.,32.,32.,32.,16.,16.,16., 48.,48.,48.,48.,48.,48.,24.,24.,24.,48.,48.,48.,48.,48.,48.,24.,24.,24.,32.,32.,32.,32.,32.,32.,16.,16.,16.}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test2) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 4, 3, 3}, {534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,152. ,155.2,158.4,152. ,155.2,158.4, 66.4, 68. , 69.6, 170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6,170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2, 534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,152. ,155.2,158.4,152. ,155.2,158.4, 66.4, 68. , 69.6, 170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6,170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test3) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2, 3}, {686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test4) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2}); input = 2.; weights = 0.5; expected = 48.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test5) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2}); input = 2.; weights = 0.5; expected = 49.; bias = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test6) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC},{1,2,3}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{49., 49.,49., 49., 49., 49.,49., 49., 50., 50.,50., 50., 50., 50.,50., 50., 51., 51.,51., 51., 51., 51.,51., 51., 49., 49.,49., 49., 49., 49.,49., 49., 50., 50.,50., 50., 50., 50.,50., 50., 51., 51.,51., 51., 51., 51.,51., 51.}); input = 2.; weights = 0.5; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test7) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC},{1,2,3}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 698. , 698. , 698. , 698. , 698. , 698. , 698. , 698. ,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 698. , 698. , 698. , 698. , 698. , 698. , 698. , 698. ,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test8) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 696. , 696. , 696. , 696. , 696. , 696. , 696. , 696. , 1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 696. , 696. , 696. , 696. , 696. , 696. , 696. , 696. ,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test9) { auto x = NDArrayFactory::create<TypeParam>('c', {4, 2, 28, 28, 3}); auto y = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 3, 4}); auto e = NDArrayFactory::create<TypeParam>('c', {4, 1, 7, 10, 4}); nd4j::ops::conv3dnew op; auto result = op.execute({&x, &y}, {}, {2,5,5, 5,4,3, 0,0,0, 1,1,1, 1,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(e.isSameShape(z)); delete result; } TYPED_TEST(TypedConvolutionTests1, conv3d_test10) { auto x = NDArrayFactory::create<TypeParam>('c', {4, 2, 28, 28, 3}); auto w = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 3, 4}); auto exp = NDArrayFactory::create<TypeParam>('c', {4, 1, 7, 10, 4}); nd4j::ops::conv3dnew op; auto result = op.execute({&x, &w}, {}, {2,5,5, 5,4,3, 0,0,0, 1,1,1, 1,1}); ASSERT_EQ(Status::OK(), result->status()); ShapeList shapeList({x.shapeInfo(), w.shapeInfo()}); ContextPrototype proto; Context ctx(1); ctx.getIArguments()->push_back(2); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(4); ctx.getIArguments()->push_back(3); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(1); // previous variant was "ctx.getIArguments()->push_back(0)" and this caused fail auto shapes = op.calculateOutputShape(&shapeList, ctx); ASSERT_EQ(1, shapes->size()); auto s = shapes->at(0); auto z = result->at(0); // z->printShapeInfo("z shape"); ASSERT_TRUE(exp.isSameShape(z)); delete result; shapes->destroy(); delete shapes; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, pointwise_conv2d_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {1, 1, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, oC},{ 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0}); input = 2.; weights.linspace(0.1, 0.1); bias = 1.; nd4j::ops::pointwise_conv2d op; auto results = op.execute({&input, &weights, &bias}, {}, {dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, sconv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int oC=iC*mC; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weightsDepth = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{0.07 , 0.19 , 0.348, 0.652, 0.588, 0.956, 0.387, 0.687, 1.326, 2.022, 1.878, 2.67 , 1.071, 1.515, 2.982, 3.966, 3.534, 4.614, 1.606, 1.982, 3.932, 4.748, 4.428, 5.308, 1.126, 1.63 , 3.228, 4.3 , 3.468, 4.604, 3.123, 3.999, 7.95 , 9.798, 8.502, 10.446, 3.807, 4.827, 9.606, 11.742,10.158, 12.39 , 4.198, 4.958, 9.884, 11.468,10.38 , 12.028}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC},{19.08, 19.44,19.8 , 20.16,12.24, 12.48,12.72, 12.96,22.56, 23.04,23.52, 24. ,14.4 , 14.72,15.04, 15.36,14.76, 15.12,15.48, 15.84, 9.36, 9.6 , 9.84, 10.08}); input = 2.; weightsDepth.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::sconv2d_bp op; auto results = op.execute({&input, &gradO, &weightsDepth, &bias}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradWD = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradWD)); ASSERT_TRUE(expGradW.equalsTo(gradWD)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test4) { int bS=1, iH=256,iW=256, iC=1,oC=1, kH=4,kW=3, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; // int oH=256,oW=256; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); input = 5.; weights = 3.; nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test11) { int bS=1, iD=2,iH=2,iW=2, iC=1,oC=1, kD=2,kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test12) { int bS=5, iD=4,iH=14,iW=14, iC=1,oC=1, kD=2,kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=3,oH=13,oW=13; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {bS, oC, oD, oH, oW}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(output->isSameShape(&expected)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, vol2col_test1) { int bS=2, iD=2,iH=3,iW=2, iC=3,oC=2, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=3,oW=2; NDArray volume('c', {bS, iD, iH, iW, iC}, nd4j::DataType::FLOAT32); NDArray columns('c', {bS, iC, kD, kH, kW, oD, oH, oW}, nd4j::DataType::FLOAT32); columns = -1.; volume.linspace(1); NDArray columnsExpected('c', {bS, iC, kD, kH, kW, oD, oH, oW}, {1., 2., 4., 5., 0., 0., 7., 8., 10., 11., 0., 0., 2., 3., 5., 6., 0., 0., 8., 9., 11., 12., 0., 0., 4., 5., 0., 0., 0., 0., 10., 11., 0., 0., 0., 0., 5., 6., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 10., 11., 0., 0., 13., 14., 16., 17., 0., 0., 8., 9., 11., 12., 0., 0., 14., 15., 17., 18., 0., 0., 10., 11., 0., 0., 0., 0., 16., 17., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 17., 18., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 19., 20., 22., 23., 0., 0., 25., 26., 28., 29., 0., 0., 20., 21., 23., 24., 0., 0., 26., 27., 29., 30., 0., 0., 22., 23., 0., 0., 0., 0., 28., 29., 0., 0., 0., 0., 23., 24., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 25., 26., 28., 29., 0., 0., 31., 32., 34., 35., 0., 0., 26., 27., 29., 30., 0., 0., 32., 33., 35., 36., 0., 0., 28., 29., 0., 0., 0., 0., 34., 35., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 35., 36., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., 37., 38., 40., 41., 0., 0., 43., 44., 46., 47., 0., 0., 38., 39., 41., 42., 0., 0., 44., 45., 47., 48., 0., 0., 40., 41., 0., 0., 0., 0., 46., 47., 0., 0., 0., 0., 41., 42., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 43., 44., 46., 47., 0., 0., 49., 50., 52., 53., 0., 0., 44., 45., 47., 48., 0., 0., 50., 51., 53., 54., 0., 0., 46., 47., 0., 0., 0., 0., 52., 53., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 53., 54., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 55., 56., 58., 59., 0., 0., 61., 62., 64., 65., 0., 0., 56., 57., 59., 60., 0., 0., 62., 63., 65., 66., 0., 0., 58., 59., 0., 0., 0., 0., 64., 65., 0., 0., 0., 0., 59., 60., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 61., 62., 64., 65., 0., 0., 67., 68., 70., 71., 0., 0., 62., 63., 65., 66., 0., 0., 68., 69., 71., 72., 0., 0., 64., 65., 0., 0., 0., 0., 70., 71., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 71., 72., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.}, nd4j::DataType::FLOAT32); // PointersManager manager(columnsExpected.getContext()); // manager.printDevContentOnHost<float>(columnsExpected.getSpecialBuffer(), columnsExpected.lengthOf()); graph::Context context(1); nd4j::ops::ConvolutionUtils::vol2col(context, volume, columns, sD, sH, sW, pD, pH, pW, dD, dH, dW); ASSERT_TRUE(columns.equalsTo(columnsExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, vol2col_test2) { int bS=2, iD=2,iH=3,iW=2, iC=3,oC=2, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=3,oW=2; auto volume = NDArrayFactory::create<float>('c', {iD, bS, iH, iC, iW}); volume.permutei({1, 0, 2, 4, 3}); volume.linspace(1); auto columns = NDArrayFactory::create<float>('c', {kD, iC, kH, oW, kW, bS, oD, oH}); columns.permutei({5, 1, 0, 2, 4, 6, 7, 3}); columns = -1.; auto columnsExpected = NDArrayFactory::create<float>('c', {bS, iC, kD, kH, kW, oD, oH, oW}, {1., 2., 4., 5., 0., 0., 7., 8., 10., 11., 0., 0., 2., 3., 5., 6., 0., 0., 8., 9., 11., 12., 0., 0., 4., 5., 0., 0., 0., 0., 10., 11., 0., 0., 0., 0., 5., 6., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 10., 11., 0., 0., 13., 14., 16., 17., 0., 0., 8., 9., 11., 12., 0., 0., 14., 15., 17., 18., 0., 0., 10., 11., 0., 0., 0., 0., 16., 17., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 17., 18., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 19., 20., 22., 23., 0., 0., 25., 26., 28., 29., 0., 0., 20., 21., 23., 24., 0., 0., 26., 27., 29., 30., 0., 0., 22., 23., 0., 0., 0., 0., 28., 29., 0., 0., 0., 0., 23., 24., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 25., 26., 28., 29., 0., 0., 31., 32., 34., 35., 0., 0., 26., 27., 29., 30., 0., 0., 32., 33., 35., 36., 0., 0., 28., 29., 0., 0., 0., 0., 34., 35., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 35., 36., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., 37., 38., 40., 41., 0., 0., 43., 44., 46., 47., 0., 0., 38., 39., 41., 42., 0., 0., 44., 45., 47., 48., 0., 0., 40., 41., 0., 0., 0., 0., 46., 47., 0., 0., 0., 0., 41., 42., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 43., 44., 46., 47., 0., 0., 49., 50., 52., 53., 0., 0., 44., 45., 47., 48., 0., 0., 50., 51., 53., 54., 0., 0., 46., 47., 0., 0., 0., 0., 52., 53., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 53., 54., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 55., 56., 58., 59., 0., 0., 61., 62., 64., 65., 0., 0., 56., 57., 59., 60., 0., 0., 62., 63., 65., 66., 0., 0., 58., 59., 0., 0., 0., 0., 64., 65., 0., 0., 0., 0., 59., 60., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 61., 62., 64., 65., 0., 0., 67., 68., 70., 71., 0., 0., 62., 63., 65., 66., 0., 0., 68., 69., 71., 72., 0., 0., 64., 65., 0., 0., 0., 0., 70., 71., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 71., 72., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.}); graph::Context context(1); nd4j::ops::ConvolutionUtils::vol2col(context, volume, columns, sD, sH, sW, pD, pH, pW, dD, dH, dW); ASSERT_TRUE(columns.equalsTo(columnsExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, col2im_test1) { int bS=2, iH=2,iW=2, iC=2, kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oH=2,oW=2; auto image = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); image = -2.; auto columns = NDArrayFactory::create<float>('c', {bS, iC, kH, kW, oH, oW}); columns.linspace(1); auto imageExpected = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}, {1., 7., 12., 34., 17., 39., 44., 98., 33., 71., 76., 162., 49., 103., 108., 226.}); LaunchContext ctx; nd4j::ops::helpers::col2im(ctx, columns, image, sH, sW, pH, pW, iH, iW, dH, dW); ASSERT_TRUE(image.equalsTo(imageExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_test1) { const int bS=3, iH=2,iW=2, iC=3; const int factorH=2, factorW=3; const int isNCHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iH*factorH, iW*factorW, iC}, {1., 2., 3., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,10., 11., 12., 13., 14., 15.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,16., 17., 18., 19., 20., 21.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,22., 23., 24., 25., 26., 27.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,28., 29., 30., 31., 32., 33.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,34., 35., 36.}); nd4j::ops::upsampling2d op; auto results = op.execute({&input}, {}, {factorH, factorW, isNCHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_test2) { const int bS=3, iH=2,iW=2, iC=3; const int factorH=2, factorW=3; const int isNCHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iC, iH*factorH, iW*factorW}, {1., 1., 1., 2., 2., 2., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 4., 4., 3., 3., 3., 4., 4., 4., 5., 5., 5., 6., 6., 6., 5., 5., 5., 6., 6., 6., 7., 7., 7., 8., 8., 8., 7., 7., 7., 8., 8., 8., 9., 9., 9., 10., 10., 10., 9., 9., 9., 10., 10., 10.,11., 11., 11., 12., 12., 12.,11., 11., 11., 12., 12., 12., 13., 13., 13., 14., 14., 14.,13., 13., 13., 14., 14., 14.,15., 15., 15., 16., 16., 16.,15., 15., 15., 16., 16., 16.,17., 17., 17., 18., 18., 18.,17., 17., 17., 18., 18., 18.,19., 19., 19., 20., 20., 20.,19., 19., 19., 20., 20., 20., 21., 21., 21., 22., 22., 22.,21., 21., 21., 22., 22., 22.,23., 23., 23., 24., 24., 24.,23., 23., 23., 24., 24., 24.,25., 25., 25., 26., 26., 26.,25., 25., 25., 26., 26., 26.,27., 27., 27., 28., 28., 28.,27., 27., 27., 28., 28., 28., 29., 29., 29., 30., 30., 30.,29., 29., 29., 30., 30., 30.,31., 31., 31., 32., 32., 32.,31., 31., 31., 32., 32., 32., 33., 33., 33., 34., 34., 34.,33., 33., 33., 34., 34., 34.,35., 35., 35., 36., 36., 36.,35., 35., 35., 36., 36., 36.}); nd4j::ops::upsampling2d op; auto results = op.execute({&input}, {}, {factorH, factorW, isNCHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_test1) { const int bS=3, iD=2,iH=2,iW=2, iC=3; const int factorD=2,factorH=3,factorW=2; const int isNCDHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iD, iH, iW, iC}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iD*factorD, iH*factorH, iW*factorW, iC}, {1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18., 19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18., 13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30., 25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36., 25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36., 31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48., 43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42., 43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54., 49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54., 49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60., 61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72., 67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72., 67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.}); nd4j::ops::upsampling3d op; auto results = op.execute({&input}, {}, {factorD, factorH, factorW, isNCDHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_test2) { const int bS=3, iD=2,iH=2,iW=2, iC=3; const int factorD=2,factorH=3,factorW=2; const int isNCDHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iC, iD*factorD, iH*factorH, iW*factorW}, { 1., 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 3., 3., 4., 4., 3., 3., 4., 4., 3., 3., 4., 4., 1., 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 3., 3., 4., 4., 3., 3., 4., 4., 3., 3., 4., 4., 5., 5., 6., 6., 5., 5., 6., 6., 5., 5., 6., 6., 7., 7., 8., 8., 7., 7., 8., 8., 7., 7., 8., 8., 5., 5., 6., 6., 5., 5., 6., 6., 5., 5., 6., 6., 7., 7., 8., 8., 7., 7., 8., 8., 7., 7., 8., 8., 9., 9., 10., 10., 9., 9., 10., 10., 9., 9., 10., 10.,11., 11., 12., 12.,11., 11., 12., 12.,11., 11., 12., 12., 9., 9., 10., 10., 9., 9., 10., 10., 9., 9., 10., 10.,11., 11., 12., 12.,11., 11., 12., 12.,11., 11., 12., 12., 13., 13., 14., 14.,13., 13., 14., 14.,13., 13., 14., 14.,15., 15., 16., 16.,15., 15., 16., 16.,15., 15., 16., 16.,13., 13., 14., 14.,13., 13., 14., 14.,13., 13., 14., 14.,15., 15., 16., 16.,15., 15., 16., 16.,15., 15., 16., 16.,17., 17., 18., 18.,17., 17., 18., 18.,17., 17., 18., 18.,19., 19., 20., 20.,19., 19., 20., 20.,19., 19., 20., 20., 17., 17., 18., 18.,17., 17., 18., 18.,17., 17., 18., 18.,19., 19., 20., 20.,19., 19., 20., 20.,19., 19., 20., 20.,21., 21., 22., 22.,21., 21., 22., 22.,21., 21., 22., 22.,23., 23., 24., 24.,23., 23., 24., 24.,23., 23., 24., 24.,21., 21., 22., 22.,21., 21., 22., 22.,21., 21., 22., 22.,23., 23., 24., 24.,23., 23., 24., 24.,23., 23., 24., 24., 25., 25., 26., 26.,25., 25., 26., 26.,25., 25., 26., 26.,27., 27., 28., 28.,27., 27., 28., 28.,27., 27., 28., 28.,25., 25., 26., 26.,25., 25., 26., 26.,25., 25., 26., 26.,27., 27., 28., 28.,27., 27., 28., 28.,27., 27., 28., 28.,29., 29., 30., 30.,29., 29., 30., 30.,29., 29., 30., 30.,31., 31., 32., 32.,31., 31., 32., 32.,31., 31., 32., 32., 29., 29., 30., 30.,29., 29., 30., 30.,29., 29., 30., 30.,31., 31., 32., 32.,31., 31., 32., 32.,31., 31., 32., 32.,33., 33., 34., 34.,33., 33., 34., 34.,33., 33., 34., 34.,35., 35., 36., 36.,35., 35., 36., 36.,35., 35., 36., 36.,33., 33., 34., 34.,33., 33., 34., 34.,33., 33., 34., 34.,35., 35., 36., 36.,35., 35., 36., 36.,35., 35., 36., 36., 37., 37., 38., 38.,37., 37., 38., 38.,37., 37., 38., 38.,39., 39., 40., 40.,39., 39., 40., 40.,39., 39., 40., 40.,37., 37., 38., 38.,37., 37., 38., 38.,37., 37., 38., 38.,39., 39., 40., 40.,39., 39., 40., 40.,39., 39., 40., 40.,41., 41., 42., 42.,41., 41., 42., 42.,41., 41., 42., 42.,43., 43., 44., 44.,43., 43., 44., 44.,43., 43., 44., 44., 41., 41., 42., 42.,41., 41., 42., 42.,41., 41., 42., 42.,43., 43., 44., 44.,43., 43., 44., 44.,43., 43., 44., 44.,45., 45., 46., 46.,45., 45., 46., 46.,45., 45., 46., 46.,47., 47., 48., 48.,47., 47., 48., 48.,47., 47., 48., 48.,45., 45., 46., 46.,45., 45., 46., 46.,45., 45., 46., 46.,47., 47., 48., 48.,47., 47., 48., 48.,47., 47., 48., 48., 49., 49., 50., 50.,49., 49., 50., 50.,49., 49., 50., 50.,51., 51., 52., 52.,51., 51., 52., 52.,51., 51., 52., 52.,49., 49., 50., 50.,49., 49., 50., 50.,49., 49., 50., 50.,51., 51., 52., 52.,51., 51., 52., 52.,51., 51., 52., 52.,53., 53., 54., 54.,53., 53., 54., 54.,53., 53., 54., 54.,55., 55., 56., 56.,55., 55., 56., 56.,55., 55., 56., 56., 53., 53., 54., 54.,53., 53., 54., 54.,53., 53., 54., 54.,55., 55., 56., 56.,55., 55., 56., 56.,55., 55., 56., 56.,57., 57., 58., 58.,57., 57., 58., 58.,57., 57., 58., 58.,59., 59., 60., 60.,59., 59., 60., 60.,59., 59., 60., 60.,57., 57., 58., 58.,57., 57., 58., 58.,57., 57., 58., 58.,59., 59., 60., 60.,59., 59., 60., 60.,59., 59., 60., 60., 61., 61., 62., 62.,61., 61., 62., 62.,61., 61., 62., 62.,63., 63., 64., 64.,63., 63., 64., 64.,63., 63., 64., 64.,61., 61., 62., 62.,61., 61., 62., 62.,61., 61., 62., 62.,63., 63., 64., 64.,63., 63., 64., 64.,63., 63., 64., 64.,65., 65., 66., 66.,65., 65., 66., 66.,65., 65., 66., 66.,67., 67., 68., 68.,67., 67., 68., 68.,67., 67., 68., 68., 65., 65., 66., 66.,65., 65., 66., 66.,65., 65., 66., 66.,67., 67., 68., 68.,67., 67., 68., 68.,67., 67., 68., 68.,69., 69., 70., 70.,69., 69., 70., 70.,69., 69., 70., 70.,71., 71., 72., 72.,71., 71., 72., 72.,71., 71., 72., 72.,69., 69., 70., 70.,69., 69., 70., 70.,69., 69., 70., 70.,71., 71., 72., 72.,71., 71., 72., 72.,71., 71., 72., 72.}); nd4j::ops::upsampling3d op; auto results = op.execute({&input}, {}, {factorD, factorH, factorW, isNCDHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_bp_test1) { const int bS=1, iH=2,iW=2, iC=1; const int factorH=2, factorW=2; const int isNCHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); auto gradO = NDArrayFactory::create<float>('c', {bS, iC, iH*factorH, iW*factorW}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); expGradI = 4.; nd4j::ops::upsampling2d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_bp_test2) { const int bS=1, iH=2,iW=2, iC=1; const int factorH=2, factorW=2; const int isNCHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); auto gradO = NDArrayFactory::create<float>('c', {bS, iH*factorH, iW*factorW, iC}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); expGradI = 4.; nd4j::ops::upsampling2d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_bp_test1) { const int bS=1, iD=2,iH=2,iW=2, iC=1; const int factorD=2, factorH=2, factorW=2; const int isNCDHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); auto gradO = NDArrayFactory::create<float>('c', {bS, iC, iD*factorD, iH*factorH, iW*factorW}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); expGradI = 8.; nd4j::ops::upsampling3d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCDHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, maxpool_test6) { int bS=1, iH=4,iW=4, iC=3, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}, {0.27620894, 0.21801452, 0.062078513, 7.348895E-4, 0.24149609, 0.4948205, 0.93483436, 0.52035654, 0.30292067, 0.3289706, 0.7977864, 0.03180518, 0.1455722, 0.90352905, 0.9405744, 0.0048329555, 0.44062102, 0.111197524, 0.31742015, 0.1933705, 0.23825112, 0.35076278, 0.7135856, 0.28229436, 0.18310733, 0.9613717, 0.56823575, 0.78289545, 0.62195826, 0.5244586, 0.5040889, 0.025349546, 0.41400263, 0.28420195, 0.8536445, 0.3044107, 0.7997134, 0.45762005, 0.7653578, 0.07198584, 0.5304998, 0.7334402, 0.85019743, 0.031957153, 0.37088063, 0.85722464, 0.06376881, 0.39791203}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, iC, oH, oW}, {0.4948205, 0.93483436, 0.93483436, 0.4948205, 0.93483436, 0.93483436, 0.90352905, 0.9405744, 0.9405744, 0.44062102, 0.7135856, 0.7135856, 0.9613717, 0.9613717, 0.78289545, 0.9613717, 0.9613717, 0.78289545, 0.7997134, 0.8536445, 0.8536445, 0.7997134, 0.85019743, 0.85019743, 0.85722464, 0.85722464, 0.85019743}); nd4j::ops::maxpool2d op; auto results = op.execute({&input}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } TYPED_TEST(TypedConvolutionTests1, conv2D_input_BP_test1) { auto inputShape = NDArrayFactory::create<TypeParam>('c', {4}, {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); auto shapeArr = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, shapeArr.getShapeInfo()); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_input_bp op; auto results = op.execute({&inputShape, &weights, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}); ASSERT_TRUE(results->size() == 1); auto epsilon = results->at(0); ASSERT_TRUE(shapeArr.isSameShape(epsilon)); ASSERT_TRUE(expEps.equalsTo(epsilon)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test4) { int bS=1, iH=3,iW=3, iC=2,mC=1, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=3,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}, {20., 24.,28., 32.,16., 18.,44., 48.,52., 56.,28., 30.,28., 30.,32., 34.,17., 18.}); input.linspace(1.); weights = 1.; nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test4_1) { int bS=1, iH=3,iW=3, iC=2,mC=1, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=3,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW NDArray input('c', {bS, iH, iW, iC}, nd4j::DataType::DOUBLE); NDArray weights('c', {kH, kW, iC, mC}, nd4j::DataType::DOUBLE); NDArray expOutput('c', {bS, oH, oW, oC}, {20., 24.,28., 32.,16., 18.,44., 48.,52., 56.,28., 30.,28., 30.,32., 34.,17., 18.}); input.linspace(1.); weights = 1.; nd4j::ops::depthwise_conv2d op; ResultSet* results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); NDArray* output = results->at(0); // output.printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, deconv2d_test1) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, oC}); auto exp = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}, { 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75, 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75}); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); ASSERT_EQ(Status::OK(), results->status()); auto output = results->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, deconv2d_test2) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=4; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, oC}); auto exp = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}, {2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. }); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, deconv2d_tf_test1) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto outShape = NDArrayFactory::create<TypeParam>('c', {4}, {static_cast<TypeParam>(bS), static_cast<TypeParam>(iH), static_cast<TypeParam>(iW), static_cast<TypeParam>(iC)}); auto exp = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}, { 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75, 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75}); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d_tf op; auto results = op.execute({&outShape, &weights, &input}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } #endif //LIBND4J_CONVOLUTIONTESTS1_H
/** * Copyright 2019-2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frontend/parallel/step_auto_parallel.h" #include <cinttypes> #include <ctime> #include <algorithm> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "utils/hash_map.h" #include "utils/hash_set.h" #include "base/core_ops.h" #include "frontend/optimizer/opt.h" #include "frontend/optimizer/optimizer.h" #include "frontend/parallel/auto_parallel/dp_algo_costmodel.h" #include "frontend/parallel/auto_parallel/edge_costmodel.h" #include "frontend/parallel/auto_parallel/graph_costmodel.h" #include "frontend/parallel/auto_parallel/rec_core/rec_generate_strategy.h" #include "frontend/parallel/auto_parallel/rec_core/rec_parse_graph.h" #include "frontend/parallel/auto_parallel/rec_core/rec_partition.h" #include "include/common/utils/parallel_context.h" #include "frontend/parallel/graph_util/node_info.h" #include "frontend/parallel/graph_util/graph_info.h" #include "frontend/parallel/ops_info/reshape_info.h" #include "frontend/parallel/ops_info/tmp_identity_info.h" #include "frontend/parallel/step_parallel.h" #include "frontend/parallel/parameter_manager.h" #include "frontend/parallel/strategy_checkpoint/parallel_strategy_checkpoint.h" #include "ir/anf.h" #include "ir/param_info.h" #include "ir/tensor.h" #if ((defined ENABLE_CPU) && (!defined _WIN32)) #include "ps/util.h" #endif namespace mindspore { namespace parallel { bool StepAutoParallel(const FuncGraphPtr &root, const opt::OptimizerPtr &) { #if ((defined ENABLE_CPU) && (!defined _WIN32) && !defined(__APPLE__)) if (ps::Util::IsRoleOfPServer() || ps::Util::IsRoleOfScheduler()) { return false; } #endif MS_EXCEPTION_IF_NULL(root); MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance()); std::string parallel_mode = ParallelContext::GetInstance()->parallel_mode(); // assume no change to graph bool changes = false; // control whether use model_parallel mode if (!root->has_flag(kAutoParallel) || (parallel_mode != kAutoParallel) || root->has_flag(AUTO_PARALLEL_RUN_ONCE_ONLY)) { return changes; } std::string strategy_search_mode = ParallelContext::GetInstance()->strategy_search_mode(); MS_LOG(INFO) << "search_mode: " << strategy_search_mode; struct timeval start_time { 0 }, end_time{0}; (void)gettimeofday(&start_time, nullptr); #ifdef ENABLE_DUMP_IR if (MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) { draw::Draw(STEP_AUTO_PARALLEL_BEGIN, root); } #endif MS_LOG(INFO) << "Now entering step auto parallel"; TOTAL_OPS = 0; AnfNodePtr ret = root->get_return(); std::vector<AnfNodePtr> all_nodes = DeepScopedGraphSearch(ret); if (ParallelInit() != SUCCESS) { MS_LOG(EXCEPTION) << "Parallel init failed"; } // mark the forward cnodes, parallel only care these nodes MarkForwardCNode(root); if (IsInsertVirtualOutput(root)) { InsertVirtualOutput(root, all_nodes); AnfNodePtr ret_after = root->get_return(); MS_EXCEPTION_IF_NULL(ret_after); all_nodes = DeepScopedGraphSearch(ret_after); } if (FindCommunicationOp(all_nodes)) { MS_LOG(EXCEPTION) << "The graph contain communication op"; } // search parallelization strategy if ((strategy_search_mode == kDynamicProgramming) || (strategy_search_mode == kShardingPropagation)) { if (ParallelStrategySearch(all_nodes, root) != SUCCESS) { MS_LOG(EXCEPTION) << "Auto-parallel strategy search failed when using " << strategy_search_mode << " searching mode"; } } else if (strategy_search_mode == kRecursiveProgramming) { if (ParallelStrategyRecSearch(all_nodes, root) != SUCCESS) { MS_LOG(EXCEPTION) << "Auto-parallel strategy search failed when using RP searching mode"; } } else { MS_LOG(EXCEPTION) << "Auto-parallel strategy searching mode unexpected: " << strategy_search_mode; } (void)gettimeofday(&end_time, nullptr); uint64_t time = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec); time += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec); MS_LOG(INFO) << "Now leaving step auto parallel, used time: " << time << " us"; root->set_flag(AUTO_PARALLEL_RUN_ONCE_ONLY, true); return changes; } bool IsElementWiseOperator(const std::string &op_name) { // clang-format off static const std::set<std::string> elementwise_op = {ACTIVATION, GELU, TANH, SOFTMAX, LOG_SOFTMAX, RELU, SQRT, CAST, POW, EXP, LOG, COS, ACOS, LOGICALNOT, NEG, SQUARE, SIGMOID, ABS, ACOSH, ASIN, ASINH, ATAN, ATANH, CEIL, COSH, EXPM1, LOG1P, SIN, SINH, TAN, RSQRT, RECIPROCAL, INV, ROUND, FLOOR, SIGN, ERF, ERFC, ZEROSLIKE, ONESLIKE, BESSELI0E, MOD, ASSIGN, ASSIGN_ADD, ATAN2, DIVNONAN, LOGICALAND, ELU, LOGICALOR, RELU6, SOFTPLUS, SOFTSIGN, LESS, LESSEQUAL, BESSELI1E, GREATEREQUAL, APPROXIMATEEQUAL, REPEAT_ELEMENTS}; // clang-format on auto iter = elementwise_op.find(op_name); return (iter != elementwise_op.end()); } bool IsSplittableOperator(const std::string &op_name) { // clang-format off static const std::set<std::string> splittable_op = {MATMUL, TRANSPOSE, GELU, FAST_GELU, TANH, SOFTMAX, SUB, MUL, DIV, RESHAPE, GREATER, LOG_SOFTMAX, ACTIVATION, PRELU, FLOORDIV, L2_NORMALIZE, ADD, MAXPOOL, AVGPOOL, MAXPOOLV2, VIRTUAL_DATA_SET, RELU, ONEHOT, DROPOUT_DO_MASK, REDUCE_MAX, REDUCE_MIN, ARGMAXWITHVALUE, ARGMINWITHVALUE, REDUCE_SUM, CONV2D, FUSE_BATCH_NORM, POOLING, MAX_POOL_WITH_ARGMAX, SIMPLE_MEAN, FLATTEN, BATCH_NORM, LAYER_NORM, BIAS_ADD, ASSIGN_SUB, COS, ACOS, EXP, STACK, LOG, REDUCE_MEAN, REAL_DIV, SIGMOID, POW, MAXIMUM, MINIMUM, EQUAL, NOT_EQUAL, LOGICALNOT, GATHERV2, SQRT, CONCAT, STRIDEDSLICE, GET_NEXT, CAST, NEG, SQUARE, BATCH_MATMUL, EXPAND_DIMS, SQUEEZE, SPARSE_GATHERV2, TILE, DROPOUT, SOFTMAX_CROSS_ENTROPY_WITH_LOGITS, SIGMOID_CROSS_ENTROPY_WITH_LOGITS, SPARSE_SOFTMAX_CROSS_ENTROPY_WITH_LOGITS, EMBEDDING_LOOKUP, FUSE_BATCH_NORM_EX, SPLIT, BROADCAST_TO, ABS, ACOSH, ASIN, ASINH, ATAN, ATANH, CEIL, COSH, EXPM1, LOG1P, SIN, SINH, TAN, RSQRT, INV, RECIPROCAL, ROUND, FLOOR, SIGN, ERF, ERFC, ZEROSLIKE, ONESLIKE, BESSELI0E, BESSELI1E, FLOORMOD, ASSIGN, ASSIGN_ADD, ATAN2, DIVNONAN, LOGICALAND, LOGICALOR, ELU, RELU6, RELUV2, SOFTPLUS, SOFTSIGN, GREATEREQUAL, LESSEQUAL, LESS, APPROXIMATEEQUAL, MOD, UNIQUE, UNSORTED_SEGMENT_SUM, UNSORTED_SEGMENT_MIN, REPEAT_ELEMENTS, TENSOR_DOT, RANGE, UNIFORM_CANDIDATE_SAMPLER, SLICE, SELECT, GATHERD, UNSORTED_SEGMENT_MAX, GATHER_ND, TOPK, SCATTER_UPDATE, VIRTUAL_OUTPUT, CONV2D_BACK_PROP_INPUT, CONV2D_TRANSPOSE, MATMUL_DDS, DSD_MATMUL, UNIFORMREAL, RESIZE_BILINEAR, RESIZE_NEAREST_NEIGHBOR, CUMSUM, FAST_GELU, IOU, BOUNDING_BOX_ENCODE, RANDOM_CHOICE_WITH_MASK, CROP_AND_RESIZE, ROI_ALIGN}; // clang-format on auto iter = splittable_op.find(op_name); return (iter != splittable_op.end()); } bool IsAutoParallelCareNode(const CNodePtr &cnode) { MS_EXCEPTION_IF_NULL(cnode); ValueNodePtr prim_node = cnode->input(0)->cast<ValueNodePtr>(); if (prim_node == nullptr) { return false; } PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_node); if (prim == nullptr) { return false; } bool bool_result = IsParallelCareNode(cnode) && !IsSplittableOperator(prim->name()); if (bool_result && (prim->name() != MAKE_TUPLE) && (prim->name() != MAKE_LIST)) { MS_LOG(EXCEPTION) << "Should implementing OperatorInfo for: " << prim->name(); } else if (prim->name() == CAST) { if (cnode->fullname_with_scope().find(OPTIMIZER_SUB_STRING) != std::string::npos) { // Do not care CASTs from optimizer return false; } return true; } return IsParallelCareNode(cnode) && IsSplittableOperator(prim->name()); } // Recording the operators appearing in a for-loop. // Currently, we assume that the operators in different for-loops are identical, and their traversal // orderings are also identical. // Therefore, we create OperatorInfo objects for the operators in a loop (say, loop-3), and reuse them in // the rest of loops (loop-2, loop-1 and loop-0) std::set<std::string> ops_in_a_loop_; // Whether two operators are in different loops; if it is true, then return true. // If at least one of the two operators is not in the loop, then return false. // If two operators are in the same loop, the return false. bool IsOperatorsInTwoSeparateLoops(const CNodePtr &a_cnode, const CNodePtr &b_cnode) { auto a_op_info = a_cnode->user_data<OperatorInfo>(); MS_EXCEPTION_IF_NULL(a_op_info); auto b_op_info = b_cnode->user_data<OperatorInfo>(); MS_EXCEPTION_IF_NULL(b_op_info); if ((ops_in_a_loop_.find(a_op_info->name()) == ops_in_a_loop_.end()) || (ops_in_a_loop_.find(b_op_info->name()) == ops_in_a_loop_.end())) { return false; } size_t a_loop_index = 0, b_loop_index = 0; const auto &a_fullname = a_cnode->fullname_with_scope(); if (!GetLoopIndexFromCNode(a_cnode, &a_loop_index)) { MS_LOG(EXCEPTION) << "The operator with fullname_with_scope: " << a_fullname << " was not included in the set."; } const auto &b_fullname = b_cnode->fullname_with_scope(); if (!GetLoopIndexFromCNode(b_cnode, &b_loop_index)) { MS_LOG(EXCEPTION) << "The operator with fullname_with_scope: " << b_fullname << " was not included in the set."; } if (a_loop_index == b_loop_index) { return false; } return true; } // 'configured_stra_ops_' includes all operators that are configured sharding strategies. std::map<OperatorInfoPtr, StrategyPtr, OpsPtrCompare> configured_stra_ops_; std::set<OperatorInfoPtr> ignore_candidate_; void InitCostGraph() { if (entire_costgraph == nullptr) { entire_costgraph = std::make_shared<CostGraph>(); } MS_EXCEPTION_IF_NULL(CostModelContext::GetInstance()); CostModelContext::GetInstance()->PrintCostModel(); entire_costgraph->Init(); configured_stra_ops_.clear(); ignore_candidate_.clear(); } void SetStrategyToOperator(const OperatorInfoPtr &operator_info, const PrimitivePtr &prim, mindspore::HashMap<std::string, ValuePtr> attrs, bool, StrategyMap *stra_map, const std::string &strategy_key_name) { // In this case, the configured strategy should be extracted to help setting cost StrategyPtr strategyPtr; if (StrategyFound(attrs)) { strategyPtr = parallel::ExtractStrategy(attrs[IN_STRATEGY]); } else { strategyPtr = (*stra_map)[strategy_key_name]; } if (strategyPtr == nullptr) { return; } if (prim->name() == RESHAPE) { MS_LOG(EXCEPTION) << "Setting strategy for Reshape goes for nothing!"; return; } // Set cost for this configured strategy if (operator_info->SetCostUnderStrategy(strategyPtr) != SUCCESS) { MS_LOG(EXCEPTION) << "Failure: operator " << prim->name() << " SetCostUnderStrategy failed"; return; } const auto fully_use_devices = CostModelContext::GetInstance()->fully_use_device(); if (fully_use_devices) { // If configured to fully use devices, then checking for the user-specified strategy int64_t used_devices = operator_info->used_devices(); MS_EXCEPTION_IF_NULL(g_device_manager); auto total_device_num = g_device_manager->GetDeviceListByStageId(0).size(); // 'used_devices == -1' means that 'used_devices_' is not set // 'used_devices == 1' means that ALL-1 strategy, which is valid in auto-parallel if (used_devices == -1 || (used_devices != 1 && LongToSize(used_devices) != total_device_num)) { MS_LOG(EXCEPTION) << "In current configuration 'fully_use_devices' = True, " << "but the specified strategy uses device: " << used_devices << ", total devices: " << total_device_num << ", try to set 'set_algo_parameters(fully_use_devices=False)' " "in package 'mindspore.parallel'."; } } (void)configured_stra_ops_.emplace(operator_info, strategyPtr); } void ApplyApproximationForNode(const OperatorInfoPtr &operator_info) { auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi(); if (approximation) { operator_info->ApproximateStrategies(); MS_LOG(INFO) << "Approximated StrategyCost for: " << operator_info->name(); } } void AddOperatorToIgnoreCandidates(const PrimitivePtr &prim, const OperatorInfoPtr &operator_info) { if (prim->name() == CAST) { // add CAST into ignore_candidate (void)ignore_candidate_.insert(operator_info); } } OperatorInfoPtr CreateTheOperatorInfo(const PrimitivePtr &prim, const CNodePtr &cnode, bool is_last_nodes, StrategyMap *stra_map) { MS_EXCEPTION_IF_NULL(prim); MS_EXCEPTION_IF_NULL(cnode); auto attrs = prim->attrs(); std::vector<Shapes> shape_list = ExtractShape(cnode); if (shape_list.empty()) { MS_LOG(EXCEPTION) << "Failure: node " << cnode->UniqueId() << " failed to extract shape"; } // Create an OperatorInfo instance OperatorInfoPtr operator_info = NewOperatorInstance(prim, attrs, shape_list); MS_EXCEPTION_IF_NULL(operator_info); // Set the parameter information for this OperatorInfo (whether the inputs are parameters or not) std::vector<bool> parameter_info = ExtractInputParameterByNode(cnode); if (operator_info->set_is_parameter(parameter_info) != SUCCESS) { MS_LOG(ERROR) << "Initializing parameter information failed for operator: " << operator_info->name(); return nullptr; } // Set the data type for inputs and outputs of this OperatorInfo auto inputs_type_length = ExtractInputTypeLengthByNode(cnode); auto outputs_type = ExtractOutputTypeByNode(cnode); std::vector<size_t> outputs_type_length; outputs_type_length.reserve(outputs_type.size()); std::transform(outputs_type.begin(), outputs_type.end(), std::back_inserter(outputs_type_length), GetLengthOfDataType); if (operator_info->SetInputAndOutputTypeLength(inputs_type_length, outputs_type_length) != SUCCESS) { MS_LOG(ERROR) << "Setting the lengths of inputs and outputs failed for operator: " << operator_info->name(); return nullptr; } if (operator_info->set_outputs_type(outputs_type) != SUCCESS) { MS_LOG(ERROR) << "Setting the types of outputs failed for operator: " << operator_info->name(); return nullptr; } // When the 'inputs' contains numerical values for some operators, these values should be extracted from // ANF graph auto &inputs = cnode->inputs(); std::vector<ValuePtr> input_value; for (size_t index = 1; index < inputs.size(); ++index) { if (inputs[index]->isa<ValueNode>()) { input_value.push_back(GetValueNode(inputs[index])); } else { input_value.emplace_back(nullptr); } } operator_info->set_input_value(input_value); operator_info->set_outputs_dtype(cnode->Type()); operator_info->set_cnode(cnode); AddOperatorToIgnoreCandidates(prim, operator_info); // key of strategy map std::string strategy_key_name = ""; auto param_names = NodeParameterName(cnode, -1, 0); if (!param_names.empty()) { strategy_key_name = prim->name() + "_" + param_names[0].first; } bool load_strategy_from_ckpt = StrategyCheckpoint::GetInstance().LoadCheckPointOn() && stra_map->find(strategy_key_name) != stra_map->end(); // If no strategy has been configured for this operator, then candidate strategies are generated for // auto-strategy searching; if this primitive is CAST, we ignore the user-specified strategy. // if strategy is set to load from checkpoint, it is prefer to load strategy from checkpoint . if ((StrategyFound(attrs) && prim->name() != CAST) || load_strategy_from_ckpt) { SetStrategyToOperator(operator_info, prim, attrs, is_last_nodes, stra_map, strategy_key_name); return operator_info; } // Compute split_flag_list_, indicating which input has batch dimension. This is ONLY used for preparation for // BatchParallelInfo operator operator_info->ComputeBatchSplitFlagList(); Status retGenStra; if (AttrFound(attrs, STRATEGY_GEN_MODE) && GetValue<std::string>(attrs[STRATEGY_GEN_MODE]) == kDataParallel) { MS_LOG(INFO) << "generating batch parallel strategy..."; StrategyPtr strategyPtr = parallel::GenerateBatchParallelStrategy(operator_info, prim); retGenStra = operator_info->SetCostUnderStrategy(strategyPtr); attrs = prim->attrs(); operator_info->addAttr(IN_STRATEGY, attrs[GEN_STRATEGY]); // for d-rec } else { MS_LOG(INFO) << "auto-searching strategy..."; retGenStra = operator_info->GenerateStrategies(0); } if (retGenStra != SUCCESS) { MS_LOG(ERROR) << "Strategy search for Operator " << operator_info->name() << " failed."; return nullptr; } bool use_sp_and_dataset = ((ParallelContext::GetInstance()->strategy_search_mode() == kShardingPropagation) || (ParallelContext::GetInstance()->sharding_propagation())) && (operator_info->name().find(VIRTUAL_DATA_SET_INFO) != std::string::npos); if (use_sp_and_dataset) { const auto &swc_vec = operator_info->GetStrategyCost(); if (swc_vec.empty()) { MS_LOG(EXCEPTION) << "No available strategy for: " << operator_info->name(); } MS_EXCEPTION_IF_NULL(swc_vec[0]->strategy_ptr); (void)configured_stra_ops_.emplace(operator_info, swc_vec[0]->strategy_ptr); } // If 'approximation' is enabled, the 'strategy_cost' of each operator is approximated ApplyApproximationForNode(operator_info); return operator_info; } bool IsFindWrong(const OperatorInfoPtr current_op_ptr, const std::string &prim_name) { bool is_find_wrong = (current_op_ptr->name().find(VIRTUAL_DATA_SET_INFO) == std::string::npos) && (current_op_ptr->name().find(BATCH_PARALLEL) == std::string::npos) && (current_op_ptr->name().find(prim_name + "Info") == std::string::npos); if (prim_name == GATHERV2) { is_find_wrong = is_find_wrong && (current_op_ptr->name().find(prim_name + "PInfo") == std::string::npos); } return is_find_wrong; } void AddSharedTensorWhenMultiUsers( const std::pair<std::string, std::pair<AnfNodePtr, AnfNodeIndexSet>> &parameter_users_info) { auto users_set = parameter_users_info.second.second; if (users_set.size() > 1) { MS_LOG(INFO) << "Parameter " << parameter_users_info.first << " has " << users_set.size() << " users."; std::vector<std::string> user_names; for (auto user : users_set) { MS_LOG(INFO) << "with ID: " << user.first->UniqueId(); user_names.push_back(user.first->UniqueId()); } entire_costgraph->add_shared_tensor(user_names); } } // Using CNode's UniqueIds to construct nodes Status ConstructCostGraphNodesByUniqueId(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &) { MS_LOG(INFO) << "Constructing nodes for cost graph begins."; // The map from CNode's UniqueId to its operatorInfo std::map<std::string, OperatorInfoPtr> from_cnode_to_info; // The operator_infos in a loop std::vector<OperatorInfoPtr> operators_in_forloop; // Key: i-th loop; Value: index of 'operators_in_forloop' std::map<size_t, size_t> loop_to_ops; // extract strategy from checkpoint for multi-train StrategyMap stra_map; if (StrategyCheckpoint::GetInstance().LoadCheckPointOn()) { if (StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) { MS_LOG(EXCEPTION) << "Load strategy checkpoint failed"; } } for (auto &node : all_nodes) { // NOTE: we only care about splittable Primitive operators auto cnode = node->cast<CNodePtr>(); bool bool_result = (cnode == nullptr) || (!IsValueNode<Primitive>(cnode->input(0))); if (bool_result) { continue; } ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>(); if (!IsAutoParallelCareNode(cnode)) { // Needed by rec_parser if (ParallelContext::GetInstance()->strategy_search_mode() == kRecursiveProgramming) { auto prev_cnode = GetInternalOperatorInfo(cnode, prim_anf_node); if (prev_cnode != nullptr) { entire_costgraph->add_tuple_getitem(std::make_pair(cnode->UniqueId(), prev_cnode->UniqueId())); } } continue; } PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node); MS_EXCEPTION_IF_NULL(prim); auto search_cnode = from_cnode_to_info.find(cnode->UniqueId()); if (search_cnode == from_cnode_to_info.end()) { size_t loop_index = 0; bool is_in_loop = GetLoopIndexFromCNode(cnode, &loop_index); const auto single_loop = CostModelContext::GetInstance()->dp_algo_single_loop(); if (single_loop && is_in_loop && (loop_to_ops[loop_index] < operators_in_forloop.size())) { const auto &current_op_ptr = operators_in_forloop[loop_to_ops[loop_index]]; if (IsFindWrong(current_op_ptr, prim->name())) { MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name() << " does not match the Prim: " << prim->name() << ". The fullname_with_scope: " << cnode->fullname_with_scope(); } loop_to_ops[loop_index]++; cnode->set_user_data<OperatorInfo>(current_op_ptr); MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << ", CNode fullname_with_scope: " << cnode->fullname_with_scope() << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name(); (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueId(), current_op_ptr)); continue; } bool is_last_nodes = IsPrimitiveCNode(cnode, prim::kPrimVirtualOutput); auto operator_info = CreateTheOperatorInfo(prim, cnode, is_last_nodes, &stra_map); if (operator_info == nullptr) { return FAILED; } // Needed by rec_parser operator_info->set_type(prim->name()); operator_info->set_last_node_flag(is_last_nodes); std::vector<std::string> inputs_tensor_name = ExtractInputsTensorName(cnode); entire_costgraph->AddOperator(operator_info); cnode->set_user_data<OperatorInfo>(operator_info); MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << ", CNode fullname_with_scope: " << cnode->fullname_with_scope() << " is set OperatorInfo: " << operator_info->name() << ", Primitive: " << prim->name(); (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueId(), operator_info)); if (single_loop && is_in_loop) { operators_in_forloop.push_back(operator_info); ops_in_a_loop_.insert(operator_info->name()); loop_to_ops[loop_index]++; } // Needed by rec_parser entire_costgraph->add_inputs_tensor_name(inputs_tensor_name); } else { // Two CNODEs' UniqueIds should not be equal MS_LOG(EXCEPTION) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << " is set OperatorInfo: " << search_cnode->second->name() << ", Primitive: " << prim->name(); } } MS_LOG(INFO) << "Constructing nodes for cost graph ends."; // Needed by rec_parser 2 for (auto &node : all_nodes) { if (node->isa<Parameter>()) { ParameterUsersInfo parameter_users_info = FindParameterUsers(node, IsParallelCareNode); AddSharedTensorWhenMultiUsers(parameter_users_info); } } return SUCCESS; } void SetOperatorToCNode(const OperatorInfoPtr &current_op_ptr, const PrimitivePtr &prim, const CNodePtr &cnode) { if (current_op_ptr == nullptr) { MS_LOG(EXCEPTION) << "Find " << prim->name() << " from CostGraph failed."; } else { if (IsFindWrong(current_op_ptr, prim->name())) { MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name() << " does not match the Prim: " << prim->name(); } // Needed by rec_parser ModifyInputsTensorNameListIfOperatorInfoCreated(current_op_ptr->name(), cnode->UniqueId()); cnode->set_user_data<OperatorInfo>(current_op_ptr); MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << ", CNode fullname_with_scope: " << cnode->fullname_with_scope() << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name(); } } // Using CNode's UniqueIdThroughCopys to construct nodes Status ConstructCostGraphNodesByUniqueIdTC(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &) { MS_LOG(INFO) << "Constructing nodes for cost graph begins."; // The map from CNode's UniqueIdThroughCopy to its operatorInfo std::map<std::string, OperatorInfoPtr> from_cnode_to_info; // The operator_infos in a loop std::vector<OperatorInfoPtr> operators_in_forloop; // Key: i-th loop; Value: index of 'operators_in_forloop' std::map<size_t, size_t> loop_to_ops; // extract strategy from checkpoint for multi-train StrategyMap stra_map; if (StrategyCheckpoint::GetInstance().LoadCheckPointOn() && StrategyCheckpoint::GetInstance().Load(&stra_map) != SUCCESS) { MS_LOG(WARNING) << "Load strategy checkpoint failed"; return FAILED; } for (auto &node : all_nodes) { // NOTE: we only care about splittable Primitive operators auto cnode = node->cast<CNodePtr>(); if ((cnode == nullptr) || (!IsValueNode<Primitive>(cnode->input(0)))) { continue; } ValueNodePtr prim_anf_node = cnode->input(0)->cast<ValueNodePtr>(); if (!IsAutoParallelCareNode(cnode)) { // Needed by rec_parser if (ParallelContext::GetInstance()->strategy_search_mode() == kRecursiveProgramming) { auto prev_cnode = GetInternalOperatorInfo(cnode, prim_anf_node); if (prev_cnode != nullptr) { entire_costgraph->add_tuple_getitem(std::make_pair(cnode->UniqueId(), prev_cnode->UniqueId())); } } continue; } PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node); // Find the operatorInfo if it exists auto search_cnode = from_cnode_to_info.find(cnode->UniqueIdThroughCopy()); if (search_cnode == from_cnode_to_info.end()) { size_t loop_index = 0; bool is_in_loop = GetLoopIndexFromCNode(cnode, &loop_index); const auto single_loop = CostModelContext::GetInstance()->dp_algo_single_loop(); bool is_op_created = single_loop && is_in_loop && (loop_to_ops[loop_index] < operators_in_forloop.size()); if (is_op_created) { const auto &current_op_ptr = operators_in_forloop[loop_to_ops[loop_index]]; if (IsFindWrong(current_op_ptr, prim->name())) { MS_LOG(EXCEPTION) << "The OperatorInfo: " << current_op_ptr->name() << " does not match the Prim: " << prim->name() << ". The fullname_with_scope: " << cnode->fullname_with_scope(); } loop_to_ops[loop_index]++; cnode->set_user_data<OperatorInfo>(current_op_ptr); MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << ", CNode fullname_with_scope: " << cnode->fullname_with_scope() << " is set OperatorInfo: " << current_op_ptr->name() << ", Primitive: " << prim->name(); (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueIdThroughCopy(), current_op_ptr)); continue; } // In this case, the corresponding OperatorInfo is not created, create the new one. bool is_last_nodes = IsPrimitiveCNode(cnode, prim::kPrimVirtualOutput); auto operator_info = CreateTheOperatorInfo(prim, cnode, is_last_nodes, &stra_map); MS_EXCEPTION_IF_NULL(operator_info); // Needed by rec_parser operator_info->set_type(prim->name()); operator_info->set_last_node_flag(is_last_nodes); std::vector<std::string> inputs_tensor_name = ExtractInputsTensorName(cnode); entire_costgraph->AddOperator(operator_info); cnode->set_user_data<OperatorInfo>(operator_info); MS_LOG(INFO) << "The CNode with UniqueId: " << cnode->UniqueId() << " and UniqueIdThroughCopy: " << cnode->UniqueIdThroughCopy() << ", CNode fullname_with_scope: " << cnode->fullname_with_scope() << " is set OperatorInfo: " << operator_info->name() << ", Primitive: " << prim->name(); (void)from_cnode_to_info.emplace(std::make_pair(cnode->UniqueIdThroughCopy(), operator_info)); if (single_loop && is_in_loop) { operators_in_forloop.push_back(operator_info); ops_in_a_loop_.insert(operator_info->name()); loop_to_ops[loop_index]++; } // Needed by rec_parser entire_costgraph->add_inputs_tensor_name(inputs_tensor_name); } else { SetOperatorToCNode(search_cnode->second, prim, cnode); } } MS_LOG(INFO) << "Constructing nodes for cost graph ends."; // Needed by rec_parser 2 for (auto &node : all_nodes) { if (node->isa<Parameter>()) { ParameterUsersInfo parameter_users_info = FindParameterUsers(node, IsParallelCareNode); AddSharedTensorWhenMultiUsers(parameter_users_info); } } return SUCCESS; } void CreateEdgeBetweenTwoOps(const OperatorInfoPtr &prev_op_info, const OperatorInfoPtr &node_op_info, const CNodePtr &cnode, const CNodePtr &prev_cnode, const PrimitivePtr &prim, const PrimitivePtr &prev_prim, size_t output_index, size_t input_index, size_t *edge_count) { std::string edge_name = prev_op_info->name() + OPERATOR_TO_OPERATOR_CONNECTOR + node_op_info->name(); // If the edge between these two operators already has been added, then the edge will not be added again. if (entire_costgraph->IsEdgeInCostGraph(edge_name, output_index, input_index - 1)) { return; } EdgePtr edge_ptr; MS_LOG(INFO) << "Creating edge: " << edge_name; if (IsOperatorsInTwoSeparateLoops(prev_cnode, cnode)) { MS_LOG(INFO) << "prev_cnode_fullname: " << prev_cnode->fullname_with_scope() << ", cnode_fullname: " << cnode->fullname_with_scope(); MS_LOG(INFO) << "The two operators in two separate for-loops, thus skip the edge."; return; } const auto stra_follow = CostModelContext::GetInstance()->elementwise_stra_follow(); bool follow_strategy = (prim->name() == RESHAPE) || (prev_prim->name() == RESHAPE) || (stra_follow && IsElementWiseOperator(prev_prim->name())); if (follow_strategy) { // Redistribution in not allowed on the edge. // Elementwise operators have the same strategy as their previous operators. edge_ptr = std::make_shared<Edge>(edge_name, prev_op_info, node_op_info, output_index, input_index - 1, false, true); } else { edge_ptr = std::make_shared<Edge>(edge_name, prev_op_info, node_op_info, output_index, input_index - 1, false); } // Init costs for this edge if (edge_ptr->InitEdgeCost() != SUCCESS) { MS_LOG(EXCEPTION) << "Edge cost initialization failed"; } node_op_info->AddPrevEdge(edge_ptr); prev_op_info->AddSuccEdge(edge_ptr); entire_costgraph->AddEdge(prev_op_info, node_op_info, edge_ptr); bool use_sp = (ParallelContext::GetInstance()->strategy_search_mode() == kShardingPropagation) || (ParallelContext::GetInstance()->sharding_propagation()); if (use_sp && (prev_prim->name() == CAST) && (configured_stra_ops_.find(node_op_info) != configured_stra_ops_.end())) { const auto next_op_stra = configured_stra_ops_[node_op_info]; const auto cast_stra = edge_ptr->GetPrevOpStrategyByNextOpStrategyWithMiniComm(next_op_stra); if (cast_stra == nullptr) { MS_LOG(EXCEPTION) << "No available strategy for: " << prev_op_info->name(); } prev_op_info->ClearStrategyCost(); if (prev_op_info->SetCostUnderStrategy(cast_stra) != SUCCESS) { MS_LOG(EXCEPTION) << "Failure: operator " << prev_op_info->name() << " SetCostUnderStrategy failed"; } if (edge_ptr->InitEdgeCost() != SUCCESS) { MS_LOG(EXCEPTION) << "Edge cost re-initialization failed."; } MS_LOG(INFO) << "Set strategy for: " << prev_op_info->name() << " under the strategy of: " << node_op_info->name(); (void)configured_stra_ops_.emplace(prev_op_info, cast_stra); } MS_LOG(INFO) << "Successfully adding the edge between " << prev_op_info->name() << " and " << node_op_info->name(); (*edge_count)++; } void ApplyApproximationForGraphs() { // If 'approximation' is enabled, the edges need to be checked have effective costs. auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi(); if (approximation) { entire_costgraph->CheckApproximateCostGraphEdges(); } } static void ConstructCNodeCostGraphEdges(const mindspore::CNodePtr &cnode) { auto &inputs = cnode->inputs(); ValueNodePtr prim_anf_node = inputs[0]->cast<ValueNodePtr>(); PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node); size_t edge_count = 0; auto node_op_info = cnode->user_data<OperatorInfo>(); for (size_t i = 1; i < inputs.size(); ++i) { auto prev_cnode = inputs[i]->cast<CNodePtr>(); bool bool_result_prev_cnode = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0))); if (bool_result_prev_cnode) { continue; } ValueNodePtr prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>(); PrimitivePtr prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>(); size_t output_index = 0; while ((IsAutoParallelCareNode(prev_cnode)) || (prev_prim->name() == prim::kTupleGetItem) || (prev_prim->name() == DEPEND)) { if (IsAutoParallelCareNode(prev_cnode)) { auto prev_op_info = prev_cnode->user_data<OperatorInfo>(); CreateEdgeBetweenTwoOps(prev_op_info, node_op_info, cnode, prev_cnode, prim, prev_prim, output_index, i, &edge_count); break; } else if (prev_prim->name() == prim::kTupleGetItem) { // In this case, 'prev_anf_node' is 'tuple_getitem', the actual precursor node is node before // this 'tuple_getitem' MS_LOG(INFO) << "Jumping the 'tuple_getitem' operator."; output_index = LongToSize(GetValue<int64_t>(GetValueNode(prev_cnode->input(2)))); prev_cnode = prev_cnode->input(1)->cast<CNodePtr>(); bool bool_result_tuple = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0))); if (bool_result_tuple) { break; } prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>(); prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>(); if (!IsAutoParallelCareNode(prev_cnode)) { MS_LOG(EXCEPTION) << "Did not create OperatorInfo for : " << prev_prim->name(); } MS_LOG(INFO) << "Jumped the 'tuple_getitem' operator, " << "and creating an edge between the Operator before " << "'tuple_getitem' and the Operator after 'tuple_getitem'."; } else if (prev_prim->name() == DEPEND) { // In this case, 'prev_anf_node' is 'depend', the actual precursor node is node before // this 'depend' MS_LOG(INFO) << "Jumping the 'depend' operator."; prev_cnode = prev_cnode->input(1)->cast<CNodePtr>(); bool bool_result_depend = (prev_cnode == nullptr) || (!IsValueNode<Primitive>(prev_cnode->input(0))); if (bool_result_depend) { break; } prev_prim_anf_node = prev_cnode->input(0)->cast<ValueNodePtr>(); prev_prim = prev_prim_anf_node->value()->cast<PrimitivePtr>(); MS_LOG(INFO) << "Jumped the 'depend' operator, " << "and creating an edge between the Operator before " << "'depend' and the Operator after 'depend'."; } } } MS_LOG(INFO) << "Successfully created " << edge_count << " edges for: " << node_op_info->name(); } void ConstructCostGraphEdges(const std::vector<AnfNodePtr> &all_nodes) { // Step 2 MS_LOG(INFO) << "Constructing edges for cost graph begins."; for (auto &node : all_nodes) { auto cnode = node->cast<CNodePtr>(); if ((cnode == nullptr) || !IsValueNode<Primitive>(cnode->input(0))) { continue; } if (!IsAutoParallelCareNode(cnode)) { continue; } ConstructCNodeCostGraphEdges(cnode); } ApplyApproximationForGraphs(); MS_LOG(INFO) << "Constructing edges for cost graph ends."; } void ApplyApproximationForParaNode(const OperatorInfoPtr &target_op_info) { // If 'approximation' is enabled, the edges need to be checked have effective costs. auto approximation = CostModelContext::GetInstance()->dp_algo_enable_approxi(); if (approximation) { target_op_info->ExactStrategiesAndRelatedEdges(); } } void AugmentCostGraph(const std::vector<AnfNodePtr> &all_nodes) { // Step 3 for (auto &node : all_nodes) { ParameterUsersInfo parameter_users_info = FindParameterUsers(node, IsAutoParallelCareNode); auto parameter_name = parameter_users_info.first; auto target_parameter = parameter_users_info.second.first; auto target_set = parameter_users_info.second.second; if (target_set.size() <= 1) { continue; } // Rule out the case when a Parameter being used by a Operator, but the Operator appears in multiple CNODEs std::set<std::string> target_without_duplicate; for (auto &target : target_set) { auto target_cnode = target.first->cast<CNodePtr>(); auto input_index = target.second; (void)target_without_duplicate.insert(std::to_string(input_index) + target_cnode->user_data<OperatorInfo>()->name()); } if (target_without_duplicate.size() <= 1) { continue; } // Here, it is sure that this Parameter (RefKey) is being used by multiple Operators. OperatorInfoPtr tmp_identity_ptr; bool new_identity = false; std::string tmp_identity_name; auto returned_identity = entire_costgraph->FindTmpIdentityByParameterName(parameter_name); if (returned_identity != nullptr) { // In this case, the TmpIdentityInfo instance has already been created new_identity = false; tmp_identity_ptr = returned_identity; tmp_identity_name = tmp_identity_ptr->name(); } else { // In the case, the TmpIdentityInfo instance has NOT been created. Thus, a new one is created. new_identity = true; // 1) extract input shape from this Parameter MS_EXCEPTION_IF_NULL(target_parameter); AbstractBasePtr abstract = target_parameter->abstract(); if (abstract == nullptr) { MS_LOG(EXCEPTION) << "Failure: abstract is nullptr"; } auto input_shape = dyn_cast<abstract::Shape>(abstract->GetShapeTrack()); if (input_shape == nullptr) { MS_LOG(EXCEPTION) << "Failure: input_shape is nullptr"; } Shape shape = input_shape->shape(); Shapes inputs_shape = {shape}; Shapes outputs_shape = {shape}; // 2) init the attr mindspore::HashMap<std::string, ValuePtr> attr = {}; // Create the TmpIdentity instance tmp_identity_ptr = std::make_shared<TmpIdentityInfo>(inputs_shape, outputs_shape, attr); tmp_identity_ptr->set_name(tmp_identity_ptr->name() + std::to_string(TOTAL_OPS)); TOTAL_OPS++; tmp_identity_ptr->set_refkey_parameter_name(parameter_name); // Set the parameter and type lengths for inputs and outputs std::vector<bool> is_parameter; auto casted_target_parameter = target_parameter->cast<ParameterPtr>(); MS_EXCEPTION_IF_NULL(casted_target_parameter); is_parameter.push_back(ParameterRequireGrad(casted_target_parameter)); if (tmp_identity_ptr->set_is_parameter(is_parameter) != SUCCESS) { MS_LOG(EXCEPTION) << "Setting parameter for TmpIdentityInfo failed"; } auto node_type = target_parameter->Type(); if (node_type->isa<mindspore::TensorType>()) { auto input_element_type = node_type->cast<mindspore::TensorTypePtr>()->element(); std::vector<size_t> type_length = {GetLengthOfDataType(input_element_type)}; if (tmp_identity_ptr->SetInputAndOutputTypeLength(type_length, type_length) != SUCCESS) { MS_LOG(EXCEPTION) << "Setting input and output type length for TmpIdentityInfo failed"; } } else { MS_LOG(EXCEPTION) << "Unknown type: " << node_type->type_name(); } // Generate strategies for this TmpIdentityInfo instance; if (tmp_identity_ptr->GenerateStrategies(0) != SUCCESS) { MS_LOG(EXCEPTION) << "Strategy search for Operator failed : " << tmp_identity_ptr->name(); } } // A flag recording whether new edges have been created or not bool add_identity_edge = false; // Create edges between this TmpIdentityInfo instance and subsequent Operator instances for (auto &target : target_set) { auto target_cnode = target.first->cast<CNodePtr>(); auto input_index = target.second; auto target_op_info = target_cnode->user_data<OperatorInfo>(); std::string edge_name = std::string(IDENTITY_INFO) + OPERATOR_TO_OPERATOR_CONNECTOR + target_op_info->name(); // If the edge between these two operators already has been added, then the edge will not be added again. if (entire_costgraph->IsEdgeInCostGraph(edge_name, 0, LongToSize(input_index - 1))) { continue; } std::shared_ptr<Edge> edge_ptr = std::make_shared<Edge>(edge_name, tmp_identity_ptr, target_op_info, 0, input_index - 1, false, true); ApplyApproximationForParaNode(target_op_info); if (edge_ptr->InitEdgeCost() != SUCCESS) { MS_LOG(EXCEPTION) << "Edge cost initialization failed"; } target_op_info->AddPrevEdge(edge_ptr); tmp_identity_ptr->AddSuccEdge(edge_ptr); entire_costgraph->AddEdge(tmp_identity_ptr, target_op_info, edge_ptr); MS_LOG(INFO) << "Successfully adding the edge between " << tmp_identity_ptr->name() << " and " << target_op_info->name(); add_identity_edge = true; } if (new_identity && add_identity_edge) { // Add the TmpIdentityInfo to CostGraph if BOTH two conditions are satisfied entire_costgraph->AddOperator(tmp_identity_ptr); } } } void ReshapeCostCompute(const std::vector<AnfNodePtr> &all_nodes) { mindspore::HashSet<std::string> op_cache; for (auto node : all_nodes) { auto cnode = node->cast<CNodePtr>(); if (!FindReshape(cnode, &op_cache)) { continue; } MS_ASSERT(cnode->inputs().size() == 3); // get previous node's strategy_cost_ auto pre_node = cnode->input(1); if (IsPrimitiveCNode(pre_node, prim::kPrimLoad)) { pre_node = pre_node->cast<CNodePtr>()->input(1); } int64_t out_index = 0; OperatorInfoPtr pre_operator_info; std::vector<std::shared_ptr<StrategyWithCost>> pre_stra_costs; auto operator_info = cnode->user_data<OperatorInfo>(); if (pre_node->isa<Parameter>()) { auto reshape_info1 = std::dynamic_pointer_cast<ReshapeInfo>(operator_info); reshape_info1->SetCostForReshapeWithParameter(); pre_operator_info = reshape_info1; pre_stra_costs = reshape_info1->strategy_cost(); } else { if (!FindReshapePreNodeStraCosts(pre_node, &pre_operator_info, &out_index, 0)) { MS_LOG(EXCEPTION) << "FindReshapePreNodeStraCosts for reshape failed"; } pre_stra_costs = pre_operator_info->strategy_cost(); } // get next node's strategy_cost_ int64_t in_index = 0; OperatorInfoPtr next_operator_info; bool is_next_reshape = false; std::vector<std::shared_ptr<StrategyWithCost>> next_stra_costs; bool find_next_node = FindReshapeNextNodeStraCosts(cnode, &next_operator_info, &in_index, &is_next_reshape, 0); if (!find_next_node) { MS_LOG(INFO) << "FindReshapeNextNodeStraCosts for reshape failed"; } // set input_layout and output_layout for reshape. // init reshape and set cost for each input_layout and output_layout. auto reshape_info = std::dynamic_pointer_cast<ReshapeInfo>(operator_info); reshape_info->set_pre_operator_name(pre_operator_info->name()); reshape_info->set_pre_operator_index(out_index); if (find_next_node) { next_stra_costs = next_operator_info->strategy_cost(); reshape_info->set_next_operator_name(next_operator_info->name()); reshape_info->set_next_operator_index(in_index); } bool is_prev_param = pre_node->isa<Parameter>(); if (reshape_info->GenerateStrategyCosts(pre_stra_costs, next_stra_costs, out_index, in_index, is_prev_param, is_next_reshape) != SUCCESS) { MS_LOG(EXCEPTION) << "reshape generate strategy_costs failed!"; } } } Status IgnoreOperatorsInCostGraph() { for (const auto &op : ignore_candidate_) { auto cnodes = op->cnodes(); for (auto &cnode : cnodes) { MS_EXCEPTION_IF_NULL(cnode); cnode->set_user_data<OperatorInfo>(nullptr); } } return SUCCESS; } Status ParallelStrategySearch(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) { // There are 4 meta-steps to determine the parallelization strategy for the ANF graph. // Step 1: Traverse the ANF graph, and create NODEs for costgraph: // create the OperatorInfo object for each primitive, and enumerate the parallelization strategies // for each OperatorInfo; // Step 1.1: Deal with 'Reshape': // For 'Reshape', it takes its previous operator's layout as its input layout, and takes its next operator's // layout as its output layout. // Step 2: Traverse the ANF graph, and create EDGES for costgraph: // create the Edge object for each pair of OperatorInfo, and enumerate the parallelization strategies // for each edge, based on the strategies of two OperatorInfos; // Step 3: Augment the costgraph: // taking care for the case of a single Parameter being used by multiple operators. Create a TmpIdentity // operator for this Parameter, and add an edge for the use of this Parameter by each // subsequent operator; // Step 3.1: Calculate memory usage: // note the memory usage calculation is different in training phase and inference phase. // Step 4: Run the strategy searching algorithm: // If 'sharding_propagation' is configured to be true, then the configured-sharding-strategies will propagate // to the non-configured operators, with the goal of minimizing redistribution cost. // Otherwise, DP algorithm is used to search strategy of the costgraph. Note that there may be several connected // components in the costgraph, and the DP algorithm runs on each of them. // // OUTPUT: the determined strategy for each operator. InitCostGraph(); // Step 1 if (CostModelContext::GetInstance()->is_multi_subgraphs()) { if (ConstructCostGraphNodesByUniqueIdTC(all_nodes, root) == SUCCESS) { MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are " << entire_costgraph->GetOperators().size() << " operators."; } else { MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed."; } } else { if (ConstructCostGraphNodesByUniqueId(all_nodes, root) == SUCCESS) { MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are " << entire_costgraph->GetOperators().size() << " operators."; } else { MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed."; } } // Step 1.1 ReshapeCostCompute(all_nodes); // Step 2 ConstructCostGraphEdges(all_nodes); MS_LOG(INFO) << "Constructing edges for cost graph succeeded. There are " << entire_costgraph->GetOperators().size() << " operators, and " << entire_costgraph->GetNumEdges() << " edges."; // Step 3: Augment the costgraph. AugmentCostGraph(all_nodes); auto num_ops = entire_costgraph->GetOperators().size(); SetOpsNumToExecutor(num_ops); auto num_edges = entire_costgraph->GetNumEdges(); MS_LOG(INFO) << "After the augmenting procedure, there are " << num_ops << " operators, and " << num_edges << " edges."; // Step 3.1: Calculate the memory usage if (entire_costgraph->CalculateMemoryCost() != SUCCESS) { MS_LOG(EXCEPTION) << "Calculating memory cost failed."; } // Step 4: run the strategy searching algorithm bool use_sp = (ParallelContext::GetInstance()->strategy_search_mode() == kShardingPropagation) || (ParallelContext::GetInstance()->sharding_propagation()); if (use_sp) { entire_costgraph->StrategyPropagate(configured_stra_ops_); } else if (GetStrategy(entire_costgraph) != SUCCESS) { MS_LOG(ERROR) << "Strategy search for cost-graph fails"; return FAILED; } MS_LOG(INFO) << "Searching strategy succeeded."; if (entire_costgraph->InitSelectedStrategy() == SUCCESS) { MS_LOG(INFO) << "Init selected strategy succeeded."; } else { MS_LOG(EXCEPTION) << "Init selected strategy failed."; } // print the selected strategy for (auto &op : entire_costgraph->GetOperators()) { StrategyPtr s_strategy = op->selected_strategy(); MS_LOG(INFO) << op->name() << " : The strategy is:"; PrintStrategy(s_strategy); } // Remove some operatorInfo from the CNODEs (void)IgnoreOperatorsInCostGraph(); ops_in_a_loop_.clear(); configured_stra_ops_.clear(); ignore_candidate_.clear(); return SUCCESS; } std::vector<std::vector<std::string>> RecInputTensorNames(const std::map<std::string, std::string>::iterator &it, std::vector<std::vector<std::string>> input_tensor_names) { for (size_t j = 0; j < input_tensor_names.size(); j++) { for (size_t k = 0; k < input_tensor_names[j].size(); k++) { if (it->first == input_tensor_names[j][k]) { input_tensor_names[j][k] = it->second; break; } } } return input_tensor_names; } CNodePtr GetInternalOperatorInfo(const CNodePtr &cnode, const ValueNodePtr &prim_anf_node) { PrimitivePtr prim = GetValueNode<PrimitivePtr>(prim_anf_node); if (prim->name() == prim::kTupleGetItem || prim->name() == DEPEND) { auto prev_cnode = cnode->input(1)->cast<CNodePtr>(); if (prev_cnode == nullptr || !IsValueNode<Primitive>(prev_cnode->input(0))) { return nullptr; } auto prev_prim = prev_cnode->input(0)->cast<ValueNodePtr>()->value()->cast<PrimitivePtr>(); while (prev_prim->name() == prim::kTupleGetItem || prev_prim->name() == DEPEND) { prev_cnode = prev_cnode->input(1)->cast<CNodePtr>(); if (prev_cnode == nullptr || !IsValueNode<Primitive>(prev_cnode->input(0))) { return nullptr; } prev_prim = prev_cnode->input(0)->cast<ValueNodePtr>()->value()->cast<PrimitivePtr>(); } return prev_cnode; } return nullptr; } void ModifyInputsTensorNameListIfOperatorInfoCreated(const std::string &name, const std::string &uniqueid) { size_t iter_ops = 0; for (auto op : entire_costgraph->GetOperators()) { if (op->name() == name) { break; } iter_ops = iter_ops + 1; } std::vector<std::vector<std::string>> input_tensor_names = entire_costgraph->get_inputs_tensor_name_list(); for (size_t i = 0; i < input_tensor_names.size(); i++) { for (size_t j = 0; j < input_tensor_names[i].size(); j++) { if (input_tensor_names[i][j] == uniqueid) { input_tensor_names[i][j] = input_tensor_names[iter_ops][0]; } } } entire_costgraph->set_inputs_tensor_name_list(input_tensor_names); } size_t FindOperatorIndexById(const std::string &unique_id, const std::vector<std::vector<std::string>> &input_tensor_names) { for (size_t i = 0; i < input_tensor_names.size(); i++) { if (input_tensor_names[i][0] == unique_id) { return i; } } return SIZE_MAX; } std::vector<std::vector<size_t>> GetSharedTensorsOps( const std::vector<std::vector<std::string>> &shared_tensors_ops_names, const std::vector<std::vector<std::string>> &input_tensor_names) { std::vector<std::vector<size_t>> shared_tensors_ops; for (auto user_names : shared_tensors_ops_names) { std::vector<size_t> users_index; for (size_t i = 0; i < user_names.size(); i++) { size_t user_index = FindOperatorIndexById(user_names[i], input_tensor_names); if (user_index != SIZE_MAX) { users_index.push_back(user_index); } } shared_tensors_ops.push_back(users_index); } return shared_tensors_ops; } Status ParallelStrategyRecSearch(const std::vector<AnfNodePtr> &all_nodes, const FuncGraphPtr &root) { InitCostGraph(); if (CostModelContext::GetInstance()->is_multi_subgraphs()) { if (ConstructCostGraphNodesByUniqueIdTC(all_nodes, root) == SUCCESS) { MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are " << entire_costgraph->GetOperators().size() << " operators."; } else { MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed."; } } else { if (ConstructCostGraphNodesByUniqueId(all_nodes, root) == SUCCESS) { MS_LOG(INFO) << "Constructing nodes for cost graph succeeded. There are " << entire_costgraph->GetOperators().size() << " operators."; } else { MS_LOG(EXCEPTION) << "Constructing nodes for cost graph failed."; } } ReshapeCostCompute(all_nodes); ConstructCostGraphEdges(all_nodes); auto ops = entire_costgraph->GetOperators(); std::vector<std::vector<std::string>> input_tensor_names = entire_costgraph->get_inputs_tensor_name_list(); // Needed by rec_parser 2 auto shared_tensors_ops_name_list = entire_costgraph->get_shared_tensors_ops_name_list(); auto tuple_getitem_list = entire_costgraph->get_tuple_getitem_list(); for (auto it = tuple_getitem_list.begin(); it != tuple_getitem_list.end();) { input_tensor_names = RecInputTensorNames(it++, input_tensor_names); } std::shared_ptr<Graph> graph = ParseGraph(ops, input_tensor_names); std::vector<std::vector<size_t>> shared_tensors_ops = GetSharedTensorsOps(shared_tensors_ops_name_list, input_tensor_names); std::shared_ptr<std::vector<std::vector<size_t>>> eli_list = std::make_shared<std::vector<std::vector<size_t>>>(); std::shared_ptr<std::vector<size_t>> index_list = std::make_shared<std::vector<size_t>>(); graph = EliminateGraph(graph, eli_list, index_list); size_t num_device = g_device_manager->DeviceNum(); const auto device_memory = CostModelContext::GetInstance()->device_memory_capacity(); if (PartitionForAllDevices(num_device, device_memory, graph) == SUCCESS) { MS_LOG(INFO) << "Partition Success With " << num_device << " devices."; } else { MS_LOG(ERROR) << "PartitionForAllDevices failed."; return FAILED; } bool is_training = true; if (!root->has_flag(kTraining)) { is_training = false; } GenerateStrategy(graph, ops, eli_list, input_tensor_names, index_list, is_training, shared_tensors_ops); if (entire_costgraph->InitSelectedStrategy() == SUCCESS) { MS_LOG(INFO) << "Init selected strategy succeeded."; } else { MS_LOG(ERROR) << "Init selected strategy failed."; return FAILED; } // print the selected strategy for (auto &op : entire_costgraph->GetOperators()) { StrategyPtr s_strategy = op->selected_strategy(); MS_LOG(INFO) << op->name() << " : The strategy is:"; PrintStrategy(s_strategy); } return SUCCESS; } } // namespace parallel } // namespace mindspore
/* * soyac - Soya Programming Language compiler * Copyright (c) 2009 Denis Washington <dwashington@gmx.net> * * This file is distributed under the terms of the MIT license. * See LICENSE.txt for details. */ #ifndef _PASS_RESULT_HPP #define _PASS_RESULT_HPP #include <list> #include "Problem.hpp" namespace soyac { /** * Holds information about the result of a compiler pass. * * PassResult instances are created using the PassResultBuilder class. */ class PassResult { public: /** * Iterates over the problems found in the pass. */ typedef std::list<Problem*>::const_iterator problems_iterator; /** * PassResult destructor. */ ~PassResult(); /** * Returns @c true if the compiler pass that returned the PassResult * found any problems (errors or warnings) in the processed abstract * syntax tree. * * @return @c true if the pass found problems; * @c false otherwise. */ bool foundProblems() const; /** * Returns @c true if the compiler pass that returned the PassResult * found any errors in the processed abstract syntax tree. * * @return @c true if the pass found errors; * @c false otherwise. */ bool foundErrors() const; /** * Returns a constant iterator pointing to the first problem found by * the compiler pass that returned the PassResult. * * @return The start iterator for the found problems. */ problems_iterator problems_begin() const; /** * Returns a constant iterator pointing past the last problem found by * the compiler pass that returned the PassResult. * * @return The end iterator for the found problems. */ problems_iterator problems_end() const; private: std::list<Problem*> mProblems; bool mFoundErrors; /* * PassResultBuilder is made a friend class of PassResult so that it can * directly add problems to a PassResult's internal problem list. */ friend class PassResultBuilder; /* * PassResult constructor. */ PassResult(); }; } #endif
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletdb.h" #include "base58.h" #include "protocol.h" #include "serialize.h" #include "sync.h" #include "wallet.h" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/foreach.hpp> using namespace std; using namespace boost; static uint64_t nAccountingEntryNumber = 0; extern bool fWalletUnlockStakingOnly; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx) { nWalletDBUpdated++; return Write(std::make_pair(std::string("tx"), hash), wtx); } bool CWalletDB::EraseTx(uint256 hash) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("tx"), hash)); } bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) { nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) return false; // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + vchPrivKey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end()); return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false); } bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta) { const bool fEraseUnencryptedKey = true; nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta)) return false; if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false)) return false; if (fEraseUnencryptedKey) { Erase(std::make_pair(std::string("key"), vchPubKey)); Erase(std::make_pair(std::string("wkey"), vchPubKey)); } return true; } bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey) { nWalletDBUpdated++; return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true); } bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript) { nWalletDBUpdated++; return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false); } bool CWalletDB::WriteBestBlock(const CBlockLocator& locator) { nWalletDBUpdated++; return Write(std::string("bestblock"), locator); } bool CWalletDB::ReadBestBlock(CBlockLocator& locator) { return Read(std::string("bestblock"), locator); } bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext) { nWalletDBUpdated++; return Write(std::string("orderposnext"), nOrderPosNext); } bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey) { nWalletDBUpdated++; return Write(std::string("defaultkey"), vchPubKey); } bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool) { return Read(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool) { nWalletDBUpdated++; return Write(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::ErasePool(int64_t nPool) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("pool"), nPool)); } bool CWalletDB::WriteMinVersion(int nVersion) { return Write(std::string("minversion"), nVersion); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64_t nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair > TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx *const pwtx = (*it).second.first; CAccountingEntry *const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } WriteOrderPosNext(nOrderPosNext); return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState &wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; if (wtx.CheckTransaction() && (wtx.GetHash() == hash)) wtx.BindWallet(pwallet); else { pwallet->mapWallet.erase(hash); return false; } // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; //// debug print //LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString()); //LogPrintf(" %12d %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()), // wtx.hashBlock.ToString(), // wtx.mapValue["message"]); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "key" || strType == "wkey") { CPubKey vchPubKey; ssKey >> vchPubKey; if (!vchPubKey.IsValid()) { strErr = "Error reading wallet database: CPubKey corrupt"; return false; } CKey key; CPrivKey pkey; uint256 hash = 0; if (strType == "key") { wss.nKeys++; ssValue >> pkey; } else { CWalletKey wkey; ssValue >> wkey; pkey = wkey.vchPrivKey; } // Old wallets store keys as "key" [pubkey] => [privkey] // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key // using EC operations as a checksum. // Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while // remaining backwards-compatible. try { ssValue >> hash; } catch(...){} bool fSkipCheck = false; if (hash != 0) { // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + pkey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), pkey.begin(), pkey.end()); if (Hash(vchKey.begin(), vchKey.end()) != hash) { strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt"; return false; } fSkipCheck = true; } if (!key.Load(pkey, vchPubKey, fSkipCheck)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (!pwallet->LoadKey(key, vchPubKey)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { wss.nCKeys++; vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) LogPrintf("%s\n", strErr); } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; LogPrintf("nFileVersion = %d\n", wss.nFileVersion); LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } void ThreadFlushWalletDB(const string& strFile) { // Make this thread recognisable as the wallet flushing thread RenameThread("CloudStorageIntegral-wallet"); static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (true) { MilliSleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0) { boost::this_thread::interruption_point(); map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { LogPrint("db", "Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (true) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif LogPrintf("copied wallet.dat to %s\n", pathDest.string()); return true; } catch(const filesystem::filesystem_error &e) { LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what()); return false; } } } MilliSleep(100); } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%d.bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) LogPrintf("Renamed %s to %s\n", filename, newFilename); else { LogPrintf("Failed to rename %s to %s\n", filename, newFilename); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); return false; } LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); bool fSuccess = allOK; Db* pdbCopy = new Db(&dbenv.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { LogPrintf("Cannot create database file %s\n", filename); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); delete pdbCopy; return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); }
#pragma once #include <list> #include <memory> #include "../util/vec.hpp" #include "../types.hpp" class Galaxy { private: unsigned long id; double size; // light years Vec3 position; // position of this galaxy within the universe, units of light years std::list<System_ptr> systems; Universe_ptr universe; public: Galaxy(Vec3 position, double size, unsigned long id); ~Galaxy(); static Galaxy_ptr generate(Vec3 position); System_ptr new_system(); System_ptr new_inhabitable_system(SystemObject_ptr &object); Vec3 get_position() const; unsigned long get_id() const; };
#pragma once #include <fstream> #include <string> #include <vector> #include "all_type_variant.hpp" #include "csv_meta.hpp" #include "type_cast.hpp" #include "types.hpp" namespace opossum { class CsvWriter { public: /* * Creates a new CsvWriter with the given file as output file. * @param file The file to output the csv to. */ explicit CsvWriter(const std::string& file, const ParseConfig& config = {}); void write(const AllTypeVariant& value); /* * Ends a row of entries in the csv file. */ void end_line(); protected: std::string _escape(const std::string& string); void _write_value(const AllTypeVariant& value); void _write_string_value(const std::string& value); std::ofstream _stream; ColumnID _current_col_count{0}; ParseConfig _config; }; } // namespace opossum
#include <iostream> int main(void) { std::cin.tie(0); std::ios_base::sync_with_stdio(0); int n, counter = 0, counterElse = 0; std::cin >> n; char mat[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { std::cin >> mat[i][j]; } } bool isPossible = mat[0][n-1] == mat[0][0] && mat[n-1][0] == mat[0][0] && mat[n-1][n-1] == mat[0][0]; if (isPossible) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (((i+j) == n-1 || i == j ) && mat[i][j] == mat[0][0]) { counter++; } else { if (mat[0][1] == mat[i][j] && mat[0][1] != mat[0][0]) { counterElse++; } } } } } if (counter == (n*2)-1 && (counter+counterElse == n*n) && isPossible) { std::cout << "YES\n"; } else { std::cout << "NO\n"; } return 0; }
/********************************************************************** Audacity: A Digital Audio Editor Audacity(R) is copyright (c) 1999-2008 Audacity Team. License: GPL v2 or later. See License.txt. ScoreAlignDialog.cpp <TODO: authors> ******************************************************************//** \class ScoreAlignDialog \brief ScoreAlignDialog is \TODO. It \TODO: description *//*******************************************************************/ #include "ScoreAlignDialog.h" #ifdef EXPERIMENTAL_SCOREALIGN // For compilers that support precompilation, includes "wx/wx.h". #include <wx/wxprec.h> #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/brush.h> #include <wx/button.h> #include <wx/choice.h> #include <wx/image.h> #include <wx/file.h> #include <wx/intl.h> #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/statusbr.h> #endif #include <fstream> #include <wx/dialog.h> #include "Prefs.h" #include "../ShuttleGui.h" #include "../lib-src/header-substitutes/allegro.h" #include "audioreader.h" #include "scorealign.h" #include "scorealign-glue.h" static std::unique_ptr<ScoreAlignDialog> gScoreAlignDialog{}; //IMPLEMENT_CLASS(ScoreAlignDialog, wxDialogWrapper) ScoreAlignDialog::ScoreAlignDialog(ScoreAlignParams &params) : wxDialogWrapper(NULL, -1, XO("Align MIDI to Audio"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { gScoreAlignDialog.reset(this); // Allows anyone to close dialog by calling // CloseScoreAlignDialog() gPrefs->Read(wxT("/Tracks/Synchronize/FramePeriod"), &p.mFramePeriod, float(SA_DFT_FRAME_PERIOD)); gPrefs->Read(wxT("/Tracks/Synchronize/WindowSize"), &p.mWindowSize, float(SA_DFT_WINDOW_SIZE)); gPrefs->Read(wxT("/Tracks/Synchronize/SilenceThreshold"), &p.mSilenceThreshold, float(SA_DFT_SILENCE_THRESHOLD)); gPrefs->Read(wxT("/Tracks/Synchronize/ForceFinalAlignment"), &p.mForceFinalAlignment, float(SA_DFT_FORCE_FINAL_ALIGNMENT)); gPrefs->Read(wxT("/Tracks/Synchronize/IgnoreSilence"), &p.mIgnoreSilence, float(SA_DFT_IGNORE_SILENCE)); gPrefs->Read(wxT("/Tracks/Synchronize/PresmoothTime"), &p.mPresmoothTime, float(SA_DFT_PRESMOOTH_TIME)); gPrefs->Read(wxT("/Tracks/Synchronize/LineTime"), &p.mLineTime, float(SA_DFT_LINE_TIME)); gPrefs->Read(wxT("/Tracks/Synchronize/SmoothTime"), &p.mSmoothTime, float(SA_DFT_SMOOTH_TIME)); //wxButton *ok = safenew wxButton(this, wxID_OK, _("OK")); //wxButton *cancel = safenew wxButton(this, wxID_CANCEL, _("Cancel")); //wxSlider *sl = safenew wxSliderWrapper(this, ID_SLIDER, 0, 0, 100, // wxDefaultPosition, wxSize(20, 124), // wxSL_HORIZONTAL); ShuttleGui S(this, eIsCreating); //ok->SetDefault(); S.SetBorder(5); S.StartVerticalLay(true); S.StartStatic(XO("Align MIDI to Audio")); S.StartMultiColumn(3, wxEXPAND | wxALIGN_CENTER_VERTICAL); S.SetStretchyCol(1); mFramePeriodLabel = S.AddVariableText( XO("Frame Period:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mFramePeriodSlider = S.Id(ID_FRAMEPERIOD) .Name(XO("Frame Period")) .Style(wxSL_HORIZONTAL) .MinSize( { 300, -1 } ) .AddSlider( {}, /*pos*/ (int) (p.mFramePeriod * 100 + 0.5), /*max*/ 50, /*min*/ 5); mFramePeriodText = S.AddVariableText( SA_DFT_FRAME_PERIOD_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); mWindowSizeLabel = S.AddVariableText( XO("Window Size:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mWindowSizeSlider = S.Id(ID_WINDOWSIZE) .Name(XO("Window Size")) .Style(wxSL_HORIZONTAL) .AddSlider( {}, /*pos*/ (int) (p.mWindowSize * 100 + 0.5), /*max*/ 100, /*min*/ 5); mWindowSizeText = S.AddVariableText( SA_DFT_WINDOW_SIZE_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); mForceFinalAlignmentCheckBox = S.Id(ID_FORCEFINALALIGNMENT) .Name(XO("Force Final Alignment")) .AddCheckBox( XO("Force Final Alignment"), p.mForceFinalAlignment); mIgnoreSilenceCheckBox = S.Id(ID_IGNORESILENCE) .Name(XO("Ignore Silence at Beginnings and Endings")) .AddCheckBox( XO("Ignore Silence at Beginnings and Endings"), p.mIgnoreSilence ); // need a third column after checkboxes: S.AddVariableText({}, true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mSilenceThresholdLabel = S.AddVariableText(XO("Silence Threshold:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mSilenceThresholdSlider = S.Id(ID_SILENCETHRESHOLD) .Name(XO("Silence Threshold")) .Style(wxSL_HORIZONTAL) .AddSlider( {}, /*pos*/ (int) (p.mSilenceThreshold * 1000 + 0.5), /*max*/ 500); mSilenceThresholdText = S.AddVariableText( SA_DFT_SILENCE_THRESHOLD_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); mPresmoothLabel = S.AddVariableText( /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ XO("Presmooth Time:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mPresmoothSlider = S.Id(ID_PRESMOOTH) /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ .Name(XO("Presmooth Time")) .Style(wxSL_HORIZONTAL) .AddSlider( {}, /*pos*/ (int) (p.mPresmoothTime * 100 + 0.5), /*max*/ 500); mPresmoothText = S.AddVariableText( SA_DFT_PRESMOOTH_TIME_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ mLineTimeLabel = S.AddVariableText(XO("Line Time:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mLineTimeSlider = S.Id(ID_LINETIME) /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ .Name(XO("Line Time")) .Style(wxSL_HORIZONTAL) .AddSlider( {}, /*pos*/ (int) (p.mLineTime * 100 + 0.5), /*max*/ 500); mLineTimeText = S.AddVariableText( SA_DFT_LINE_TIME_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ mSmoothTimeLabel = S.AddVariableText( XO("Smooth Time:"), true, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); mSmoothTimeSlider = S.Id(ID_SMOOTHTIME) /* i18n-hint: The English would be clearer if it had 'Duration' rather than 'Time' This is a NEW experimental effect, and until we have it documented in the user manual we don't have a clear description of what this parameter does. It is OK to leave it in English. */ .Name(XO("Smooth Time")) .Style(wxSL_HORIZONTAL) .AddSlider( {}, /*pos*/ (int) (p.mSmoothTime * 100 + 0.5), /*max*/ 500); mSmoothTimeText = S.AddVariableText( SA_DFT_SMOOTH_TIME_TEXT, true, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); S.EndMultiColumn(); S.EndStatic(); mDefaultButton = safenew wxButton(this, ID_DEFAULT, _("Use Defaults")); mDefaultButton->SetName(_("Restore Defaults")); S.AddStandardButtons(eOkButton | eCancelButton, mDefaultButton); S.EndVerticalLay(); Layout(); Fit(); Center(); TransferDataFromWindow(); // set labels according to actual initial values params.mStatus = p.mStatus = ShowModal(); if (p.mStatus == wxID_OK) { // Retain the settings gPrefs->Write(wxT("/Tracks/Synchronize/FramePeriod"), p.mFramePeriod); gPrefs->Write(wxT("/Tracks/Synchronize/WindowSize"), p.mWindowSize); gPrefs->Write(wxT("/Tracks/Synchronize/SilenceThreshold"), p.mSilenceThreshold); gPrefs->Write(wxT("/Tracks/Synchronize/ForceFinalAlignment"), p.mForceFinalAlignment); gPrefs->Write(wxT("/Tracks/Synchronize/IgnoreSilence"), p.mIgnoreSilence); gPrefs->Write(wxT("/Tracks/Synchronize/PresmoothTime"), p.mPresmoothTime); gPrefs->Write(wxT("/Tracks/Synchronize/LineTime"), p.mLineTime); gPrefs->Write(wxT("/Tracks/Synchronize/SmoothTime"), p.mSmoothTime); gPrefs->Flush(); params = p; // return all parameters through params } } ScoreAlignDialog::~ScoreAlignDialog() { } //void ScoreAlignDialog::OnOK(wxCommandEvent & event) //{ // EndModal(wxID_OK); //} //void ScoreAlignDialog::OnCancel(wxCommandEvent & event) //{ // EndModal(wxID_CANCEL); //} void ScoreAlignDialog::OnSlider(wxCommandEvent & event) { TransferDataFromWindow(); } void ScoreAlignDialog::OnDefault(wxCommandEvent & event) { mFramePeriodSlider->SetValue((int) (SA_DFT_FRAME_PERIOD * 100 + 0.5)); mWindowSizeSlider->SetValue((int) (SA_DFT_WINDOW_SIZE * 100 + 0.5)); mSilenceThresholdSlider->SetValue( (int) (SA_DFT_SILENCE_THRESHOLD * 1000 + 0.5)); mForceFinalAlignmentCheckBox->SetValue(SA_DFT_FORCE_FINAL_ALIGNMENT); mIgnoreSilenceCheckBox->SetValue(SA_DFT_IGNORE_SILENCE); mPresmoothSlider->SetValue((int) (SA_DFT_PRESMOOTH_TIME * 100 + 0.5)); mLineTimeSlider->SetValue((int) (SA_DFT_LINE_TIME * 100 + 0.5)); mSmoothTimeSlider->SetValue((int) (SA_DFT_SMOOTH_TIME * 100 + 0.5)); TransferDataFromWindow(); } bool ScoreAlignDialog::TransferDataFromWindow() { p.mFramePeriod = (double) mFramePeriodSlider->GetValue() / 100.0; p.mWindowSize = (double) mWindowSizeSlider->GetValue() / 100.0; p.mSilenceThreshold = (double) mSilenceThresholdSlider->GetValue() / 1000.0; p.mForceFinalAlignment = (double) mForceFinalAlignmentCheckBox->GetValue(); p.mIgnoreSilence = (double) mIgnoreSilenceCheckBox->GetValue(); p.mPresmoothTime = (double) mPresmoothSlider->GetValue() / 100.0; p.mLineTime = (double) mLineTimeSlider->GetValue() / 100.0; p.mSmoothTime = (double) mSmoothTimeSlider->GetValue() / 100.0; mFramePeriodText->SetLabel(wxString::Format(_("%.2f secs"), p.mFramePeriod)); mWindowSizeText->SetLabel(wxString::Format(_("%.2f secs"), p.mWindowSize)); mSilenceThresholdText->SetLabel(wxString::Format(_("%.3f"), p.mSilenceThreshold)); mPresmoothText->SetLabel(p.mPresmoothTime > 0 ? wxString::Format(_("%.2f secs"), p.mPresmoothTime) : wxT("(off)")); mLineTimeText->SetLabel(p.mLineTime > 0 ? wxString::Format(_("%.2f secs"), p.mLineTime) : wxT("(off)")); mSmoothTimeText->SetLabel(wxString::Format(_("%.2f secs"), p.mSmoothTime)); return true; } void CloseScoreAlignDialog() { gScoreAlignDialog.reset(); } BEGIN_EVENT_TABLE(ScoreAlignDialog, wxDialogWrapper) // EVT_BUTTON(wxID_OK, ScoreAlignDialog::OnOK) // EVT_BUTTON(wxID_CANCEL, ScoreAlignDialog::OnCancel) EVT_BUTTON(ID_DEFAULT, ScoreAlignDialog::OnDefault) EVT_SLIDER(ID_FRAMEPERIOD, ScoreAlignDialog::OnSlider) EVT_SLIDER(ID_WINDOWSIZE, ScoreAlignDialog::OnSlider) EVT_SLIDER(ID_SILENCETHRESHOLD, ScoreAlignDialog::OnSlider) EVT_CHECKBOX(ID_FORCEFINALALIGNMENT, ScoreAlignDialog::OnSlider) EVT_CHECKBOX(ID_IGNORESILENCE, ScoreAlignDialog::OnSlider) EVT_SLIDER(ID_PRESMOOTH, ScoreAlignDialog::OnSlider) EVT_SLIDER(ID_LINETIME, ScoreAlignDialog::OnSlider) EVT_SLIDER(ID_SMOOTHTIME, ScoreAlignDialog::OnSlider) END_EVENT_TABLE() #endif
/** * @file Benchmark.cpp * * @brief Benchmarking tests for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017-2019 The Altecoin developers #include <boost/test/unit_test.hpp> #include <string> #include <iostream> #include <fstream> // #include <curses.h> #include <exception> #include <cstdlib> #include <sys/time.h> #include "streams.h" #include "libzerocoin/ParamGeneration.h" #include "libzerocoin/Denominations.h" #include "libzerocoin/Coin.h" #include "libzerocoin/CoinSpend.h" #include "libzerocoin/Accumulator.h" #include "test_altecoin.h" #define COLOR_STR_GREEN "\033[32m" #define COLOR_STR_NORMAL "\033[0m" #define COLOR_STR_RED "\033[31m" #define TESTS_COINS_TO_ACCUMULATE 50 // Global test counters uint32_t ggNumTests = 0; uint32_t ggSuccessfulTests = 0; // Global coin array libzerocoin::PrivateCoin *ggCoins[TESTS_COINS_TO_ACCUMULATE]; // Global params libzerocoin::ZerocoinParams *gg_Params; ////////// // Utility routines ////////// class Timer { timeval timer[2]; public: timeval start() { gettimeofday(&this->timer[0], NULL); return this->timer[0]; } timeval stop() { gettimeofday(&this->timer[1], NULL); return this->timer[1]; } int duration() const { int secs(this->timer[1].tv_sec - this->timer[0].tv_sec); int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec); if(usecs < 0) { --secs; usecs += 1000000; } return static_cast<int>(secs * 1000 + usecs / 1000.0 + 0.5); } }; // Global timer Timer timer; void gLogTestResult(std::string testName, bool (*testPtr)()) { std::string colorGreen(COLOR_STR_GREEN); std::string colorNormal(COLOR_STR_NORMAL); std::string colorRed(COLOR_STR_RED); std::cout << "Testing if " << testName << "..." << std::endl; bool testResult = testPtr(); if (testResult == true) { std::cout << "\t" << colorGreen << "[PASS]" << colorNormal << std::endl; ggSuccessfulTests++; } else { std::cout << colorRed << "\t[FAIL]" << colorNormal << std::endl; } ggNumTests++; } CBigNum gGetTestModulus() { static CBigNum testModulus(0); // TODO: should use a hard-coded RSA modulus for testing if (!testModulus) { CBigNum p, q; p = CBigNum::generatePrime(1024, false); q = CBigNum::generatePrime(1024, false); testModulus = p * q; } return testModulus; } ////////// // Test routines ////////// bool Testb_GenRSAModulus() { CBigNum result = gGetTestModulus(); if (!result) { return false; } else { return true; } } bool Testb_CalcParamSizes() { bool result = true; #if 0 uint32_t pLen, qLen; try { calculateGroupParamLengths(4000, 80, &pLen, &qLen); if (pLen < 1024 || qLen < 256) { result = false; } calculateGroupParamLengths(4000, 96, &pLen, &qLen); if (pLen < 2048 || qLen < 256) { result = false; } calculateGroupParamLengths(4000, 112, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } calculateGroupParamLengths(4000, 120, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } calculateGroupParamLengths(4000, 128, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } } catch (const exception &e) { result = false; } #endif return result; } bool Testb_GenerateGroupParams() { uint32_t pLen = 1024, qLen = 256, count; libzerocoin::IntegerGroupParams group; for (count = 0; count < 1; count++) { try { group = libzerocoin::deriveIntegerGroupParams(libzerocoin::calculateSeed(gGetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); } catch (const std::runtime_error& e) { std::cout << "Caught exception " << e.what() << std::endl; return false; } // Now perform some simple tests on the resulting parameters if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) { return false; } CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus); //cout << "g^q mod p = " << c << std::endl; if (!(c.isOne())) return false; // Try at multiple parameter sizes pLen = pLen * 1.5; qLen = qLen * 1.5; } return true; } bool Testb_ParamGen() { bool result = true; try { timer.start(); // Instantiating testParams runs the parameter generation code libzerocoin::ZerocoinParams testParams(gGetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); timer.stop(); std::cout << "\tPARAMGEN ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; result = false; } return result; } bool Testb_Accumulator() { // This test assumes a list of coins were generated during // the Testb_MintCoin() test. if (ggCoins[0] == NULL) { return false; } try { // Accumulate the coin list from first to last into one accumulator libzerocoin::Accumulator accOne(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accTwo(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accThree(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accFour(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::AccumulatorWitness wThree(gg_Params, accThree, ggCoins[0]->getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { accOne += ggCoins[i]->getPublicCoin(); accTwo += ggCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin(); accThree += ggCoins[i]->getPublicCoin(); wThree += ggCoins[i]->getPublicCoin(); if(i != 0) { accFour += ggCoins[i]->getPublicCoin(); } } // Compare the accumulated results if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) { std::cout << "Accumulators don't match" << std::endl; return false; } if(accFour.getValue() != wThree.getValue()) { std::cout << "Witness math not working," << std::endl; return false; } // Verify that the witness is correct if (!wThree.VerifyWitness(accThree, ggCoins[0]->getPublicCoin()) ) { std::cout << "Witness not valid" << std::endl; return false; } } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; return false; } return true; } bool Testb_MintCoin() { try { // Generate a list of coins timer.start(); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { ggCoins[i] = new libzerocoin::PrivateCoin(gg_Params, libzerocoin::CoinDenomination::ZQ_ONE); } timer.stop(); } catch (const std::exception& e) { return false; } std::cout << "\tMINT ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Coin: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; return true; } bool Testb_MintAndSpend() { try { // This test assumes a list of coins were generated in Testb_MintCoin() if (ggCoins[0] == NULL) { // No coins: mint some. Testb_MintCoin(); if (ggCoins[0] == NULL) { return false; } } // Accumulate the list of generated coins into a fresh accumulator. // The first one gets marked as accumulated for a witness, the // others just get accumulated normally. libzerocoin::Accumulator acc(&gg_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::AccumulatorWitness wAcc(gg_Params, acc, ggCoins[0]->getPublicCoin()); timer.start(); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { acc += ggCoins[i]->getPublicCoin(); } timer.stop(); std::cout << "\tACCUMULATOR ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; timer.start(); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { wAcc +=ggCoins[i]->getPublicCoin(); } timer.stop(); std::cout << "\tWITNESS ELAPSED TIME: \n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; // Now spend the coin timer.start(); libzerocoin::CoinSpend spend(gg_Params, gg_Params, *(ggCoins[0]), acc, 0, wAcc, 0, libzerocoin::SpendType::SPEND); //(0) presstab timer.stop(); std::cout << "\tSPEND ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; // Serialize the proof and deserialize into newSpend CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); timer.start(); ss << spend; timer.stop(); libzerocoin::CoinSpend newSpend(gg_Params, gg_Params, ss); std::cout << "\tSERIALIZE ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; // Finally, see if we can verify the deserialized proof (return our result) timer.start(); bool ret = newSpend.Verify(acc); timer.stop(); std::cout << "\tSPEND VERIFY ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; return ret; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; return false; } return false; } void Testb_RunAllTests() { // Make a new set of parameters from a random RSA modulus gg_Params = new libzerocoin::ZerocoinParams(gGetTestModulus()); ggNumTests = ggSuccessfulTests = 0; for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { ggCoins[i] = NULL; } // Run through all of the Zerocoin tests gLogTestResult("an RSA modulus can be generated", Testb_GenRSAModulus); gLogTestResult("parameter sizes are correct", Testb_CalcParamSizes); gLogTestResult("group/field parameters can be generated", Testb_GenerateGroupParams); gLogTestResult("parameter generation is correct", Testb_ParamGen); gLogTestResult("coins can be minted", Testb_MintCoin); gLogTestResult("the accumulator works", Testb_Accumulator); gLogTestResult("a minted coin can be spent", Testb_MintAndSpend); // Summarize test results if (ggSuccessfulTests < ggNumTests) { std::cout << std::endl << "ERROR: SOME TESTS FAILED" << std::endl; } // Clear any generated coins for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { delete ggCoins[i]; } std::cout << ggSuccessfulTests << " out of " << ggNumTests << " tests passed." << std::endl << std::endl; delete gg_Params; } BOOST_FIXTURE_TEST_SUITE(benchmark_zerocoin, TestingSetup) BOOST_AUTO_TEST_CASE(benchmark_test) { std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " benchmark utility." << std::endl << std::endl; Testb_RunAllTests(); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "httpserver.h" #include "chainparamsbase.h" #include "compat.h" #include "util.h" #include "netbase.h" #include "rpc/protocol.h" // For HTTP status codes #include "sync.h" #include "ui_interface.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <signal.h> #include <future> #include <event2/event.h> #include <event2/http.h> #include <event2/thread.h> #include <event2/buffer.h> #include <event2/util.h> #include <event2/keyvalq_struct.h> #ifdef EVENT__HAVE_NETINET_IN_H #include <netinet/in.h> #ifdef _XOPEN_SOURCE_EXTENDED #include <arpa/inet.h> #endif #endif /** Maximum size of http request (request line + headers) */ static const size_t MAX_HEADERS_SIZE = 8192; /** HTTP request work item */ class HTTPWorkItem : public HTTPClosure { public: HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func): req(std::move(_req)), path(_path), func(_func) { } void operator()() override { func(req.get(), path); } std::unique_ptr<HTTPRequest> req; private: std::string path; HTTPRequestHandler func; }; /** Simple work queue for distributing work over multiple threads. * Work items are simply callable objects. */ template <typename WorkItem> class WorkQueue { private: /** Mutex protects entire object */ std::mutex cs; std::condition_variable cond; std::deque<std::unique_ptr<WorkItem>> queue; bool running; size_t maxDepth; int numThreads; /** RAII object to keep track of number of running worker threads */ class ThreadCounter { public: WorkQueue &wq; ThreadCounter(WorkQueue &w): wq(w) { std::lock_guard<std::mutex> lock(wq.cs); wq.numThreads += 1; } ~ThreadCounter() { std::lock_guard<std::mutex> lock(wq.cs); wq.numThreads -= 1; wq.cond.notify_all(); } }; public: WorkQueue(size_t _maxDepth) : running(true), maxDepth(_maxDepth), numThreads(0) { } /** Precondition: worker threads have all stopped * (call WaitExit) */ ~WorkQueue() { } /** Enqueue a work item */ bool Enqueue(WorkItem* item) { std::unique_lock<std::mutex> lock(cs); if (queue.size() >= maxDepth) { return false; } queue.emplace_back(std::unique_ptr<WorkItem>(item)); cond.notify_one(); return true; } /** Thread function */ void Run() { ThreadCounter count(*this); while (true) { std::unique_ptr<WorkItem> i; { std::unique_lock<std::mutex> lock(cs); while (running && queue.empty()) cond.wait(lock); if (!running) break; i = std::move(queue.front()); queue.pop_front(); } (*i)(); } } /** Interrupt and exit loops */ void Interrupt() { std::unique_lock<std::mutex> lock(cs); running = false; cond.notify_all(); } /** Wait for worker threads to exit */ void WaitExit() { std::unique_lock<std::mutex> lock(cs); while (numThreads > 0){ cond.wait(lock); } } /** Return current depth of queue */ size_t Depth() { std::unique_lock<std::mutex> lock(cs); return queue.size(); } }; struct HTTPPathHandler { HTTPPathHandler() {} HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler): prefix(_prefix), exactMatch(_exactMatch), handler(_handler) { } std::string prefix; bool exactMatch; HTTPRequestHandler handler; }; /** HTTP module state */ //! libevent event loop static struct event_base* eventBase = 0; //! HTTP server struct evhttp* eventHTTP = 0; //! List of subnets to allow RPC connections from static std::vector<CSubNet> rpc_allow_subnets; //! Work queue for handling longer requests off the event loop thread static WorkQueue<HTTPClosure>* workQueue = 0; //! Handlers for (sub)paths std::vector<HTTPPathHandler> pathHandlers; //! Bound listening sockets std::vector<evhttp_bound_socket *> boundSockets; /** Check if a network address is allowed to access the HTTP server */ static bool ClientAllowed(const CNetAddr& netaddr) { if (!netaddr.IsValid()) return false; for(const CSubNet& subnet : rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; } /** Initialize ACL list for HTTP server */ static bool InitHTTPAllowList() { rpc_allow_subnets.clear(); CNetAddr localv4; CNetAddr localv6; LookupHost("127.0.0.1", localv4, false); LookupHost("::1", localv6, false); rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost if (mapMultiArgs.count("-rpcallowip")) { const std::vector<std::string>& vAllow = mapMultiArgs.at("-rpcallowip"); for (std::string strAllow : vAllow) { CSubNet subnet; LookupSubNet(strAllow.c_str(), subnet); if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow), "", CClientUIInterface::MSG_ERROR); return false; } rpc_allow_subnets.push_back(subnet); } } std::string strAllowed; for (const CSubNet& subnet : rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed); return true; } /** HTTP request method as string - use for logging only */ static std::string RequestMethodString(HTTPRequest::RequestMethod m) { switch (m) { case HTTPRequest::GET: return "GET"; break; case HTTPRequest::POST: return "POST"; break; case HTTPRequest::HEAD: return "HEAD"; break; case HTTPRequest::PUT: return "PUT"; break; default: return "unknown"; } } /** HTTP request callback */ static void http_request_cb(struct evhttp_request* req, void* arg) { std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req)); LogPrint("http", "Received a %s request for %s from %s\n", RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString()); // Early address-based allow check if (!ClientAllowed(hreq->GetPeer())) { hreq->WriteReply(HTTP_FORBIDDEN); return; } // Early reject unknown HTTP methods if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) { hreq->WriteReply(HTTP_BADMETHOD); return; } // Find registered handler for prefix std::string strURI = hreq->GetURI(); std::string path; std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin(); std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end(); for (; i != iend; ++i) { bool match = false; if (i->exactMatch) match = (strURI == i->prefix); else match = (strURI.substr(0, i->prefix.size()) == i->prefix); if (match) { path = strURI.substr(i->prefix.size()); break; } } // Dispatch to worker thread if (i != iend) { std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler)); assert(workQueue); if (workQueue->Enqueue(item.get())) item.release(); /* if true, queue took ownership */ else { LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n"); item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded"); } } else { hreq->WriteReply(HTTP_NOTFOUND); } } /** Callback to reject HTTP requests after shutdown. */ static void http_reject_request_cb(struct evhttp_request* req, void*) { LogPrint("http", "Rejecting request while shutting down\n"); evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL); } /** Event dispatcher thread */ static bool ThreadHTTP(struct event_base* base, struct evhttp* http) { RenameThread("zevno-http"); LogPrint("http", "Entering http event loop\n"); event_base_dispatch(base); // Event loop will be interrupted by InterruptHTTPServer() LogPrint("http", "Exited http event loop\n"); return event_base_got_break(base) == 0; } /** Bind HTTP server to specified addresses */ static bool HTTPBindAddresses(struct evhttp* http) { int defaultPort = GetArg("-rpcport", BaseParams().RPCPort()); std::vector<std::pair<std::string, uint16_t> > endpoints; // Determine what addresses to bind to if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs endpoints.push_back(std::make_pair("::1", defaultPort)); endpoints.push_back(std::make_pair("127.0.0.1", defaultPort)); if (IsArgSet("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind"); for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) { int port = defaultPort; std::string host; SplitHostPort(*i, port, host); endpoints.push_back(std::make_pair(host, port)); } } else { // No specific bind address specified, bind to any endpoints.push_back(std::make_pair("::", defaultPort)); endpoints.push_back(std::make_pair("0.0.0.0", defaultPort)); } // Bind addresses for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) { LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second); evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second); if (bind_handle) { boundSockets.push_back(bind_handle); } else { LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second); } } return !boundSockets.empty(); } /** Simple wrapper to set thread name and run work queue */ static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue) { RenameThread("zevno-httpworker"); queue->Run(); } /** libevent event log callback */ static void libevent_log_cb(int severity, const char *msg) { #ifndef EVENT_LOG_WARN // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed. # define EVENT_LOG_WARN _EVENT_LOG_WARN #endif if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category LogPrintf("libevent: %s\n", msg); // The below code causes log spam on Travis and the output of these logs has never been of any use so far //else // LogPrint("libevent", "libevent: %s\n", msg); } bool InitHTTPServer() { struct evhttp* http = 0; struct event_base* base = 0; if (!InitHTTPAllowList()) return false; if (GetBoolArg("-rpcssl", false)) { uiInterface.ThreadSafeMessageBox( "SSL mode for RPC (-rpcssl) is no longer supported.", "", CClientUIInterface::MSG_ERROR); return false; } // Redirect libevent's logging to our own log event_set_log_callback(&libevent_log_cb); #if LIBEVENT_VERSION_NUMBER >= 0x02010100 // If -debug=libevent, set full libevent debugging. // Otherwise, disable all libevent debugging. if (LogAcceptCategory("libevent")) event_enable_debug_logging(EVENT_DBG_ALL); else event_enable_debug_logging(EVENT_DBG_NONE); #endif #ifdef WIN32 evthread_use_windows_threads(); #else evthread_use_pthreads(); #endif base = event_base_new(); // XXX RAII if (!base) { LogPrintf("Couldn't create an event_base: exiting\n"); return false; } /* Create a new evhttp object to handle requests. */ http = evhttp_new(base); // XXX RAII if (!http) { LogPrintf("couldn't create evhttp. Exiting.\n"); event_base_free(base); return false; } evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); evhttp_set_max_body_size(http, MAX_SIZE); evhttp_set_gencb(http, http_request_cb, NULL); if (!HTTPBindAddresses(http)) { LogPrintf("Unable to bind any endpoint for RPC server\n"); evhttp_free(http); event_base_free(base); return false; } LogPrint("http", "Initialized HTTP server\n"); int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth); workQueue = new WorkQueue<HTTPClosure>(workQueueDepth); eventBase = base; eventHTTP = http; return true; } std::thread threadHTTP; std::future<bool> threadResult; bool StartHTTPServer() { LogPrint("http", "Starting HTTP server\n"); int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L); LogPrintf("HTTP: starting %d worker threads\n", rpcThreads); std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP); threadResult = task.get_future(); threadHTTP = std::thread(std::move(task), eventBase, eventHTTP); for (int i = 0; i < rpcThreads; i++) { std::thread rpc_worker(HTTPWorkQueueRun, workQueue); rpc_worker.detach(); } return true; } void InterruptHTTPServer() { LogPrint("http", "Interrupting HTTP server\n"); if (eventHTTP) { // Unlisten sockets for (evhttp_bound_socket *socket : boundSockets) { evhttp_del_accept_socket(eventHTTP, socket); } // Reject requests on current connections evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL); } if (workQueue) workQueue->Interrupt(); } void StopHTTPServer() { LogPrint("http", "Stopping HTTP server\n"); if (workQueue) { LogPrint("http", "Waiting for HTTP worker threads to exit\n"); #ifndef WIN32 // ToDo: Disabling WaitExit() for Windows platforms is an ugly workaround for the wallet not // closing during a repair-restart. It doesn't hurt, though, because threadHTTP.timed_join // below takes care of this and sends a loopbreak. workQueue->WaitExit(); #endif delete workQueue; } if (eventBase) { LogPrint("http", "Waiting for HTTP event thread to exit\n"); // Give event loop a few seconds to exit (to send back last RPC responses), then break it // Before this was solved with event_base_loopexit, but that didn't work as expected in // at least libevent 2.0.21 and always introduced a delay. In libevent // master that appears to be solved, so in the future that solution // could be used again (if desirable). // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990) if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) { LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n"); event_base_loopbreak(eventBase); } threadHTTP.join(); } if (eventHTTP) { evhttp_free(eventHTTP); eventHTTP = 0; } if (eventBase) { event_base_free(eventBase); eventBase = 0; } LogPrint("http", "Stopped HTTP server\n"); } struct event_base* EventBase() { return eventBase; } static void httpevent_callback_fn(evutil_socket_t, short, void* data) { // Static handler: simply call inner handler HTTPEvent *self = ((HTTPEvent*)data); self->handler(); if (self->deleteWhenTriggered) delete self; } HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler): deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) { ev = event_new(base, -1, 0, httpevent_callback_fn, this); assert(ev); } HTTPEvent::~HTTPEvent() { event_free(ev); } void HTTPEvent::trigger(struct timeval* tv) { if (tv == NULL) event_active(ev, 0, 0); // immediately trigger event in main thread else evtimer_add(ev, tv); // trigger after timeval passed } HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req), replySent(false) { } HTTPRequest::~HTTPRequest() { if (!replySent) { // Keep track of whether reply was sent to avoid request leaks LogPrintf("%s: Unhandled request\n", __func__); WriteReply(HTTP_INTERNAL, "Unhandled request"); } // evhttpd cleans up the request, as long as a reply was sent. } std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) { const struct evkeyvalq* headers = evhttp_request_get_input_headers(req); assert(headers); const char* val = evhttp_find_header(headers, hdr.c_str()); if (val) return std::make_pair(true, val); else return std::make_pair(false, ""); } std::string HTTPRequest::ReadBody() { struct evbuffer* buf = evhttp_request_get_input_buffer(req); if (!buf) return ""; size_t size = evbuffer_get_length(buf); /** Trivial implementation: if this is ever a performance bottleneck, * internal copying can be avoided in multi-segment buffers by using * evbuffer_peek and an awkward loop. Though in that case, it'd be even * better to not copy into an intermediate string but use a stream * abstraction to consume the evbuffer on the fly in the parsing algorithm. */ const char* data = (const char*)evbuffer_pullup(buf, size); if (!data) // returns NULL in case of empty buffer return ""; std::string rv(data, size); evbuffer_drain(buf, size); return rv; } void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value) { struct evkeyvalq* headers = evhttp_request_get_output_headers(req); assert(headers); evhttp_add_header(headers, hdr.c_str(), value.c_str()); } /** Closure sent to main thread to request a reply to be sent to * a HTTP request. * Replies must be sent in the main loop in the main http thread, * this cannot be done from worker threads. */ void HTTPRequest::WriteReply(int nStatus, const std::string& strReply) { assert(!replySent && req); // Send event to main http thread to send reply message struct evbuffer* evb = evhttp_request_get_output_buffer(req); assert(evb); evbuffer_add(evb, strReply.data(), strReply.size()); HTTPEvent* ev = new HTTPEvent(eventBase, true, std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL)); ev->trigger(0); replySent = true; req = 0; // transferred back to main thread } CService HTTPRequest::GetPeer() { evhttp_connection* con = evhttp_request_get_connection(req); CService peer; if (con) { // evhttp retains ownership over returned address string const char* address = ""; uint16_t port = 0; evhttp_connection_get_peer(con, (char**)&address, &port); peer = LookupNumeric(address, port); } return peer; } std::string HTTPRequest::GetURI() { return evhttp_request_get_uri(req); } HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() { switch (evhttp_request_get_command(req)) { case EVHTTP_REQ_GET: return GET; break; case EVHTTP_REQ_POST: return POST; break; case EVHTTP_REQ_HEAD: return HEAD; break; case EVHTTP_REQ_PUT: return PUT; break; default: return UNKNOWN; break; } } void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler) { LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler)); } void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) { std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin(); std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end(); for (; i != iend; ++i) if (i->prefix == prefix && i->exactMatch == exactMatch) break; if (i != iend) { LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); pathHandlers.erase(i); } }
#ifndef _w32_sy_Attributes_hpp__ #define _w32_sy_Attributes_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /*! * @file w32.sy/Attributes.hpp * @brief */ #include "__configure__.hpp" #include <w32/NotCopyable.hpp> namespace w32 { namespace sy { //! @addtogroup w32-sy //! @{ /*! * @brief Contains a security descriptor and its inheritability state. */ class Attributes : private NotCopyable { /* nested types. */ public: typedef ::SECURITY_ATTRIBUTES Data; /* data. */ private: Data myData; /* construction. */ private: // Not sure how to use this yet... Attributes (); public: /* methods. */ public: Data& get (); const Data& get () const; bool inheritable () const; void inheritable ( bool value ); }; //! @} } } #endif /* _w32_sy_Attributes_hpp__ */
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "master/allocator/sorter/drf/metrics.hpp" #include <process/defer.hpp> #include <process/metrics/metrics.hpp> #include <stout/foreach.hpp> #include <stout/path.hpp> #include "master/allocator/sorter/drf/sorter.hpp" using std::string; using process::UPID; using process::defer; using process::metrics::Gauge; namespace mesos { namespace internal { namespace master { namespace allocator { Metrics::Metrics( const UPID& _context, DRFSorter& _sorter, const string& _prefix) : context(_context), sorter(&_sorter), prefix(_prefix) {} Metrics::~Metrics() { foreachvalue (const Gauge& gauge, dominantShares) { process::metrics::remove(gauge); } } void Metrics::add(const string& client) { CHECK(!dominantShares.contains(client)); Gauge gauge( path::join(prefix, client, "/shares/", "/dominant"), defer(context, [this, client]() { // The client may have been removed if the dispatch // occurs after the client is removed but before the // metric is removed. DRFSorter::Node* sorterClient = sorter->find(client); if (sorterClient == nullptr) { return 0.0; } return sorter->calculateShare(sorterClient); })); dominantShares.put(client, gauge); process::metrics::add(gauge); } void Metrics::remove(const string& client) { CHECK(dominantShares.contains(client)); process::metrics::remove(dominantShares.at(client)); dominantShares.erase(client); } } // namespace allocator { } // namespace master { } // namespace internal { } // namespace mesos {
// // EditorComponents.inl // EnginePrototype // // Created by Samir Sinha on 4/21/16. // // namespace cinek { template<typename Object> void updateComponentUI ( EditorUIVariantMap& uiVariants, float columnOffsets[2], const char* componentName, Object* object ) { ove::Component<Object> component(object); if (ImGui::CollapsingHeader(componentName, nullptr, true, true)) { ImGui::Columns(2); ImGui::SetColumnOffset(0, columnOffsets[0]); ImGui::SetColumnOffset(1, columnOffsets[1]); // label on the left, editable on the right. component.enumerateProperties( [componentName](const char* label, ove::ComponentData& data) -> bool { char widgetId[32]; float floats[4]; bool writeProperty = false; snprintf(widgetId, sizeof(widgetId), "##%s_%s", componentName, label); widgetId[sizeof(widgetId)-1] = '\0'; ImGui::Selectable(label); ImGui::NextColumn(); ImGui::PushItemWidth(-1); switch(data.type()) { case ove::ComponentData::Type::kPoint3: { auto pos = data.get<ckm::vector3>(); floats[0] = pos[0]; floats[1] = pos[1]; floats[2] = pos[2]; writeProperty = ImGui::InputFloat3(widgetId, floats, 4); if (writeProperty) { pos[0] = floats[0]; pos[1] = floats[1]; pos[2] = floats[2]; data.set(pos); } } break; case ove::ComponentData::Type::kQuaternion: { auto quat = data.get<ckm::quat>(); char text[48]; snprintf(text, sizeof(text), "(%1.2f, %1.2f, %1.2f, %1.2f)", quat[0], quat[1], quat[2], quat[3]); if (ImGui::Selectable(text)) { snprintf(widgetId, sizeof(widgetId), "##%s_%s", componentName, label); ImGui::OpenPopup(widgetId); } if (ImGui::BeginPopup(widgetId)) { ImGui::EndPopup(); } /* if (writeProperty) { quat[0] = floats[0]; quat[1] = floats[1]; quat[2] = floats[2]; quat[3] = floats[3]; ckm::normalize(quat, quat); data.set(quat); } */ } break; default: break; } ImGui::PopItemWidth(); ImGui::NextColumn(); return writeProperty; } ); ImGui::Columns(1); } } }
/*******************************************************************\ Module: Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include "boolbv.h" #include <cassert> #include <util/arith_tools.h> #include <util/std_expr.h> #include <util/simplify_expr.h> bvt boolbvt::convert_index(const index_exprt &expr) { if(expr.id()!=ID_index) throw "expected index expression"; if(expr.operands().size()!=2) throw "index takes two operands"; const exprt &array=expr.array(); const exprt &index=expr.index(); const typet &array_op_type=ns.follow(array.type()); bvt bv; if(array_op_type.id()==ID_array) { const array_typet &array_type= to_array_type(array_op_type); std::size_t width=boolbv_width(expr.type()); if(width==0) return conversion_failed(expr); // see if the array size is constant if(is_unbounded_array(array_type)) { // use array decision procedure // free variables bv.resize(width); for(std::size_t i=0; i<width; i++) bv[i]=prop.new_variable(); record_array_index(expr); // record type if array is a symbol if(array.id()==ID_symbol) map.get_map_entry( to_symbol_expr(array).get_identifier(), array_type); // make sure we have the index in the cache convert_bv(index); return bv; } // Must have a finite size mp_integer array_size; if(to_integer(array_type.size(), array_size)) throw "failed to convert array size"; // see if the index address is constant // many of these are compacted by simplify_expr // but variable location writes will block this mp_integer index_value; if(!to_integer(index, index_value)) return convert_index(array, index_value); // Special case : arrays of one thing (useful for constants) // TODO : merge with ACTUAL_ARRAY_HACK so that ranges of the same // value, bit-patterns with the same value, etc. are treated like // this rather than as a series of individual options. #define UNIFORM_ARRAY_HACK #ifdef UNIFORM_ARRAY_HACK bool is_uniform = false; if(array.id()==ID_array_of) { is_uniform = true; } else if(array.id()==ID_constant || array.id()==ID_array) { bool found_exception = false; forall_expr(it, array.operands()) { if(*it != array.op0()) { found_exception = true; break; } } if(!found_exception) is_uniform = true; } if(is_uniform && prop.has_set_to()) { static int uniform_array_counter; // Temporary hack std::string identifier= "__CPROVER_internal_uniform_array_"+ std::to_string(uniform_array_counter++); symbol_exprt result(identifier, expr.type()); bv = convert_bv(result); equal_exprt value_equality(result, array.op0()); binary_relation_exprt lower_bound( from_integer(0, index.type()), ID_le, index); binary_relation_exprt upper_bound( index, ID_lt, from_integer(array_size, index.type())); if(lower_bound.lhs().is_nil() || upper_bound.rhs().is_nil()) throw "number conversion failed (2)"; and_exprt range_condition(lower_bound, upper_bound); implies_exprt implication(range_condition, value_equality); // Simplify may remove the lower bound if the type // is correct. prop.l_set_to_true(convert(simplify_expr(implication, ns))); return bv; } #endif #define ACTUAL_ARRAY_HACK #ifdef ACTUAL_ARRAY_HACK // More useful when updates to concrete locations in // actual arrays are compacted by simplify_expr if((array.id()==ID_constant || array.id()==ID_array) && prop.has_set_to()) { #ifdef CONSTANT_ARRAY_HACK // TODO : Compile the whole array into a single relation #endif // Symbol for output static int actual_array_counter; // Temporary hack std::string identifier= "__CPROVER_internal_actual_array_"+ std::to_string(actual_array_counter++); symbol_exprt result(identifier, expr.type()); bv = convert_bv(result); // add implications equal_exprt index_equality; index_equality.lhs()=index; // index operand equal_exprt value_equality; value_equality.lhs()=result; #ifdef COMPACT_EQUAL_CONST bv_utils.equal_const_register(convert_bv(index)); // Definitely bv_utils.equal_const_register(convert_bv(result)); // Maybe #endif exprt::operandst::const_iterator it = array.operands().begin(); for(mp_integer i=0; i<array_size; i=i+1) { index_equality.rhs()=from_integer(i, index_equality.lhs().type()); if(index_equality.rhs().is_nil()) throw "number conversion failed (1)"; assert(it != array.operands().end()); value_equality.rhs()=*it++; // Cache comparisons and equalities prop.l_set_to_true(convert(implies_exprt(index_equality, value_equality))); } return bv; } #endif // TODO : As with constant index, there is a trade-off // of when it is best to flatten the whole array and // when it is best to use the array theory and then use // one or more of the above encoding strategies. // get literals for the whole array const bvt &array_bv=convert_bv(array); if(array_size*width!=array_bv.size()) throw "unexpected array size"; // TODO: maybe a shifter-like construction would be better // Would be a lot more compact but propagate worse if(prop.has_set_to()) { // free variables bv.resize(width); for(std::size_t i=0; i<width; i++) bv[i]=prop.new_variable(); // add implications equal_exprt index_equality; index_equality.lhs()=index; // index operand #ifdef COMPACT_EQUAL_CONST bv_utils.equal_const_register(convert_bv(index)); // Definitely #endif bvt equal_bv; equal_bv.resize(width); for(mp_integer i=0; i<array_size; i=i+1) { index_equality.rhs()=from_integer(i, index_equality.lhs().type()); if(index_equality.rhs().is_nil()) throw "number conversion failed (1)"; mp_integer offset=i*width; for(std::size_t j=0; j<width; j++) equal_bv[j]=prop.lequal(bv[j], array_bv[integer2size_t(offset+j)]); prop.l_set_to_true( prop.limplies(convert(index_equality), prop.land(equal_bv))); } } else { bv.resize(width); equal_exprt equality; equality.lhs()=index; // index operand #ifdef COMPACT_EQUAL_CONST bv_utils.equal_const_register(convert_bv(index)); // Definitely #endif typet constant_type=index.type(); // type of index operand assert(array_size>0); for(mp_integer i=0; i<array_size; i=i+1) { equality.op1()=from_integer(i, constant_type); literalt e=convert(equality); mp_integer offset=i*width; for(std::size_t j=0; j<width; j++) { literalt l=array_bv[integer2size_t(offset+j)]; if(i==0) // this initializes bv bv[j]=l; else bv[j]=prop.lselect(e, l, bv[j]); } } } } else return conversion_failed(expr); return bv; } /// index operator with constant index bvt boolbvt::convert_index( const exprt &array, const mp_integer &index) { const array_typet &array_type= to_array_type(ns.follow(array.type())); std::size_t width=boolbv_width(array_type.subtype()); if(width==0) return conversion_failed(array); bvt bv; bv.resize(width); // TODO: If the underlying array can use one of the // improvements given above then it may be better to use // the array theory for short chains of updates and then // the improved array handling rather than full flattening. // Note that the calculation is non-trivial as the cost of // full flattening is amortised against all uses of // the array (constant and variable indexes) and updated // versions of it. const bvt &tmp=convert_bv(array); // recursive call mp_integer offset=index*width; if(offset>=0 && offset+width<=mp_integer(tmp.size())) { // in bounds // The assertion below is disabled as we want to be able // to run CBMC without simplifier. // Expression simplification should remove these cases // assert(array.id()!=ID_array_of && // array.id()!=ID_array); // If not there are large improvements possible as above for(std::size_t i=0; i<width; i++) bv[i]=tmp[integer2size_t(offset+i)]; } else { // out of bounds for(std::size_t i=0; i<width; i++) bv[i]=prop.new_variable(); } return bv; }
/* * nghttp2 - HTTP/2 C Library * * Copyright (c) 2019 nghttp2 contributors * * 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 "h2load_quic.h" #include <netinet/udp.h> #include <iostream> #include <ngtcp2/ngtcp2_crypto_openssl.h> #include <openssl/err.h> #include "h2load_http3_session.h" namespace h2load { namespace { auto randgen = util::make_mt19937(); } // namespace namespace { int handshake_completed(ngtcp2_conn *conn, void *user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_handshake_completed() != 0) { return NGTCP2_ERR_CALLBACK_FAILURE; } return 0; } } // namespace int Client::quic_handshake_completed() { return connection_made(); } namespace { int recv_stream_data(ngtcp2_conn *conn, uint32_t flags, int64_t stream_id, uint64_t offset, const uint8_t *data, size_t datalen, void *user_data, void *stream_user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_recv_stream_data(flags, stream_id, data, datalen) != 0) { // TODO Better to do this gracefully rather than // NGTCP2_ERR_CALLBACK_FAILURE. Perhaps, call // ngtcp2_conn_write_application_close() ? return NGTCP2_ERR_CALLBACK_FAILURE; } return 0; } } // namespace int Client::quic_recv_stream_data(uint32_t flags, int64_t stream_id, const uint8_t *data, size_t datalen) { if (worker->current_phase == Phase::MAIN_DURATION) { worker->stats.bytes_total += datalen; } auto s = static_cast<Http3Session *>(session.get()); auto nconsumed = s->read_stream(flags, stream_id, data, datalen); if (nconsumed == -1) { return -1; } ngtcp2_conn_extend_max_stream_offset(quic.conn, stream_id, nconsumed); ngtcp2_conn_extend_max_offset(quic.conn, nconsumed); return 0; } namespace { int acked_stream_data_offset(ngtcp2_conn *conn, int64_t stream_id, uint64_t offset, uint64_t datalen, void *user_data, void *stream_user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_acked_stream_data_offset(stream_id, datalen) != 0) { return NGTCP2_ERR_CALLBACK_FAILURE; } return 0; } } // namespace int Client::quic_acked_stream_data_offset(int64_t stream_id, size_t datalen) { auto s = static_cast<Http3Session *>(session.get()); if (s->add_ack_offset(stream_id, datalen) != 0) { return -1; } return 0; } namespace { int stream_close(ngtcp2_conn *conn, uint32_t flags, int64_t stream_id, uint64_t app_error_code, void *user_data, void *stream_user_data) { auto c = static_cast<Client *>(user_data); if (!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) { app_error_code = NGHTTP3_H3_NO_ERROR; } if (c->quic_stream_close(stream_id, app_error_code) != 0) { return -1; } return 0; } } // namespace int Client::quic_stream_close(int64_t stream_id, uint64_t app_error_code) { auto s = static_cast<Http3Session *>(session.get()); if (s->close_stream(stream_id, app_error_code) != 0) { return -1; } return 0; } namespace { int stream_reset(ngtcp2_conn *conn, int64_t stream_id, uint64_t final_size, uint64_t app_error_code, void *user_data, void *stream_user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_stream_reset(stream_id, app_error_code) != 0) { return -1; } return 0; } } // namespace int Client::quic_stream_reset(int64_t stream_id, uint64_t app_error_code) { auto s = static_cast<Http3Session *>(session.get()); if (s->shutdown_stream_read(stream_id) != 0) { return -1; } return 0; } namespace { int stream_stop_sending(ngtcp2_conn *conn, int64_t stream_id, uint64_t app_error_code, void *user_data, void *stream_user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_stream_stop_sending(stream_id, app_error_code) != 0) { return -1; } return 0; } } // namespace int Client::quic_stream_stop_sending(int64_t stream_id, uint64_t app_error_code) { auto s = static_cast<Http3Session *>(session.get()); if (s->shutdown_stream_read(stream_id) != 0) { return -1; } return 0; } namespace { int extend_max_local_streams_bidi(ngtcp2_conn *conn, uint64_t max_streams, void *user_data) { auto c = static_cast<Client *>(user_data); if (c->quic_extend_max_local_streams() != 0) { return NGTCP2_ERR_CALLBACK_FAILURE; } return 0; } } // namespace int Client::quic_extend_max_local_streams() { auto s = static_cast<Http3Session *>(session.get()); if (s->extend_max_local_streams() != 0) { return NGTCP2_ERR_CALLBACK_FAILURE; } return 0; } namespace { int get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid, uint8_t *token, size_t cidlen, void *user_data) { auto dis = std::uniform_int_distribution<uint8_t>( 0, std::numeric_limits<uint8_t>::max()); auto f = [&dis]() { return dis(randgen); }; std::generate_n(cid->data, cidlen, f); cid->datalen = cidlen; std::generate_n(token, NGTCP2_STATELESS_RESET_TOKENLEN, f); return 0; } } // namespace namespace { void debug_log_printf(void *user_data, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } } // namespace namespace { void generate_cid(ngtcp2_cid &dest) { auto dis = std::uniform_int_distribution<uint8_t>( 0, std::numeric_limits<uint8_t>::max()); dest.datalen = 8; std::generate_n(dest.data, dest.datalen, [&dis]() { return dis(randgen); }); } } // namespace namespace { ngtcp2_tstamp timestamp(struct ev_loop *loop) { return ev_now(loop) * NGTCP2_SECONDS; } } // namespace namespace { int set_encryption_secrets(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level, const uint8_t *rx_secret, const uint8_t *tx_secret, size_t secret_len) { auto c = static_cast<Client *>(SSL_get_app_data(ssl)); if (c->quic_on_key( ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level), rx_secret, tx_secret, secret_len) != 0) { return 0; } return 1; } } // namespace namespace { int add_handshake_data(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level, const uint8_t *data, size_t len) { auto c = static_cast<Client *>(SSL_get_app_data(ssl)); c->quic_write_client_handshake( ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level), data, len); return 1; } } // namespace namespace { int flush_flight(SSL *ssl) { return 1; } } // namespace namespace { int send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert) { auto c = static_cast<Client *>(SSL_get_app_data(ssl)); c->quic_set_tls_alert(alert); return 1; } } // namespace namespace { auto quic_method = SSL_QUIC_METHOD{ set_encryption_secrets, add_handshake_data, flush_flight, send_alert, }; } // namespace // qlog write callback -- excerpted from ngtcp2/examples/client_base.cc namespace { void qlog_write_cb(void *user_data, uint32_t flags, const void *data, size_t datalen) { auto c = static_cast<Client *>(user_data); c->quic_write_qlog(data, datalen); } } // namespace void Client::quic_write_qlog(const void *data, size_t datalen) { assert(quic.qlog_file != nullptr); fwrite(data, 1, datalen, quic.qlog_file); } int Client::quic_init(const sockaddr *local_addr, socklen_t local_addrlen, const sockaddr *remote_addr, socklen_t remote_addrlen) { int rv; if (!ssl) { ssl = SSL_new(worker->ssl_ctx); SSL_set_app_data(ssl, this); SSL_set_connect_state(ssl); SSL_set_quic_method(ssl, &quic_method); SSL_set_quic_use_legacy_codepoint(ssl, 0); } auto callbacks = ngtcp2_callbacks{ ngtcp2_crypto_client_initial_cb, nullptr, // recv_client_initial ngtcp2_crypto_recv_crypto_data_cb, h2load::handshake_completed, nullptr, // recv_version_negotiation ngtcp2_crypto_encrypt_cb, ngtcp2_crypto_decrypt_cb, ngtcp2_crypto_hp_mask_cb, h2load::recv_stream_data, h2load::acked_stream_data_offset, nullptr, // stream_open h2load::stream_close, nullptr, // recv_stateless_reset ngtcp2_crypto_recv_retry_cb, h2load::extend_max_local_streams_bidi, nullptr, // extend_max_local_streams_uni nullptr, // rand get_new_connection_id, nullptr, // remove_connection_id ngtcp2_crypto_update_key_cb, nullptr, // path_validation nullptr, // select_preferred_addr h2load::stream_reset, nullptr, // extend_max_remote_streams_bidi nullptr, // extend_max_remote_streams_uni nullptr, // extend_max_stream_data nullptr, // dcid_status nullptr, // handshake_confirmed nullptr, // recv_new_token ngtcp2_crypto_delete_crypto_aead_ctx_cb, ngtcp2_crypto_delete_crypto_cipher_ctx_cb, nullptr, // recv_datagram nullptr, // ack_datagram nullptr, // lost_datagram nullptr, // get_path_challenge_data h2load::stream_stop_sending, }; ngtcp2_cid scid, dcid; generate_cid(scid); generate_cid(dcid); auto config = worker->config; ngtcp2_settings settings; ngtcp2_settings_default(&settings); if (config->verbose) { settings.log_printf = debug_log_printf; } settings.initial_ts = timestamp(worker->loop); if (!config->qlog_file_base.empty()) { assert(quic.qlog_file == nullptr); auto path = config->qlog_file_base; path += '.'; path += util::utos(worker->id); path += '.'; path += util::utos(id); path += ".qlog"; quic.qlog_file = fopen(path.c_str(), "w"); if (quic.qlog_file == nullptr) { std::cerr << "Failed to open a qlog file: " << path << std::endl; return -1; } settings.qlog.write = qlog_write_cb; } if (config->max_udp_payload_size) { settings.max_udp_payload_size = config->max_udp_payload_size; settings.no_udp_payload_size_shaping = 1; } ngtcp2_transport_params params; ngtcp2_transport_params_default(&params); auto max_stream_data = std::min((1 << 26) - 1, (1 << config->window_bits) - 1); params.initial_max_stream_data_bidi_local = max_stream_data; params.initial_max_stream_data_uni = max_stream_data; params.initial_max_data = (1 << config->connection_window_bits) - 1; params.initial_max_streams_bidi = 0; params.initial_max_streams_uni = 100; params.max_idle_timeout = 30 * NGTCP2_SECONDS; auto path = ngtcp2_path{ {local_addrlen, const_cast<sockaddr *>(local_addr)}, {remote_addrlen, const_cast<sockaddr *>(remote_addr)}, }; assert(config->npn_list.size()); uint32_t quic_version; if (config->npn_list[0] == NGHTTP3_ALPN_H3) { quic_version = NGTCP2_PROTO_VER_V1; } else { quic_version = NGTCP2_PROTO_VER_MIN; } rv = ngtcp2_conn_client_new(&quic.conn, &dcid, &scid, &path, quic_version, &callbacks, &settings, &params, nullptr, this); if (rv != 0) { return -1; } ngtcp2_conn_set_tls_native_handle(quic.conn, ssl); return 0; } void Client::quic_free() { ngtcp2_conn_del(quic.conn); if (quic.qlog_file != nullptr) { fclose(quic.qlog_file); quic.qlog_file = nullptr; } } void Client::quic_close_connection() { if (!quic.conn) { return; } std::array<uint8_t, NGTCP2_MAX_UDP_PAYLOAD_SIZE> buf; ngtcp2_ssize nwrite; ngtcp2_path_storage ps; ngtcp2_path_storage_zero(&ps); switch (quic.last_error.type) { case quic::ErrorType::TransportVersionNegotiation: return; case quic::ErrorType::Transport: nwrite = ngtcp2_conn_write_connection_close( quic.conn, &ps.path, nullptr, buf.data(), buf.size(), quic.last_error.code, timestamp(worker->loop)); break; case quic::ErrorType::Application: nwrite = ngtcp2_conn_write_application_close( quic.conn, &ps.path, nullptr, buf.data(), buf.size(), quic.last_error.code, timestamp(worker->loop)); break; default: assert(0); } if (nwrite < 0) { return; } write_udp(reinterpret_cast<sockaddr *>(ps.path.remote.addr), ps.path.remote.addrlen, buf.data(), nwrite, 0); } int Client::quic_on_key(ngtcp2_crypto_level level, const uint8_t *rx_secret, const uint8_t *tx_secret, size_t secretlen) { if (ngtcp2_crypto_derive_and_install_rx_key(quic.conn, nullptr, nullptr, nullptr, level, rx_secret, secretlen) != 0) { std::cerr << "ngtcp2_crypto_derive_and_install_rx_key() failed" << std::endl; return -1; } if (ngtcp2_crypto_derive_and_install_tx_key(quic.conn, nullptr, nullptr, nullptr, level, tx_secret, secretlen) != 0) { std::cerr << "ngtcp2_crypto_derive_and_install_tx_key() failed" << std::endl; return -1; } if (level == NGTCP2_CRYPTO_LEVEL_APPLICATION) { auto s = std::make_unique<Http3Session>(this); if (s->init_conn() == -1) { return -1; } session = std::move(s); } return 0; } void Client::quic_set_tls_alert(uint8_t alert) { quic.last_error = quic::err_transport_tls(alert); } void Client::quic_write_client_handshake(ngtcp2_crypto_level level, const uint8_t *data, size_t datalen) { assert(level < 2); ngtcp2_conn_submit_crypto_data(quic.conn, level, data, datalen); } void quic_pkt_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) { auto c = static_cast<Client *>(w->data); if (c->quic_pkt_timeout() != 0) { c->fail(); c->worker->free_client(c); delete c; return; } } int Client::quic_pkt_timeout() { int rv; auto now = timestamp(worker->loop); rv = ngtcp2_conn_handle_expiry(quic.conn, now); if (rv != 0) { quic.last_error = quic::err_transport(NGTCP2_ERR_INTERNAL); return -1; } return write_quic(); } void Client::quic_restart_pkt_timer() { auto expiry = ngtcp2_conn_get_expiry(quic.conn); auto now = timestamp(worker->loop); auto t = expiry > now ? static_cast<ev_tstamp>(expiry - now) / NGTCP2_SECONDS : 1e-9; quic.pkt_timer.repeat = t; ev_timer_again(worker->loop, &quic.pkt_timer); } int Client::read_quic() { std::array<uint8_t, 65536> buf; sockaddr_union su; socklen_t addrlen = sizeof(su); int rv; size_t pktcnt = 0; ngtcp2_pkt_info pi{}; for (;;) { auto nread = recvfrom(fd, buf.data(), buf.size(), MSG_DONTWAIT, &su.sa, &addrlen); if (nread == -1) { return 0; } assert(quic.conn); ++worker->stats.udp_dgram_recv; auto path = ngtcp2_path{ {local_addr.len, &local_addr.su.sa}, {addrlen, &su.sa}, }; rv = ngtcp2_conn_read_pkt(quic.conn, &path, &pi, buf.data(), nread, timestamp(worker->loop)); if (rv != 0) { std::cerr << "ngtcp2_conn_read_pkt: " << ngtcp2_strerror(rv) << std::endl; return -1; } if (++pktcnt == 100) { break; } } return 0; } int Client::write_quic() { ev_io_stop(worker->loop, &wev); if (quic.close_requested) { return -1; } std::array<nghttp3_vec, 16> vec; size_t pktcnt = 0; auto max_udp_payload_size = ngtcp2_conn_get_path_max_udp_payload_size(quic.conn); size_t max_pktcnt = #ifdef UDP_SEGMENT worker->config->no_udp_gso ? 1 : std::min(static_cast<size_t>(10), static_cast<size_t>(64_k / max_udp_payload_size)); #else // !UDP_SEGMENT 1; #endif // !UDP_SEGMENT std::array<uint8_t, 64_k> buf; uint8_t *bufpos = buf.data(); ngtcp2_path_storage ps; ngtcp2_path_storage_zero(&ps); auto s = static_cast<Http3Session *>(session.get()); for (;;) { int64_t stream_id = -1; int fin = 0; ssize_t sveccnt = 0; if (session && ngtcp2_conn_get_max_data_left(quic.conn)) { sveccnt = s->write_stream(stream_id, fin, vec.data(), vec.size()); if (sveccnt == -1) { return -1; } } ngtcp2_ssize ndatalen; auto v = vec.data(); auto vcnt = static_cast<size_t>(sveccnt); uint32_t flags = NGTCP2_WRITE_STREAM_FLAG_MORE; if (fin) { flags |= NGTCP2_WRITE_STREAM_FLAG_FIN; } auto nwrite = ngtcp2_conn_writev_stream( quic.conn, &ps.path, nullptr, bufpos, max_udp_payload_size, &ndatalen, flags, stream_id, reinterpret_cast<const ngtcp2_vec *>(v), vcnt, timestamp(worker->loop)); if (nwrite < 0) { switch (nwrite) { case NGTCP2_ERR_STREAM_DATA_BLOCKED: assert(ndatalen == -1); if (s->block_stream(stream_id) != 0) { return -1; } continue; case NGTCP2_ERR_STREAM_SHUT_WR: assert(ndatalen == -1); if (s->shutdown_stream_write(stream_id) != 0) { return -1; } continue; case NGTCP2_ERR_WRITE_MORE: assert(ndatalen >= 0); if (s->add_write_offset(stream_id, ndatalen) != 0) { return -1; } continue; } quic.last_error = quic::err_transport(nwrite); return -1; } else if (ndatalen >= 0 && s->add_write_offset(stream_id, ndatalen) != 0) { return -1; } quic_restart_pkt_timer(); if (nwrite == 0) { if (bufpos - buf.data()) { write_udp(ps.path.remote.addr, ps.path.remote.addrlen, buf.data(), bufpos - buf.data(), max_udp_payload_size); } return 0; } bufpos += nwrite; // Assume that the path does not change. if (++pktcnt == max_pktcnt || static_cast<size_t>(nwrite) < max_udp_payload_size) { write_udp(ps.path.remote.addr, ps.path.remote.addrlen, buf.data(), bufpos - buf.data(), max_udp_payload_size); signal_write(); return 0; } } } } // namespace h2load
// Copyright (c) 2014-2018 The Danxome Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/hmac_sha256.h> #include <string.h> CHMAC_SHA256::CHMAC_SHA256(const unsigned char* key, size_t keylen) { unsigned char rkey[64]; if (keylen <= 64) { memcpy(rkey, key, keylen); memset(rkey + keylen, 0, 64 - keylen); } else { CSHA256().Write(key, keylen).Finalize(rkey); memset(rkey + 32, 0, 32); } for (int n = 0; n < 64; n++) rkey[n] ^= 0x5c; outer.Write(rkey, 64); for (int n = 0; n < 64; n++) rkey[n] ^= 0x5c ^ 0x36; inner.Write(rkey, 64); } void CHMAC_SHA256::Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char temp[32]; inner.Finalize(temp); outer.Write(temp, 32).Finalize(hash); }
// ---------------------------------------------------------------------------- // Copyright 2016-2017 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------- // Note: this macro is needed on armcc to get the the PRI*32 macros // from inttypes.h in a C++ code. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "update-lwm2m-mbed-apis.h" #include "update-client-common/arm_uc_common.h" #include "update-client-lwm2m/lwm2m-source.h" #include "update-client-lwm2m/FirmwareUpdateResource.h" #include "update-client-lwm2m/DeviceMetadataResource.h" #include "update-client-common/arm_uc_config.h" /* error management */ static arm_uc_error_t arm_ucs_lwm2m_error = {ERR_NONE}; arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetError(void) { return arm_ucs_lwm2m_error; } arm_uc_error_t ARM_UCS_LWM2M_SOURCE_SetError(arm_uc_error_t an_error) { return (arm_ucs_lwm2m_error = an_error); } /* forward declaration */ static void ARM_UCS_PackageCallback(const uint8_t *buffer, uint16_t length); /* local copy of the received manifest */ static uint8_t *arm_ucs_manifest_buffer = NULL; static uint16_t arm_ucs_manifest_length = 0; /* callback function pointer and struct */ static void (*ARM_UCS_EventHandler)(uintptr_t event) = 0; static arm_uc_callback_t callbackNodeManifest = { NULL, 0, NULL, 0 }; static arm_uc_callback_t callbackNodeNotification = { NULL, 0, NULL, 0 }; #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) static bool arm_uc_get_data_request_transaction_ongoing = false; static size_t arm_uc_received_file_size = 0; static size_t arm_uc_total_file_size = 0; static void arm_uc_get_data_req_callback(const uint8_t *buffer, size_t buffer_size, size_t total_size, bool last_block, void *context); static void arm_uc_get_data_req_error_callback(get_data_req_error_t error_code, void *context); #define ARM_UCS_DEFAULT_COST (900) #define ARM_UCS_HASH_LENGTH (40) // The hub uses a double buffer system to speed up firmware download and storage #define BUFFER_SIZE_MAX (ARM_UC_BUFFER_SIZE / 2) // define size of the double buffers #if BUFFER_SIZE_MAX < SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE #error MBED_CLOUD_CLIENT_UPDATE_BUFFER must be at least double the size of SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE #endif // Set proper Storage buffer size with requirements: // 1. Storage buffer size >= Block size (SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE) // 1. & 2 AND is >= page size (BUFFER_SIZE_MAX) // 2. & 3. AND is multiple of Block size (X * SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE) #define STORAGE_BUFFER_SIZE max_storage(SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE, BUFFER_SIZE_MAX) // 1. 2. 3. #define max_storage(X,Y) ((X) > (Y) ? (X) : ( (Y%X==0) ? (Y) :(BLOCK_MULTIPLIER(X,Y)*X))) #define BLOCK_MULTIPLIER(X,Y) ((Y/X)+1) static uint8_t storage_message[STORAGE_BUFFER_SIZE]; static arm_uc_buffer_t storage_buffer = { .size_max = STORAGE_BUFFER_SIZE, .size = 0, .ptr = storage_message }; static arm_uc_buffer_t *output_buffer_ptr = NULL; static char *copy_full_url = NULL; static DownloadType download_type = FIRMWARE_DOWNLOAD; //default FIRMWARE = COAP download using filepath of server; #endif // ARM_UC_FEATURE_FW_SOURCE_COAP /** * @brief Get driver version. * @return Driver version. */ uint32_t ARM_UCS_LWM2M_SOURCE_GetVersion(void) { return 0; } /** * @brief Get Source capabilities. * @return Struct containing capabilites. See definition above. */ ARM_SOURCE_CAPABILITIES ARM_UCS_LWM2M_SOURCE_GetCapabilities(void) { ARM_SOURCE_CAPABILITIES result; UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetCapabilities:"); result.notify = 0; result.manifest_default = 0; result.manifest_url = 0; result.firmware = 0; result.keytable = 0; /* the event handler must be set before module can be used */ if (ARM_UCS_EventHandler != 0) { result.notify = 1; result.manifest_default = 1; result.manifest_url = 1; #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) result.firmware = 1; #endif result.keytable = 1; } return result; } /** * @brief Initialize Source. * @details Function pointer to event handler is passed as argument. * * @param cb_event Function pointer to event handler. See events above. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_Initialize(ARM_SOURCE_SignalEvent_t cb_event) { UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_Initialize: %p", cb_event); ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) arm_uc_get_data_request_transaction_ongoing = false; arm_uc_received_file_size = 0; arm_uc_total_file_size = 0; #endif if (cb_event != 0) { /* store callback handler */ ARM_UCS_EventHandler = cb_event; /* Initialize LWM2M Firmware Update Object */ FirmwareUpdateResource::Initialize(); /* Register callback handler */ FirmwareUpdateResource::addPackageCallback(ARM_UCS_PackageCallback); DeviceMetadataResource::Initialize(); ARM_UC_SET_ERROR(result, ERR_NONE); } if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } /** * @brief Uninitialized Source. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_Uninitialize(void) { ARM_UC_INIT_ERROR(retval, ERR_NONE); DeviceMetadataResource::Uninitialize(); FirmwareUpdateResource::Uninitialize(); return retval; } /** * @brief Cost estimation for retrieving manifest from the default location. * @details The estimation can vary over time and should not be cached too long. * 0x00000000 - The manifest is already downloaded. * 0xFFFFFFFF - Cannot retrieve manifest from this Source. * * @param cost Pointer to variable for the return value. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetManifestDefaultCost(uint32_t *cost) { ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); if (cost != 0) { /* set cost to 0 when manifest is cached */ if (arm_ucs_manifest_buffer && arm_ucs_manifest_length) { *cost = 0; } /* set cost to 0xFFFFFFFF when manifest has been read */ else { *cost = 0xFFFFFFFF; } ARM_UC_SET_ERROR(result, ERR_NONE); } if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } /** * @brief Retrieve manifest from the default location. * @details Manifest is stored in supplied buffer. * Event is generated once manifest is in buffer. * * @param buffer Struct containing byte array, maximum size, and actual size. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetManifestDefault(arm_uc_buffer_t *buffer, uint32_t offset) { ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); /* copy manifest from cache into buffer */ if ((buffer != NULL) && (buffer->ptr != NULL) && (arm_ucs_manifest_buffer != NULL) && (arm_ucs_manifest_length != 0) && (offset < arm_ucs_manifest_length)) { /* remaining length based on offset request */ uint16_t length = arm_ucs_manifest_length - offset; /* set actual length based on buffer size */ if (length > buffer->size_max) { length = buffer->size_max; } /* size check */ if (length > 0) { /* copy manifest from local buffer to external buffer */ memcpy(buffer->ptr, &arm_ucs_manifest_buffer[offset], length); buffer->size = length; /* delete local buffer once the entire manifest has been read */ if (offset + length >= arm_ucs_manifest_length) { delete[] arm_ucs_manifest_buffer; arm_ucs_manifest_buffer = NULL; arm_ucs_manifest_length = 0; } ARM_UC_SET_ERROR(result, ERR_NONE); /* signal event handler that manifest has been copied to buffer */ if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_MANIFEST); } } } if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } static void ARM_UCS_PackageCallback(const uint8_t *buffer, uint16_t length) { uint32_t event_code = EVENT_ERROR; if (arm_ucs_manifest_buffer) { UC_SRCE_ERR_MSG("received new manifest before reading the old one"); /* delete old buffer to make space for the new one */ delete[] arm_ucs_manifest_buffer; arm_ucs_manifest_length = 0; } /* allocate a local buffer of the same size as the manifest */ arm_ucs_manifest_buffer = new uint8_t[length]; if (arm_ucs_manifest_buffer) { /* copy manifest from payload to local buffer */ memcpy(arm_ucs_manifest_buffer, buffer, length); arm_ucs_manifest_length = length; event_code = EVENT_NOTIFICATION; } /* signal event handler with result */ if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeNotification, ARM_UCS_EventHandler, event_code); } } /** * @brief Cost estimation for retrieving firmware from URL. * @details The estimation can vary over time and should not be cached too long. * 0x00000000 - The firmware is already downloaded. * 0xFFFFFFFF - Cannot retrieve firmware from this Source. * * @param uri URI struct with firmware location. * @param cost Pointer to variable for the return value. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetFirmwareURLCost(arm_uc_uri_t *uri, uint32_t *cost) { UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareURLCost"); ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) /* not supported - return default cost regardless of actual uri location */ if ((uri != 0) && (cost != 0)) { UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareURLCost uri and cost"); *cost = ARM_UCS_DEFAULT_COST; result.code = ERR_NONE ; } #else /* not supported */ if (cost != 0) { UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareURLCost cost 0xFFFFFFFF"); *cost = 0xFFFFFFFF; result.code = ERR_NONE ; } #endif if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } /** * @brief Retrieve firmware fragment. * @details Firmware fragment is stored in supplied buffer. * Event is generated once fragment is in buffer. * * @param uri URI struct with firmware location. * @param buffer Struct containing byte array, maximum size, and actual size. * @param offset Firmware offset to retrieve fragment from. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment(arm_uc_uri_t *uri, arm_uc_buffer_t *buffer, uint32_t offset) { arm_uc_error_t retval = { .code = SRCE_ERR_INVALID_PARAMETER }; #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) if (uri == NULL || buffer == NULL || FirmwareUpdateResource::getM2MInterface() == NULL) { return retval; } UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: %s %s, buffer size: %" PRIu32 ", buffer max: %" PRIu32 " offset: %" PRIu32, (const char *)uri->ptr, uri->path, buffer->size, buffer->size_max, offset); UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: total file size %" PRIu32 ", received file size %" PRIu32, (uint32_t)arm_uc_total_file_size, (uint32_t)arm_uc_received_file_size); /* * NOTE: we are using M2MInterface API "get_data_request()" asynchronously, so first call to GetFirmwareFragment() * will not return anything in the buffer. Instead we will get COAP blocks into callback arm_uc_get_data_req_callback() * where we will copy those to our internal storage_buffer. When storage_buffer has enough data * (more or eq than buffer->size_max == Storage Page size) we will copy data from it to output buffer * and indicate to Hub state machine using event EVENT_FIRMWARE */ if (offset == 0) { // First fragment storage_buffer.size = 0; arm_uc_received_file_size = 0; arm_uc_total_file_size = 0; } else if (arm_uc_received_file_size == 0) { // The received file size was reset to zero indicating that we have received the full payload // as indicated by the server but we are asked to carry on downloading from the given offset. // This indicates a mismatch between the actual payload size in the server and that given in the manifest. UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: payload size indicated in manifest is bigger than that reported by server!"); if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_ERROR); } return retval; } output_buffer_ptr = buffer; free(copy_full_url); copy_full_url = (char *)malloc(arm_uc_calculate_full_uri_length(uri)); if (copy_full_url == NULL) { //TODO to return SRCE_ERR_OUT_OF_MEMORY UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: ERROR OUT OF MEMORY for uri copy!"); return retval; } if (uri->scheme == URI_SCHEME_COAPS) { strcpy(copy_full_url, UC_COAPS_STRING); } else if (uri->scheme == URI_SCHEME_HTTP) { strcpy(copy_full_url, UC_HTTP_STRING); } else { UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: Not Supported SCHEME! length of copy url: %u", sizeof(copy_full_url)); return retval; } strcat(copy_full_url, (const char *)uri->ptr); strcat(copy_full_url, uri->path); if ((arm_uc_received_file_size == arm_uc_total_file_size && arm_uc_received_file_size != 0)) { // If last block - write to buffer and complete if (storage_buffer.ptr && (arm_uc_received_file_size == arm_uc_total_file_size)) { memcpy(buffer->ptr, storage_buffer.ptr, storage_buffer.size); buffer->size = storage_buffer.size; memmove(storage_buffer.ptr, storage_buffer.ptr + storage_buffer.size, (storage_buffer.size_max - storage_buffer.size)); storage_buffer.size -= buffer->size; } // We were waiting for one more state machine cycle for previous write to complete // Now we can return with EVENT_FIRMWARE so that main state machine changes properly if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_FIRMWARE); } retval.code = ERR_NONE; arm_uc_received_file_size = 0; arm_uc_total_file_size = 0; } else if (!arm_uc_get_data_request_transaction_ongoing) { // We need to get request for next block of data UC_SRCE_TRACE("ARM_UCS_LWM2M_SOURCE_GetFirmwareFragment: Issue new get request for uri: %s, offset: %" PRIu32, copy_full_url, (uint32_t)arm_uc_received_file_size); if (FirmwareUpdateResource::getM2MInterface()) { FirmwareUpdateResource::getM2MInterface()->get_data_request(download_type, copy_full_url, arm_uc_received_file_size, true, arm_uc_get_data_req_callback, arm_uc_get_data_req_error_callback, FirmwareUpdateResource::getM2MInterface()); arm_uc_get_data_request_transaction_ongoing = true; retval.code = ERR_NONE; } } else { // There is not enough data in Storage buffer yet // AND We have Async get_data_request already ongoing // -> Do nothing we should not get here? // This can happen if GetFirmwareFragment is called again before // the previous get completed with buffer and EVENT_FIRMWARE UC_SRCE_ERR_MSG("Internal error: BLOCK - data request already ongoing"); } if (ARM_UC_IS_ERROR(retval)) { ARM_UCS_LWM2M_SOURCE_SetError(retval); } return retval; #else (void) uri; (void) buffer; (void) offset; return retval; #endif //ARM_UC_FEATURE_FW_SOURCE_COAP } #if defined(ARM_UC_FEATURE_FW_SOURCE_COAP) && (ARM_UC_FEATURE_FW_SOURCE_COAP == 1) void arm_uc_get_data_req_callback(const uint8_t *buffer, size_t buffer_size, size_t total_size, bool last_block, void *context) { (void)last_block; UC_SRCE_TRACE("get_data_req_callback: %" PRIu32 ", %" PRIu32, (uint32_t)buffer_size, (uint32_t)total_size); M2MInterface *interface = (M2MInterface *)context; if (arm_uc_received_file_size == 0) { arm_uc_total_file_size = total_size; } arm_uc_received_file_size += buffer_size; UC_SRCE_TRACE("get_data_req_callback: received %" PRIu32 "/%" PRIu32, (uint32_t)arm_uc_received_file_size, (uint32_t)arm_uc_total_file_size); if (arm_uc_received_file_size == arm_uc_total_file_size) { UC_SRCE_TRACE("get_data_req_callback: transfer completed\n"); } /* * FLOW: * 1. If there is space in Storage buffer for the incoming buffer -> copy buffer to storage buffer * 2. Else signal error event EVENT_ERROR_BUFFER_SIZE */ // Check there is space available in the storage buffer if (storage_buffer.size_max - storage_buffer.size >= buffer_size) { memcpy(storage_buffer.ptr + storage_buffer.size, buffer, buffer_size); storage_buffer.size += buffer_size; } else { // Error - no space available, signal it to source manager UC_SRCE_TRACE("arm_uc_get_data_req_callback: Storage Buffer OVERFLOW ERROR!! \n"); if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_ERROR_BUFFER_SIZE); } return; } /* * FLOW: * 1. If there is enough data in storage-buffer now to complete to output buffer, copy now and indicate with EVENT_FIRMWARE * to continue to write -cycle * 2. Else if this is the last block of data, copy the remaining (<size_max) to output buffer and indicate with * EVENT_FIRMWARE to continue to write-cycle * 3. Else Request new block of data using API get_data_request */ if (storage_buffer.size >= output_buffer_ptr->size_max) { // 1. We have received into Storage buffer at least one page size of data // -> Let's return it to UC Hub so that it can be written UC_SRCE_TRACE("arm_uc_get_data_req_callback: return with Storage buffer size: %" PRIu32 ", buffer size: %" PRIu32, storage_buffer.size, output_buffer_ptr->size_max); if (storage_buffer.ptr) { memcpy(output_buffer_ptr->ptr, storage_buffer.ptr, output_buffer_ptr->size_max); //storage_buffer.ptr += buffer->size_max; memmove(storage_buffer.ptr, storage_buffer.ptr + output_buffer_ptr->size_max, (storage_buffer.size_max - output_buffer_ptr->size_max)); storage_buffer.size -= output_buffer_ptr->size_max; output_buffer_ptr->size = output_buffer_ptr->size_max; } if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_FIRMWARE); } arm_uc_get_data_request_transaction_ongoing = false; } else if (arm_uc_received_file_size == arm_uc_total_file_size && arm_uc_received_file_size != 0) { // 2. this is the last block of data - copy to output buffer and complete with EVENT_FIRMWARE if (storage_buffer.ptr && (arm_uc_received_file_size == arm_uc_total_file_size)) { memcpy(output_buffer_ptr->ptr, storage_buffer.ptr, storage_buffer.size); output_buffer_ptr->size = storage_buffer.size; memmove(storage_buffer.ptr, storage_buffer.ptr + storage_buffer.size, (storage_buffer.size_max - storage_buffer.size)); storage_buffer.size = 0; } // We were waiting for one more state machine cycle for previous write to complete // Now we can return with EVENT_FIRMWARE so that main state machine changes properly if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_FIRMWARE); } arm_uc_get_data_request_transaction_ongoing = false; free(copy_full_url); copy_full_url = NULL; arm_uc_received_file_size = 0; arm_uc_total_file_size = 0; } else { // 3. We want to issue new get data UC_SRCE_TRACE("arm_uc_get_data_req_callback: Issue new get request for uri: %s, offset: %" PRIu32, copy_full_url, (uint32_t)arm_uc_received_file_size); interface->get_data_request(download_type, copy_full_url, arm_uc_received_file_size, true, arm_uc_get_data_req_callback, arm_uc_get_data_req_error_callback, interface); arm_uc_get_data_request_transaction_ongoing = true; } #ifdef ARM_UC_COAP_DATA_PRINTOUT if (buffer) { uint32_t i = 0; int row_len = 40; uint32_t max_length = 2048; while (i < buffer_size && i < max_length) { if (i + row_len > buffer_size) { row_len = buffer_size - i; } UC_SRCE_TRACE("Payload:\t\t%s", tr_array(buffer + i, row_len)); // in HEX i += row_len; } } #endif } void arm_uc_get_data_req_error_callback(get_data_req_error_t error_code, void *context) { UC_SRCE_TRACE("get_data_req_error_callback: ERROR: %u\n", error_code); arm_uc_received_file_size = 0; arm_uc_total_file_size = 0; arm_uc_get_data_request_transaction_ongoing = false; free(copy_full_url); copy_full_url = NULL; download_type = FIRMWARE_DOWNLOAD; if (ARM_UCS_EventHandler) { ARM_UC_PostCallback(&callbackNodeManifest, ARM_UCS_EventHandler, EVENT_ERROR); } } #endif //ARM_UC_FEATURE_FW_SOURCE_COAP /*****************************************************************************/ /* Capabilities not supported by this source */ /*****************************************************************************/ /** * @brief Cost estimation for retrieving manifest from URL. * @details The estimation can vary over time and should not be cached too long. * 0x00000000 - The manifest is already downloaded. * 0xFFFFFFFF - Cannot retrieve manifest from this Source. * * @param uri URI struct with manifest location. * @param cost Pointer to variable for the return value. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetManifestURLCost(arm_uc_uri_t *uri, uint32_t *cost) { (void) uri; (void) cost; ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); /* not supported - return default cost regardless of actual uri location */ if (cost) { *cost = 0xFFFFFFFF; ARM_UC_SET_ERROR(result, ERR_NONE); } if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } /** * @brief Cost estimation for retrieving key table from URL. * @details The estimation can vary over time and should not be cached too long. * 0x00000000 - The firmware is already downloaded. * 0xFFFFFFFF - Cannot retrieve firmware from this Source. * * @param uri URI struct with keytable location. * @param cost Pointer to variable for the return value. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetKeytableURLCost(arm_uc_uri_t *uri, uint32_t *cost) { (void) uri; (void) cost; ARM_UC_INIT_ERROR(result, SRCE_ERR_INVALID_PARAMETER); /* not supported - return default cost regardless of actual uri location */ if ((uri != 0) && (cost != 0)) { *cost = 0xFFFFFFFF; ARM_UC_SET_ERROR(result, ERR_NONE); } if (ARM_UC_IS_ERROR(result)) { ARM_UCS_LWM2M_SOURCE_SetError(result); } return result; } /** * @brief Retrieve manifest from URL. * @details Manifest is stored in supplied buffer. * Event is generated once manifest is in buffer. * * @param uri URI struct with manifest location. * @param buffer Struct containing byte array, maximum size, and actual size. * * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetManifestURL(arm_uc_uri_t *uri, arm_uc_buffer_t *buffer, uint32_t offset) { (void) uri; (void) buffer; (void) offset; ARM_UC_INIT_ERROR(retval, SRCE_ERR_INVALID_PARAMETER); if (ARM_UC_IS_ERROR(retval)) { ARM_UCS_LWM2M_SOURCE_SetError(retval); } return retval; } /** * @brief Retrieve a key table from a URL. * @details Key table is stored in supplied buffer. * Event is generated once fragment is in buffer. * * @param uri URI struct with keytable location. * @param buffer Struct containing byte array, maximum size, and actual size. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_SOURCE_GetKeytableURL(arm_uc_uri_t *uri, arm_uc_buffer_t *buffer) { (void) uri; (void) buffer; ARM_UC_INIT_ERROR(retval, SRCE_ERR_INVALID_PARAMETER); if (ARM_UC_IS_ERROR(retval)) { ARM_UCS_LWM2M_SOURCE_SetError(retval); } return retval; }
/* easy: C++ ESOP library * Copyright (C) 2018 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <algorithm> #include <cassert> #include <cctype> #include <locale> #include <string> /* * This code is based on * https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring */ namespace easy::utils { inline void ltrim( std::string& s ) { s.erase( s.begin(), std::find_if( s.begin(), s.end(), []( int ch ) { return !std::isspace( ch ); } ) ); } inline void rtrim( std::string& s ) { s.erase( std::find_if( s.rbegin(), s.rend(), []( int ch ) { return !std::isspace( ch ); } ) .base(), s.end() ); } inline void trim( std::string& s ) { ltrim( s ); rtrim( s ); } inline std::string ltrim_copy( std::string s ) { ltrim( s ); return s; } inline std::string rtrim_copy( std::string s ) { rtrim( s ); return s; } inline std::string trim_copy( std::string s ) { trim( s ); return s; } inline std::string binary_string_from_hex_string( const std::string& hex ) { std::string result = ""; for ( auto i = 0u; i < hex.size(); ++i ) { switch ( hex[i] ) { case '0': result.append( "0000" ); break; case '1': result.append( "0001" ); break; case '2': result.append( "0010" ); break; case '3': result.append( "0011" ); break; case '4': result.append( "0100" ); break; case '5': result.append( "0101" ); break; case '6': result.append( "0110" ); break; case '7': result.append( "0111" ); break; case '8': result.append( "1000" ); break; case '9': result.append( "1001" ); break; case 'a': result.append( "1010" ); break; case 'b': result.append( "1011" ); break; case 'c': result.append( "1100" ); break; case 'd': result.append( "1101" ); break; case 'e': result.append( "1110" ); break; case 'f': result.append( "1111" ); break; } } std::reverse( result.begin(), result.end() ); return result; } inline std::string hex_string_from_binary_string( const std::string& binary ) { assert( ( binary.size() % 4 ) == 0 ); std::string r = ""; for ( auto i = 0u; i < binary.size(); i += 4 ) { const auto bucket = binary.substr( i, 4 ); if ( bucket == "0000" ) r += '0'; else if ( bucket == "0001" ) r += '1'; else if ( bucket == "0010" ) r += '2'; else if ( bucket == "0011" ) r += '3'; else if ( bucket == "0100" ) r += '4'; else if ( bucket == "0101" ) r += '5'; else if ( bucket == "0110" ) r += '6'; else if ( bucket == "0111" ) r += '7'; else if ( bucket == "1000" ) r += '8'; else if ( bucket == "1001" ) r += '9'; else if ( bucket == "1010" ) r += 'a'; else if ( bucket == "1011" ) r += 'b'; else if ( bucket == "1100" ) r += 'c'; else if ( bucket == "1101" ) r += 'd'; else if ( bucket == "1110" ) r += 'e'; else if ( bucket == "1111" ) r += 'f'; } return r; } } // namespace easy::utils // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
/* * Copyright (c) 2020-2021, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file decode_filmgrain_gennoise_rp1_packet_g12.cpp //! \brief film grain regress phase1 kernel render packet which used in by mediapipline. //! \details film grain regress phase1 render packet provide the structures and generate the cmd buffer which mediapipline will used. //! #include "decode_filmgrain_gennoise_rp1_packet_g12.h" #include "decode_av1_filmgrain_feature_g12.h" #include "decode_av1_feature_defs_g12.h" #include "mos_defs.h" namespace decode { FilmGrainRp1Packet::FilmGrainRp1Packet(MediaPipeline *pipeline, MediaTask *task, CodechalHwInterface *hwInterface): CmdPacket(task), RenderCmdPacket(task, hwInterface->GetOsInterface(), hwInterface->GetRenderHalInterface()) { if (pipeline != nullptr) { m_statusReport = pipeline->GetStatusReportInstance(); m_featureManager = pipeline->GetFeatureManager(); m_av1Pipeline = dynamic_cast<Av1Pipeline *>(pipeline); } if (hwInterface != nullptr) { m_hwInterface = hwInterface; m_miInterface = hwInterface->GetMiInterface(); m_osInterface = hwInterface->GetOsInterface(); m_vdencInterface = hwInterface->GetVdencInterface(); m_renderHal = hwInterface->GetRenderHalInterface(); } } MOS_STATUS FilmGrainRp1Packet::Init() { DECODE_FUNC_CALL(); DECODE_CHK_NULL(m_miInterface); DECODE_CHK_NULL(m_statusReport); DECODE_CHK_NULL(m_featureManager); DECODE_CHK_NULL(m_av1Pipeline); DECODE_CHK_NULL(m_osInterface); DECODE_CHK_NULL(m_vdencInterface); DECODE_CHK_STATUS(RenderCmdPacket::Init()); m_av1BasicFeature = dynamic_cast<Av1BasicFeature *>(m_featureManager->GetFeature(FeatureIDs::basicFeature)); DECODE_CHK_NULL(m_av1BasicFeature); m_filmGrainFeature = dynamic_cast<Av1DecodeFilmGrainG12 *>(m_featureManager->GetFeature(Av1FeatureIDs::av1SwFilmGrain)); DECODE_CHK_NULL(m_filmGrainFeature); m_allocator = m_av1Pipeline->GetDecodeAllocator(); DECODE_CHK_NULL(m_allocator); DECODE_CHK_STATUS(Initilize()); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::Prepare() { DECODE_FUNC_CALL(); DECODE_CHK_NULL(m_hwInterface); m_picParams = m_av1BasicFeature->m_av1PicParams; ResetBindingTableEntry(); DECODE_CHK_STATUS(RenderEngineSetup()); DECODE_CHK_STATUS(KernelStateSetup()); DECODE_CHK_STATUS(SetUpSurfaceState()); DECODE_CHK_STATUS(SetCurbeRegressPhase1()); DECODE_CHK_STATUS(LoadKernel()); if (m_walkerType == WALKER_TYPE_MEDIA) { DECODE_CHK_STATUS(SetupMediaWalker()); } else if (m_walkerType == WALKER_TYPE_COMPUTE) { m_renderData.walkerParam.alignedRect.left = 0; m_renderData.walkerParam.alignedRect.top = 0; m_renderData.walkerParam.alignedRect.right = m_av1BasicFeature->m_filmGrainProcParams->m_outputSurface->dwWidth; m_renderData.walkerParam.alignedRect.bottom = m_av1BasicFeature->m_filmGrainProcParams->m_outputSurface->dwHeight; m_renderData.walkerParam.iCurbeLength = m_renderData.iCurbeLength; m_renderData.walkerParam.iCurbeOffset = m_curbeOffset; m_renderData.walkerParam.iBindingTable = m_bindingTable; m_renderData.walkerParam.iMediaID = m_mediaID; m_renderData.walkerParam.iBlocksX = m_renderData.KernelParam.blocks_x; m_renderData.walkerParam.iBlocksY = m_renderData.KernelParam.blocks_y; DECODE_CHK_STATUS(PrepareComputeWalkerParams(m_renderData.walkerParam, m_gpgpuWalkerParams)); } else { DECODE_ASSERTMESSAGE("Walker is disabled!"); return MOS_STATUS_UNKNOWN; } return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::Submit(MOS_COMMAND_BUFFER *commandBuffer, uint8_t packetPhase) { PMOS_INTERFACE pOsInterface = nullptr; MOS_STATUS eStatus = MOS_STATUS_SUCCESS; uint32_t dwSyncTag = 0; int32_t i = 0, iRemaining = 0; PMHW_MI_INTERFACE pMhwMiInterface = nullptr; MhwRenderInterface * pMhwRender = nullptr; MHW_MEDIA_STATE_FLUSH_PARAM FlushParam = {}; bool bEnableSLM = false; RENDERHAL_GENERIC_PROLOG_PARAMS GenericPrologParams = {}; MOS_RESOURCE GpuStatusBuffer = {}; MediaPerfProfiler * pPerfProfiler = nullptr; MOS_CONTEXT * pOsContext = nullptr; PMHW_MI_MMIOREGISTERS pMmioRegisters = nullptr; RENDER_PACKET_CHK_NULL_RETURN(m_renderHal); RENDER_PACKET_CHK_NULL_RETURN(m_renderHal->pMhwRenderInterface); RENDER_PACKET_CHK_NULL_RETURN(m_renderHal->pMhwMiInterface); RENDER_PACKET_CHK_NULL_RETURN(m_renderHal->pMhwRenderInterface->GetMmioRegisters()); RENDER_PACKET_CHK_NULL_RETURN(m_renderHal->pOsInterface); RENDER_PACKET_CHK_NULL_RETURN(m_renderHal->pOsInterface->pOsContext); eStatus = MOS_STATUS_UNKNOWN; pOsInterface = m_renderHal->pOsInterface; pMhwMiInterface = m_renderHal->pMhwMiInterface; pMhwRender = m_renderHal->pMhwRenderInterface; iRemaining = 0; FlushParam = g_cRenderHal_InitMediaStateFlushParams; pPerfProfiler = m_renderHal->pPerfProfiler; pOsContext = pOsInterface->pOsContext; pMmioRegisters = pMhwRender->GetMmioRegisters(); RENDER_PACKET_CHK_STATUS_RETURN(SetPowerMode(CODECHAl_MEDIA_STATE_AV1_FILM_GRAIN_RP1)); // Initialize command buffer and insert prolog RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnInitCommandBuffer(m_renderHal, commandBuffer, &GenericPrologParams)); if (pOsInterface && !m_av1BasicFeature->m_singleKernelPerfFlag) { pOsInterface->pfnSetPerfTag(pOsInterface, ((PERFTAG_CALL_FILM_GRAIN_RP1_KERNEL << 8) | CODECHAL_DECODE_MODE_AV1VLD << 4 | m_av1BasicFeature->m_pictureCodingType)); RENDER_PACKET_CHK_STATUS_RETURN(pPerfProfiler->AddPerfCollectStartCmd((void *)m_renderHal, pOsInterface, pMhwMiInterface, commandBuffer)); } // Write timing data for 3P budget RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnSendTimingData(m_renderHal, commandBuffer, true)); bEnableSLM = false; // Media walker first RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnSetCacheOverrideParams( m_renderHal, &m_renderHal->L3CacheSettings, bEnableSLM)); // Flush media states RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnSendMediaStates( m_renderHal, commandBuffer, m_walkerType == WALKER_TYPE_MEDIA ? &m_mediaWalkerParams : nullptr, m_walkerType == WALKER_TYPE_MEDIA ? nullptr : &m_gpgpuWalkerParams)); // Write back GPU Status tag if (!pOsInterface->bEnableKmdMediaFrameTracking) { RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnSendRcsStatusTag(m_renderHal, commandBuffer)); } if (!m_av1BasicFeature->m_singleKernelPerfFlag) { RENDER_PACKET_CHK_STATUS_RETURN(pPerfProfiler->AddPerfCollectEndCmd((void *)m_renderHal, pOsInterface, pMhwMiInterface, commandBuffer)); } // Write timing data for 3P budget RENDER_PACKET_CHK_STATUS_RETURN(m_renderHal->pfnSendTimingData(m_renderHal, commandBuffer, false)); MHW_PIPE_CONTROL_PARAMS PipeControlParams; MOS_ZeroMemory(&PipeControlParams, sizeof(PipeControlParams)); PipeControlParams.dwFlushMode = MHW_FLUSH_WRITE_CACHE; PipeControlParams.bGenericMediaStateClear = true; PipeControlParams.bIndirectStatePointersDisable = true; PipeControlParams.bDisableCSStall = false; RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddPipeControl(commandBuffer, nullptr, &PipeControlParams)); if (MEDIA_IS_WA(m_renderHal->pWaTable, WaSendDummyVFEafterPipelineSelect)) { MHW_VFE_PARAMS VfeStateParams = {}; VfeStateParams.dwNumberofURBEntries = 1; RENDER_PACKET_CHK_STATUS_RETURN(pMhwRender->AddMediaVfeCmd(commandBuffer, &VfeStateParams)); } // Add media flush command in case HW not cleaning the media state if (MEDIA_IS_WA(m_renderHal->pWaTable, WaMSFWithNoWatermarkTSGHang)) { FlushParam.bFlushToGo = true; if (m_walkerType == WALKER_TYPE_MEDIA) { FlushParam.ui8InterfaceDescriptorOffset = m_mediaWalkerParams.InterfaceDescriptorOffset; } else { RENDER_PACKET_ASSERTMESSAGE("ERROR, pWalkerParams is nullptr and cannot get InterfaceDescriptorOffset."); } RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddMediaStateFlush(commandBuffer, nullptr, &FlushParam)); } else if (MEDIA_IS_WA(m_renderHal->pWaTable, WaAddMediaStateFlushCmd)) { RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddMediaStateFlush(commandBuffer, nullptr, &FlushParam)); } if (pBatchBuffer) { // Send Batch Buffer end command (HW/OS dependent) RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddMiBatchBufferEnd(commandBuffer, nullptr)); } else if (IsMiBBEndNeeded(pOsInterface)) { // Send Batch Buffer end command for 1st level Batch Buffer RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddMiBatchBufferEnd(commandBuffer, nullptr)); } else if (m_renderHal->pOsInterface->bNoParsingAssistanceInKmd) { RENDER_PACKET_CHK_STATUS_RETURN(pMhwMiInterface->AddMiBatchBufferEnd(commandBuffer, nullptr)); } // Return unused command buffer space to OS pOsInterface->pfnReturnCommandBuffer(pOsInterface, commandBuffer, 0); MOS_NULL_RENDERING_FLAGS NullRenderingFlags = pOsInterface->pfnGetNullHWRenderFlags(pOsInterface); if ((NullRenderingFlags.VPLgca || NullRenderingFlags.VPGobal) == false) { dwSyncTag = m_renderHal->pStateHeap->dwNextTag++; // Set media state and batch buffer as busy m_renderHal->pStateHeap->pCurMediaState->bBusy = true; if (pBatchBuffer) { pBatchBuffer->bBusy = true; pBatchBuffer->dwSyncTag = dwSyncTag; } } return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::SetupMediaWalker() { DECODE_FUNC_CALL(); DECODE_CHK_NULL(m_hwInterface); // Current only add Media Walker Support in film Grain m_walkerType = WALKER_TYPE_MEDIA; CODECHAL_WALKER_CODEC_PARAMS walkerCodecParams; memset(&walkerCodecParams, 0, sizeof(walkerCodecParams)); walkerCodecParams.WalkerMode = MHW_WALKER_MODE_DUAL; walkerCodecParams.dwResolutionX = 1; walkerCodecParams.dwResolutionY = 32; walkerCodecParams.bNoDependency = true; DECODE_CHK_STATUS(CodecHalInitMediaObjectWalkerParams(m_hwInterface, &m_mediaWalkerParams, &walkerCodecParams)); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::Initilize() { m_kernelIndex = regressPhase1; return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::KernelStateSetup() { m_kernelCount = 1; MHW_KERNEL_STATE *kernelState = &m_filmGrainFeature->m_kernelStates[m_kernelIndex]; uint32_t btCount = m_filmGrainFeature->m_filmGrainBindingTableCount[m_kernelIndex]; int32_t curbeLength = m_filmGrainFeature->m_filmGrainCurbeSize[m_kernelIndex]; // Initialize States MOS_ZeroMemory(m_filter, sizeof(m_filter)); MOS_ZeroMemory(&m_renderData.KernelEntry, sizeof(Kdll_CacheEntry)); // Set Kernel Parameter m_renderData.KernelParam.GRF_Count = 0; m_renderData.KernelParam.BT_Count = btCount; m_renderData.KernelParam.Sampler_Count = 0; m_renderData.KernelParam.Thread_Count = m_renderHal->pMhwRenderInterface->GetHwCaps()->dwMaxThreads; m_renderData.KernelParam.GRF_Start_Register = 0; m_renderData.KernelParam.CURBE_Length = curbeLength; m_renderData.KernelParam.block_width = CODECHAL_MACROBLOCK_WIDTH; m_renderData.KernelParam.block_height = CODECHAL_MACROBLOCK_HEIGHT; m_renderData.KernelParam.blocks_x = 1; m_renderData.KernelParam.blocks_y = 32; m_renderData.iCurbeOffset = m_renderHal->pMhwStateHeap->GetSizeofCmdInterfaceDescriptorData(); // Set Parameters for Kernel Entry m_renderData.KernelEntry.iKUID = 0; m_renderData.KernelEntry.iKCID = m_kernelIndex; m_renderData.KernelEntry.iFilterSize = 2; m_renderData.KernelEntry.pFilter = m_filter; m_renderData.KernelEntry.iSize = kernelState->KernelParams.iSize; m_renderData.KernelEntry.pBinary = kernelState->KernelParams.pBinary; // set Curbe/Inline Data length m_renderData.iInlineLength = 0; m_renderData.iCurbeLength = 0; return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::SetUpSurfaceState() { DECODE_FUNC_CALL(); MOS_STATUS eStatus = MOS_STATUS_SUCCESS; //Set Surface States RENDERHAL_SURFACE_NEXT renderHalSurfaceNext; MOS_ZeroMemory(&renderHalSurfaceNext, sizeof(RENDERHAL_SURFACE_NEXT)); //Y random values - input bool isWritable = false; RENDERHAL_SURFACE_STATE_PARAMS surfaceParams; MOS_ZeroMemory(&surfaceParams, sizeof(RENDERHAL_SURFACE_STATE_PARAMS)); surfaceParams.MemObjCtl = m_hwInterface->GetCacheabilitySettings()[MOS_CODEC_RESOURCE_USAGE_SURFACE_ELLC_LLC_L3].Value; surfaceParams.bRenderTarget = true; surfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL; m_bindingTableIndex[rp1InputYRandomValue] = SetSurfaceForHwAccess( m_filmGrainFeature->m_yRandomValuesSurface, &renderHalSurfaceNext, &surfaceParams, isWritable); DECODE_VERBOSEMESSAGE("RP1: surface[%d] Input Y Random values index: %d\n", rp1InputYRandomValue, m_bindingTableIndex[rp1InputYRandomValue]); //Y dithering surface - output isWritable = true; MOS_ZeroMemory(&surfaceParams, sizeof(RENDERHAL_SURFACE_STATE_PARAMS)); surfaceParams.MemObjCtl = m_hwInterface->GetCacheabilitySettings()[MOS_CODEC_RESOURCE_USAGE_SURFACE_ELLC_LLC_L3].Value; surfaceParams.bRenderTarget = true; surfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL; MOS_ZeroMemory(&renderHalSurfaceNext, sizeof(RENDERHAL_SURFACE_NEXT)); m_bindingTableIndex[rp1OutputYDitheringSurface] = SetSurfaceForHwAccess( m_filmGrainFeature->m_yDitheringTempSurface, &renderHalSurfaceNext, &surfaceParams, isWritable); DECODE_VERBOSEMESSAGE("RP1: surface[%d] Output Y Dithering surface BT index: %d\n", rp1OutputYDitheringSurface, m_bindingTableIndex[rp1OutputYDitheringSurface]); //Y coefficients - input isWritable = false; MOS_ZeroMemory(&surfaceParams, sizeof(RENDERHAL_SURFACE_STATE_PARAMS)); surfaceParams.MemObjCtl = m_hwInterface->GetCacheabilitySettings()[MOS_CODEC_RESOURCE_USAGE_SURFACE_ELLC_LLC_L3].Value; surfaceParams.bRenderTarget = false; surfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL; surfaceParams.bBufferUse = true; MOS_ZeroMemory(&renderHalSurfaceNext, sizeof(RENDERHAL_SURFACE_NEXT)); m_bindingTableIndex[rp1InputYCoeff] = SetBufferForHwAccess( *m_filmGrainFeature->m_yCoefficientsSurface, &renderHalSurfaceNext, &surfaceParams, isWritable); DECODE_VERBOSEMESSAGE("RP1: surface[%d] Input Y coeff BT index: %d\n", rp1InputYCoeff, m_bindingTableIndex[rp1InputYCoeff]); return MOS_STATUS_SUCCESS; } MOS_STATUS FilmGrainRp1Packet::SetCurbeRegressPhase1() { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; DECODE_FUNC_CALL(); FilmGrainRegressPhase1Curbe curbe; curbe.DW0.YRandomValuesSurfaceIndex = rp1InputYRandomValue; curbe.DW1.YDitheringSurface = rp1OutputYDitheringSurface; curbe.DW2.YCoeffSurface = rp1InputYCoeff; DECODE_CHK_STATUS(SetupCurbe( &curbe, sizeof(FilmGrainRegressPhase1Curbe), m_renderData.KernelParam.Thread_Count)); return eStatus; } MOS_STATUS FilmGrainRp1Packet::CalculateCommandSize(uint32_t &commandBufferSize, uint32_t &requestedPatchListSize) { DECODE_FUNC_CALL(); MOS_STATUS eStatus = MOS_STATUS_SUCCESS; commandBufferSize = m_hwInterface->GetKernelLoadCommandSize(m_renderData.KernelParam.BT_Count); requestedPatchListSize = 0; return MOS_STATUS_SUCCESS; } }
/**************************************************************************************** * @author: kzvd4729 created: 2019-09-18 15:09:33 * solution_verdict: Accepted language: C++ * run_time (ms): 18 memory_used (MB): 3 * problem: https://vjudge.net/problem/LightOJ-1153 ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e5,inf=1e9; struct flow { int sr,sn;//sr=0,sn=last u+1; struct edge { int a,b,f,c; }; vector<edge>ed; vector<int>dis; vector<vector<int> >adj; void clean(void) { adj.resize(sn+1),dis.resize(sn+1); ed.clear(); for(int i=0;i<=sn;i++) adj[i].clear(); } void addEdge(int a,int b,int c) { edge e;e={a,b,0,c}; adj[a].push_back(ed.size()); ed.push_back(e);e={b,a,0,0}; //e={b,a,0,c};//for bidirectional adj[b].push_back(ed.size()); ed.push_back(e); } bool bfs(void) { for(int i=0;i<=sn;i++)dis[i]=inf; queue<int>q;q.push(sr);dis[sr]=0; while(q.size()) { int u=q.front();q.pop(); for(auto x:adj[u]) { int v=ed[x].b; if(dis[v]==inf&&ed[x].f<ed[x].c) dis[v]=dis[u]+1,q.push(v); } } return dis[sn]!=inf; } int dfs(int u,int flow) { if(!flow||u==sn)return flow; int total=0; for(auto id:adj[u]) { int v=ed[id].b; if(dis[v]!=dis[u]+1)continue; int pushed=dfs(v,min(flow-total,ed[id].c-ed[id].f)); ed[id].f+=pushed;ed[id^1].f-=pushed; total+=pushed; } return total; } int dinic(void) { int flow=0; while(bfs())flow+=dfs(sr,inf); return flow; } }fl; int main() { //ios_base::sync_with_stdio(0);cin.tie(0); int t,tc=0;scanf("%d",&t); while(t--) { int n;scanf("%d",&n); fl.sr=0,fl.sn=n+1;fl.clean(); int sr,sn,m;scanf("%d%d%d",&sr,&sn,&m); int a,b,c; for(int i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); if(a==sr)a=0;if(b==sr)b=0; if(a==sn)a=n+1;if(b==sn)b=n+1; fl.addEdge(a,b,c); fl.addEdge(b,a,c); } printf("Case %d: %d\n",++tc,fl.dinic()); } return 0; }
#include "Communicator.h" #include "ArduinoJson.h" #include "Configuration.h" void Communicator::init(arduino_planter_configuration_t & configuration, planter_state_t & state) { this->configuration = &configuration; this->state = &state; } void Communicator::listen() { state->input_result = Serial.available() ? receive() : REQUEST_NOTHING; } input_result Communicator::receive() { char buffer[INPUT_BUFSIZ]; size_t bytecount = Serial.readBytesUntil('\n', buffer, INPUT_BUFSIZ - 1); return bytecount ? handleInput(buffer) : REQUEST_NOTHING; } input_result Communicator::handleInput(char const * buffer) { switch (*buffer) { case 'p': return REQUEST_PUMP; case 'l': return REQUEST_LAMP; case 'c': return REQUEST_REPORT_CONFIGURATION; case 's': return REQUEST_REPORT_STATE; case 'r': return REQUEST_CONTROL_REMOTE; case 'a': return REQUEST_CONTROL_AUTONOMOUS; case '{': if (buffer[1]) // avoid hanging parser with sole '{' return handleJson(buffer); case '\r': case '\n': return REQUEST_NOTHING; default: return REQUEST_INVALID; } } bool is_conf_key(int id, const char * key) { return !strcmp_P(key, (const char *)pgm_read_word(&(configuration_setting_names[id]))); } input_result Communicator::handleJson(char const * buffer) { StaticJsonBuffer<JSON_BUFSIZ> jsonBuffer; JsonObject &input = jsonBuffer.parseObject(buffer); if (&input == &JsonObject::invalid()) { return REQUEST_INVALID; } input_result_t result = REQUEST_NOTHING; for (JsonObject::iterator it = input.begin(); it != input.end(); ++it) { if (is_conf_key(CONF_ACIDITY_PIN, it->key)) { configuration->acidity_pin = (analog_in_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_AIR_READ_PIN, it->key)) { configuration->air_read_pin = (digital_in_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_WATER_BOTTOM_PIN, it->key)) { configuration->water_bottom_pin = (digital_in_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_WATER_TOP_PIN, it->key)) { configuration->water_top_pin = (digital_in_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_LAMP_PIN, it->key)) { configuration->lamp_pin = (digital_out_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_PUMP_PIN, it->key)) { configuration->pump_pin = (digital_out_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_LAMP_CYCLE_TIME, it->key)) { configuration->lamp_cycle_time = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_LAMP_ACTIVE_TIME, it->key)) { configuration->lamp_active_time = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_PUMP_CYCLE_TIME, it->key)) { configuration->pump_cycle_time = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_PUMP_ACTIVE_TIME, it->key)) { configuration->pump_active_time = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_AIR_READ_INTERVAL, it->key)) { configuration->air_read_interval = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_REPORT_INTERVAL, it->key)) { configuration->report_interval = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_REMOTE_CONTROL_TIMEOUT, it->key)) { configuration->remote_control_timeout = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_STARTUP_DELAY, it->key)) { configuration->startup_delay = (milliseconds_t)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_SERIAL_PORT_SPEED, it->key)) { Serial.println("Serial port may not be reconfigured."); result = REQUEST_INVALID; } else if (is_conf_key(CONF_WATER_SENSOR_VALUE_WHEN_WET, it->key)) { configuration->water_sensor_value_when_wet = (int)it->value; result = REQUEST_RECONFIGURE; } else if (is_conf_key(CONF_AIR_SENSOR_TYPE, it->key)) { configuration->air_sensor_type = (int)it->value; result = REQUEST_RECONFIGURE; } else { Serial.println("Unknown key in JSON input"); if (result == REQUEST_NOTHING) { return REQUEST_INVALID; } } } return result; }
// Copyright (c) 2003 David Muse // See the file COPYING for more information #include <rudiments/serviceentry.h> #include <rudiments/charstring.h> #include <rudiments/stdio.h> #include "test.cpp" int main(int argc, const char **argv) { // uninitialized serviceentry se; stdoutput.printf("uninitialized:\n"); test("name",!se.getName()); test("port",se.getPort()==-1); test("protcol",!se.getProtocol()); test("alias list",!se.getAliasList()); stdoutput.printf("\n"); // get the service information for "smtp","tcp" stdoutput.printf("smtp/tcp:\n"); se.initialize("smtp","tcp"); test("name",!charstring::compare(se.getName(),"smtp")); test("port",se.getPort()==25); test("protcol",!charstring::compare(se.getProtocol(),"tcp")); // some platforms alias smtp as mail, but some do not test("alias list",!se.getAliasList() || (se.getAliasList() && !charstring::compare(se.getAliasList()[0],"mail"))); stdoutput.printf("\n"); // get the service information for the service on port 25, "tcp" stdoutput.printf("25/tcp:\n"); se.initialize(25,"tcp"); test("name",!charstring::compare(se.getName(),"smtp")); test("port",se.getPort()==25); test("protcol",!charstring::compare(se.getProtocol(),"tcp")); // some platforms alias smtp as mail, but some do not test("alias list",!se.getAliasList() || (se.getAliasList() && !charstring::compare(se.getAliasList()[0],"mail"))); stdoutput.printf("\n"); // null-safety se.initialize((const char *)NULL,NULL); stdoutput.printf("NULL/NULL:\n"); test("name",!se.getName()); test("port",se.getPort()==-1); test("protcol",!se.getProtocol()); test("alias list",!se.getAliasList()); stdoutput.printf("\n"); }
// Copyright 2020 Sapphire development team. All Rights Reserved. namespace Sa { constexpr char8 operator""_c8(unsigned long long int _lit) noexcept { return static_cast<char8>(_lit); } constexpr char16 operator""_c16(unsigned long long int _lit) noexcept { return static_cast<char16>(_lit); } constexpr char32 operator""_c32(unsigned long long int _lit) noexcept { return static_cast<char32>(_lit); } }
//=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =// // // 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 // //===----------------------------------------------------------------------===// /// /// \file /// This file lowers exception-related instructions and setjmp/longjmp /// function calls in order to use Emscripten's JavaScript try and catch /// mechanism. /// /// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's /// try and catch syntax and relevant exception-related libraries implemented /// in JavaScript glue code that will be produced by Emscripten. This is similar /// to the current Emscripten asm.js exception handling in fastcomp. For /// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch: /// (Location: https://github.com/kripken/emscripten-fastcomp) /// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp /// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp /// lib/Target/JSBackend/JSBackend.cpp /// lib/Target/JSBackend/CallHandlers.h /// /// * Exception handling /// This pass lowers invokes and landingpads into library functions in JS glue /// code. Invokes are lowered into function wrappers called invoke wrappers that /// exist in JS side, which wraps the original function call with JS try-catch. /// If an exception occurred, cxa_throw() function in JS side sets some /// variables (see below) so we can check whether an exception occurred from /// wasm code and handle it appropriately. /// /// * Setjmp-longjmp handling /// This pass lowers setjmp to a reasonably-performant approach for emscripten. /// The idea is that each block with a setjmp is broken up into two parts: the /// part containing setjmp and the part right after the setjmp. The latter part /// is either reached from the setjmp, or later from a longjmp. To handle the /// longjmp, all calls that might longjmp are also called using invoke wrappers /// and thus JS / try-catch. JS longjmp() function also sets some variables so /// we can check / whether a longjmp occurred from wasm code. Each block with a /// function call that might longjmp is also split up after the longjmp call. /// After the longjmp call, we check whether a longjmp occurred, and if it did, /// which setjmp it corresponds to, and jump to the right post-setjmp block. /// We assume setjmp-longjmp handling always run after EH handling, which means /// we don't expect any exception-related instructions when SjLj runs. /// FIXME Currently this scheme does not support indirect call of setjmp, /// because of the limitation of the scheme itself. fastcomp does not support it /// either. /// /// In detail, this pass does following things: /// /// 1) Assumes the existence of global variables: __THREW__, __threwValue /// __THREW__ and __threwValue will be set in invoke wrappers /// in JS glue code. For what invoke wrappers are, refer to 3). These /// variables are used for both exceptions and setjmp/longjmps. /// __THREW__ indicates whether an exception or a longjmp occurred or not. 0 /// means nothing occurred, 1 means an exception occurred, and other numbers /// mean a longjmp occurred. In the case of longjmp, __threwValue variable /// indicates the corresponding setjmp buffer the longjmp corresponds to. /// /// * Exception handling /// /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions /// at link time. /// The global variables in 1) will exist in wasm address space, /// but their values should be set in JS code, so these functions /// as interfaces to JS glue code. These functions are equivalent to the /// following JS functions, which actually exist in asm.js version of JS /// library. /// /// function setThrew(threw, value) { /// if (__THREW__ == 0) { /// __THREW__ = threw; /// __threwValue = value; /// } /// } // /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. /// /// In exception handling, getTempRet0 indicates the type of an exception /// caught, and in setjmp/longjmp, it means the second argument to longjmp /// function. /// /// 3) Lower /// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad /// into /// __THREW__ = 0; /// call @__invoke_SIG(func, arg1, arg2) /// %__THREW__.val = __THREW__; /// __THREW__ = 0; /// if (%__THREW__.val == 1) /// goto %lpad /// else /// goto %invoke.cont /// SIG is a mangled string generated based on the LLVM IR-level function /// signature. After LLVM IR types are lowered to the target wasm types, /// the names for these wrappers will change based on wasm types as well, /// as in invoke_vi (function takes an int and returns void). The bodies of /// these wrappers will be generated in JS glue code, and inside those /// wrappers we use JS try-catch to generate actual exception effects. It /// also calls the original callee function. An example wrapper in JS code /// would look like this: /// function invoke_vi(index,a1) { /// try { /// Module["dynCall_vi"](index,a1); // This calls original callee /// } catch(e) { /// if (typeof e !== 'number' && e !== 'longjmp') throw e; /// asm["setThrew"](1, 0); // setThrew is called here /// } /// } /// If an exception is thrown, __THREW__ will be set to true in a wrapper, /// so we can jump to the right BB based on this value. /// /// 4) Lower /// %val = landingpad catch c1 catch c2 catch c3 ... /// ... use %val ... /// into /// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...) /// %val = {%fmc, getTempRet0()} /// ... use %val ... /// Here N is a number calculated based on the number of clauses. /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. /// /// 5) Lower /// resume {%a, %b} /// into /// call @__resumeException(%a) /// where __resumeException() is a function in JS glue code. /// /// 6) Lower /// call @llvm.eh.typeid.for(type) (intrinsic) /// into /// call @llvm_eh_typeid_for(type) /// llvm_eh_typeid_for function will be generated in JS glue code. /// /// * Setjmp / Longjmp handling /// /// In case calls to longjmp() exists /// /// 1) Lower /// longjmp(buf, value) /// into /// emscripten_longjmp(buf, value) /// /// In case calls to setjmp() exists /// /// 2) In the function entry that calls setjmp, initialize setjmpTable and /// sejmpTableSize as follows: /// setjmpTableSize = 4; /// setjmpTable = (int *) malloc(40); /// setjmpTable[0] = 0; /// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS /// code. /// /// 3) Lower /// setjmp(buf) /// into /// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize); /// setjmpTableSize = getTempRet0(); /// For each dynamic setjmp call, setjmpTable stores its ID (a number which /// is incrementally assigned from 0) and its label (a unique number that /// represents each callsite of setjmp). When we need more entries in /// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will /// return the new table address, and assign the new table size in /// setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer /// buf. A BB with setjmp is split into two after setjmp call in order to /// make the post-setjmp BB the possible destination of longjmp BB. /// /// /// 4) Lower every call that might longjmp into /// __THREW__ = 0; /// call @__invoke_SIG(func, arg1, arg2) /// %__THREW__.val = __THREW__; /// __THREW__ = 0; /// if (%__THREW__.val != 0 & __threwValue != 0) { /// %label = testSetjmp(mem[%__THREW__.val], setjmpTable, /// setjmpTableSize); /// if (%label == 0) /// emscripten_longjmp(%__THREW__.val, __threwValue); /// setTempRet0(__threwValue); /// } else { /// %label = -1; /// } /// longjmp_result = getTempRet0(); /// switch label { /// label 1: goto post-setjmp BB 1 /// label 2: goto post-setjmp BB 2 /// ... /// default: goto splitted next BB /// } /// testSetjmp examines setjmpTable to see if there is a matching setjmp /// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__ /// will be the address of matching jmp_buf buffer and __threwValue be the /// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is /// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to /// each setjmp callsite. Label 0 means this longjmp buffer does not /// correspond to one of the setjmp callsites in this function, so in this /// case we just chain the longjmp to the caller. Label -1 means no longjmp /// occurred. Otherwise we jump to the right post-setjmp BB based on the /// label. /// ///===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "WebAssemblyTargetMachine.h" #include "llvm/ADT/StringExtras.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/CommandLine.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/SSAUpdater.h" using namespace llvm; #define DEBUG_TYPE "wasm-lower-em-ehsjlj" static cl::list<std::string> EHAllowlist("emscripten-cxx-exceptions-allowed", cl::desc("The list of function names in which Emscripten-style " "exception handling is enabled (see emscripten " "EMSCRIPTEN_CATCHING_ALLOWED options)"), cl::CommaSeparated); namespace { class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass { bool EnableEH; // Enable exception handling bool EnableSjLj; // Enable setjmp/longjmp handling GlobalVariable *ThrewGV = nullptr; GlobalVariable *ThrewValueGV = nullptr; Function *GetTempRet0Func = nullptr; Function *SetTempRet0Func = nullptr; Function *ResumeF = nullptr; Function *EHTypeIDF = nullptr; Function *EmLongjmpF = nullptr; Function *SaveSetjmpF = nullptr; Function *TestSetjmpF = nullptr; // __cxa_find_matching_catch_N functions. // Indexed by the number of clauses in an original landingpad instruction. DenseMap<int, Function *> FindMatchingCatches; // Map of <function signature string, invoke_ wrappers> StringMap<Function *> InvokeWrappers; // Set of allowed function names for exception handling std::set<std::string> EHAllowlistSet; StringRef getPassName() const override { return "WebAssembly Lower Emscripten Exceptions"; } bool runEHOnFunction(Function &F); bool runSjLjOnFunction(Function &F); Function *getFindMatchingCatch(Module &M, unsigned NumClauses); Value *wrapInvoke(CallBase *CI); void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult, BasicBlock *&EndBB); Function *getInvokeWrapper(CallBase *CI); bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); } bool canLongjmp(Module &M, const Value *Callee) const; bool isEmAsmCall(Module &M, const Value *Callee) const; void rebuildSSA(Function &F); public: static char ID; WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true) : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) { EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end()); } bool runOnModule(Module &M) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); } }; } // End anonymous namespace char WebAssemblyLowerEmscriptenEHSjLj::ID = 0; INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", false, false) ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH, bool EnableSjLj) { return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj); } static bool canThrow(const Value *V) { if (const auto *F = dyn_cast<const Function>(V)) { // Intrinsics cannot throw if (F->isIntrinsic()) return false; StringRef Name = F->getName(); // leave setjmp and longjmp (mostly) alone, we process them properly later if (Name == "setjmp" || Name == "longjmp") return false; return !F->doesNotThrow(); } // not a function, so an indirect call - can throw, we can't tell return true; } // Get a global variable with the given name. If it doesn't exist declare it, // which will generate an import and asssumes that it will exist at link time. static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB, WebAssemblyTargetMachine &TM, const char *Name) { auto Int32Ty = IRB.getInt32Ty(); auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Int32Ty)); if (!GV) report_fatal_error(Twine("unable to create global: ") + Name); // If the target supports TLS, make this variable thread-local. We can't just // unconditionally make it thread-local and depend on // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has // the side effect of disallowing the object from being linked into a // shared-memory module, which we don't want to be responsible for. auto *Subtarget = TM.getSubtargetImpl(); auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory() ? GlobalValue::LocalExecTLSModel : GlobalValue::NotThreadLocal; GV->setThreadLocalMode(TLS); return GV; } // Simple function name mangler. // This function simply takes LLVM's string representation of parameter types // and concatenate them with '_'. There are non-alphanumeric characters but llc // is ok with it, and we need to postprocess these names after the lowering // phase anyway. static std::string getSignature(FunctionType *FTy) { std::string Sig; raw_string_ostream OS(Sig); OS << *FTy->getReturnType(); for (Type *ParamTy : FTy->params()) OS << "_" << *ParamTy; if (FTy->isVarArg()) OS << "_..."; Sig = OS.str(); erase_if(Sig, isSpace); // When s2wasm parses .s file, a comma means the end of an argument. So a // mangled function name can contain any character but a comma. std::replace(Sig.begin(), Sig.end(), ',', '.'); return Sig; } static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name, Module *M) { Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M); // Tell the linker that this function is expected to be imported from the // 'env' module. if (!F->hasFnAttribute("wasm-import-module")) { llvm::AttrBuilder B; B.addAttribute("wasm-import-module", "env"); F->addAttributes(llvm::AttributeList::FunctionIndex, B); } if (!F->hasFnAttribute("wasm-import-name")) { llvm::AttrBuilder B; B.addAttribute("wasm-import-name", F->getName()); F->addAttributes(llvm::AttributeList::FunctionIndex, B); } return F; } // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2. // This is because a landingpad instruction contains two more arguments, a // personality function and a cleanup bit, and __cxa_find_matching_catch_N // functions are named after the number of arguments in the original landingpad // instruction. Function * WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M, unsigned NumClauses) { if (FindMatchingCatches.count(NumClauses)) return FindMatchingCatches[NumClauses]; PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext()); SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy); FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false); Function *F = getEmscriptenFunction( FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M); FindMatchingCatches[NumClauses] = F; return F; } // Generate invoke wrapper seqence with preamble and postamble // Preamble: // __THREW__ = 0; // Postamble: // %__THREW__.val = __THREW__; __THREW__ = 0; // Returns %__THREW__.val, which indicates whether an exception is thrown (or // whether longjmp occurred), for future use. Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) { LLVMContext &C = CI->getModule()->getContext(); // If we are calling a function that is noreturn, we must remove that // attribute. The code we insert here does expect it to return, after we // catch the exception. if (CI->doesNotReturn()) { if (auto *F = CI->getCalledFunction()) F->removeFnAttr(Attribute::NoReturn); CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn); } IRBuilder<> IRB(C); IRB.SetInsertPoint(CI); // Pre-invoke // __THREW__ = 0; IRB.CreateStore(IRB.getInt32(0), ThrewGV); // Invoke function wrapper in JavaScript SmallVector<Value *, 16> Args; // Put the pointer to the callee as first argument, so it can be called // within the invoke wrapper later Args.push_back(CI->getCalledOperand()); Args.append(CI->arg_begin(), CI->arg_end()); CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args); NewCall->takeName(CI); NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke); NewCall->setDebugLoc(CI->getDebugLoc()); // Because we added the pointer to the callee as first argument, all // argument attribute indices have to be incremented by one. SmallVector<AttributeSet, 8> ArgAttributes; const AttributeList &InvokeAL = CI->getAttributes(); // No attributes for the callee pointer. ArgAttributes.push_back(AttributeSet()); // Copy the argument attributes from the original for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I) ArgAttributes.push_back(InvokeAL.getParamAttributes(I)); AttrBuilder FnAttrs(InvokeAL.getFnAttributes()); if (FnAttrs.contains(Attribute::AllocSize)) { // The allocsize attribute (if any) referes to parameters by index and needs // to be adjusted. unsigned SizeArg; Optional<unsigned> NEltArg; std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs(); SizeArg += 1; if (NEltArg.hasValue()) NEltArg = NEltArg.getValue() + 1; FnAttrs.addAllocSizeAttr(SizeArg, NEltArg); } // Reconstruct the AttributesList based on the vector we constructed. AttributeList NewCallAL = AttributeList::get(C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttributes(), ArgAttributes); NewCall->setAttributes(NewCallAL); CI->replaceAllUsesWith(NewCall); // Post-invoke // %__THREW__.val = __THREW__; __THREW__ = 0; Value *Threw = IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val"); IRB.CreateStore(IRB.getInt32(0), ThrewGV); return Threw; } // Get matching invoke wrapper based on callee signature Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) { Module *M = CI->getModule(); SmallVector<Type *, 16> ArgTys; FunctionType *CalleeFTy = CI->getFunctionType(); std::string Sig = getSignature(CalleeFTy); if (InvokeWrappers.find(Sig) != InvokeWrappers.end()) return InvokeWrappers[Sig]; // Put the pointer to the callee as first argument ArgTys.push_back(PointerType::getUnqual(CalleeFTy)); // Add argument types ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end()); FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys, CalleeFTy->isVarArg()); Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M); InvokeWrappers[Sig] = F; return F; } bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M, const Value *Callee) const { if (auto *CalleeF = dyn_cast<Function>(Callee)) if (CalleeF->isIntrinsic()) return false; // Attempting to transform inline assembly will result in something like: // call void @__invoke_void(void ()* asm ...) // which is invalid because inline assembly blocks do not have addresses // and can't be passed by pointer. The result is a crash with illegal IR. if (isa<InlineAsm>(Callee)) return false; StringRef CalleeName = Callee->getName(); // The reason we include malloc/free here is to exclude the malloc/free // calls generated in setjmp prep / cleanup routines. if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free") return false; // There are functions in JS glue code if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" || CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" || CalleeName == "getTempRet0" || CalleeName == "setTempRet0") return false; // __cxa_find_matching_catch_N functions cannot longjmp if (Callee->getName().startswith("__cxa_find_matching_catch_")) return false; // Exception-catching related functions if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" || CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" || CalleeName == "__clang_call_terminate") return false; // Otherwise we don't know return true; } bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M, const Value *Callee) const { StringRef CalleeName = Callee->getName(); // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>. return CalleeName == "emscripten_asm_const_int" || CalleeName == "emscripten_asm_const_double" || CalleeName == "emscripten_asm_const_int_sync_on_main_thread" || CalleeName == "emscripten_asm_const_double_sync_on_main_thread" || CalleeName == "emscripten_asm_const_async_on_main_thread"; } // Generate testSetjmp function call seqence with preamble and postamble. // The code this generates is equivalent to the following JavaScript code: // if (%__THREW__.val != 0 & threwValue != 0) { // %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize); // if (%label == 0) // emscripten_longjmp(%__THREW__.val, threwValue); // setTempRet0(threwValue); // } else { // %label = -1; // } // %longjmp_result = getTempRet0(); // // As output parameters. returns %label, %longjmp_result, and the BB the last // instruction (%longjmp_result = ...) is in. void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp( BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult, BasicBlock *&EndBB) { Function *F = BB->getParent(); LLVMContext &C = BB->getModule()->getContext(); IRBuilder<> IRB(C); IRB.SetCurrentDebugLocation(DL); // if (%__THREW__.val != 0 & threwValue != 0) IRB.SetInsertPoint(BB); BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F); BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F); BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F); Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0)); Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV, ThrewValueGV->getName() + ".val"); Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0)); Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1"); IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1); // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize); // if (%label == 0) IRB.SetInsertPoint(ThenBB1); BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F); BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F); Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C), Threw->getName() + ".i32p"); Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt, ThrewInt->getName() + ".loaded"); Value *ThenLabel = IRB.CreateCall( TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label"); Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0)); IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2); // emscripten_longjmp(%__THREW__.val, threwValue); IRB.SetInsertPoint(ThenBB2); IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue}); IRB.CreateUnreachable(); // setTempRet0(threwValue); IRB.SetInsertPoint(EndBB2); IRB.CreateCall(SetTempRet0Func, ThrewValue); IRB.CreateBr(EndBB1); IRB.SetInsertPoint(ElseBB1); IRB.CreateBr(EndBB1); // longjmp_result = getTempRet0(); IRB.SetInsertPoint(EndBB1); PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label"); LabelPHI->addIncoming(ThenLabel, EndBB2); LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1); // Output parameter assignment Label = LabelPHI; EndBB = EndBB1; LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result"); } void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) { DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); DT.recalculate(F); // CFG has been changed SSAUpdater SSA; for (BasicBlock &BB : F) { for (Instruction &I : BB) { SSA.Initialize(I.getType(), I.getName()); SSA.AddAvailableValue(&BB, &I); for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) { Use &U = *UI; ++UI; auto *User = cast<Instruction>(U.getUser()); if (auto *UserPN = dyn_cast<PHINode>(User)) if (UserPN->getIncomingBlock(U) == &BB) continue; if (DT.dominates(&I, User)) continue; SSA.RewriteUseAfterInsertions(U); } } } } // Replace uses of longjmp with emscripten_longjmp. emscripten_longjmp takes // arguments of type {i32, i32} and longjmp takes {jmp_buf*, i32}, so we need a // ptrtoint instruction here to make the type match. jmp_buf* will eventually be // lowered to i32 in the wasm backend. static void replaceLongjmpWithEmscriptenLongjmp(Function *LongjmpF, Function *EmLongjmpF) { SmallVector<CallInst *, 8> ToErase; LLVMContext &C = LongjmpF->getParent()->getContext(); IRBuilder<> IRB(C); // For calls to longjmp, replace it with emscripten_longjmp and cast its first // argument (jmp_buf*) to int for (User *U : LongjmpF->users()) { auto *CI = dyn_cast<CallInst>(U); if (CI && CI->getCalledFunction() == LongjmpF) { IRB.SetInsertPoint(CI); Value *Jmpbuf = IRB.CreatePtrToInt(CI->getArgOperand(0), IRB.getInt32Ty(), "jmpbuf"); IRB.CreateCall(EmLongjmpF, {Jmpbuf, CI->getArgOperand(1)}); ToErase.push_back(CI); } } for (auto *I : ToErase) I->eraseFromParent(); // If we have any remaining uses of longjmp's function pointer, replace it // with (int(*)(jmp_buf*, int))emscripten_longjmp. if (!LongjmpF->uses().empty()) { Value *EmLongjmp = IRB.CreateBitCast(EmLongjmpF, LongjmpF->getType(), "em_longjmp"); LongjmpF->replaceAllUsesWith(EmLongjmp); } } bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) { LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n"); LLVMContext &C = M.getContext(); IRBuilder<> IRB(C); Function *SetjmpF = M.getFunction("setjmp"); Function *LongjmpF = M.getFunction("longjmp"); bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty(); bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty(); bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed); if ((EnableEH || DoSjLj) && Triple(M.getTargetTriple()).getArch() == Triple::wasm64) report_fatal_error("Emscripten EH/SjLj is not supported with wasm64 yet"); auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); assert(TPC && "Expected a TargetPassConfig"); auto &TM = TPC->getTM<WebAssemblyTargetMachine>(); // Declare (or get) global variables __THREW__, __threwValue, and // getTempRet0/setTempRet0 function which are used in common for both // exception handling and setjmp/longjmp handling ThrewGV = getGlobalVariableI32(M, IRB, TM, "__THREW__"); ThrewValueGV = getGlobalVariableI32(M, IRB, TM, "__threwValue"); GetTempRet0Func = getEmscriptenFunction( FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M); SetTempRet0Func = getEmscriptenFunction( FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false), "setTempRet0", &M); GetTempRet0Func->setDoesNotThrow(); SetTempRet0Func->setDoesNotThrow(); bool Changed = false; // Exception handling if (EnableEH) { // Register __resumeException function FunctionType *ResumeFTy = FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false); ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M); // Register llvm_eh_typeid_for function FunctionType *EHTypeIDTy = FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false); EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M); for (Function &F : M) { if (F.isDeclaration()) continue; Changed |= runEHOnFunction(F); } } // Setjmp/longjmp handling if (DoSjLj) { Changed = true; // We have setjmp or longjmp somewhere // Register emscripten_longjmp function FunctionType *FTy = FunctionType::get( IRB.getVoidTy(), {IRB.getInt32Ty(), IRB.getInt32Ty()}, false); EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M); if (LongjmpF) replaceLongjmpWithEmscriptenLongjmp(LongjmpF, EmLongjmpF); if (SetjmpF) { // Register saveSetjmp function FunctionType *SetjmpFTy = SetjmpF->getFunctionType(); FTy = FunctionType::get(Type::getInt32PtrTy(C), {SetjmpFTy->getParamType(0), IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, false); SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M); // Register testSetjmp function FTy = FunctionType::get( IRB.getInt32Ty(), {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}, false); TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M); // Only traverse functions that uses setjmp in order not to insert // unnecessary prep / cleanup code in every function SmallPtrSet<Function *, 8> SetjmpUsers; for (User *U : SetjmpF->users()) { auto *UI = cast<Instruction>(U); SetjmpUsers.insert(UI->getFunction()); } for (Function *F : SetjmpUsers) runSjLjOnFunction(*F); } } if (!Changed) { // Delete unused global variables and functions if (ResumeF) ResumeF->eraseFromParent(); if (EHTypeIDF) EHTypeIDF->eraseFromParent(); if (EmLongjmpF) EmLongjmpF->eraseFromParent(); if (SaveSetjmpF) SaveSetjmpF->eraseFromParent(); if (TestSetjmpF) TestSetjmpF->eraseFromParent(); return false; } return true; } bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) { Module &M = *F.getParent(); LLVMContext &C = F.getContext(); IRBuilder<> IRB(C); bool Changed = false; SmallVector<Instruction *, 64> ToErase; SmallPtrSet<LandingPadInst *, 32> LandingPads; bool AllowExceptions = areAllExceptionsAllowed() || EHAllowlistSet.count(std::string(F.getName())); for (BasicBlock &BB : F) { auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); if (!II) continue; Changed = true; LandingPads.insert(II->getLandingPadInst()); IRB.SetInsertPoint(II); bool NeedInvoke = AllowExceptions && canThrow(II->getCalledOperand()); if (NeedInvoke) { // Wrap invoke with invoke wrapper and generate preamble/postamble Value *Threw = wrapInvoke(II); ToErase.push_back(II); // Insert a branch based on __THREW__ variable Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp"); IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest()); } else { // This can't throw, and we don't need this invoke, just replace it with a // call+branch SmallVector<Value *, 16> Args(II->args()); CallInst *NewCall = IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args); NewCall->takeName(II); NewCall->setCallingConv(II->getCallingConv()); NewCall->setDebugLoc(II->getDebugLoc()); NewCall->setAttributes(II->getAttributes()); II->replaceAllUsesWith(NewCall); ToErase.push_back(II); IRB.CreateBr(II->getNormalDest()); // Remove any PHI node entries from the exception destination II->getUnwindDest()->removePredecessor(&BB); } } // Process resume instructions for (BasicBlock &BB : F) { // Scan the body of the basic block for resumes for (Instruction &I : BB) { auto *RI = dyn_cast<ResumeInst>(&I); if (!RI) continue; Changed = true; // Split the input into legal values Value *Input = RI->getValue(); IRB.SetInsertPoint(RI); Value *Low = IRB.CreateExtractValue(Input, 0, "low"); // Create a call to __resumeException function IRB.CreateCall(ResumeF, {Low}); // Add a terminator to the block IRB.CreateUnreachable(); ToErase.push_back(RI); } } // Process llvm.eh.typeid.for intrinsics for (BasicBlock &BB : F) { for (Instruction &I : BB) { auto *CI = dyn_cast<CallInst>(&I); if (!CI) continue; const Function *Callee = CI->getCalledFunction(); if (!Callee) continue; if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for) continue; Changed = true; IRB.SetInsertPoint(CI); CallInst *NewCI = IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid"); CI->replaceAllUsesWith(NewCI); ToErase.push_back(CI); } } // Look for orphan landingpads, can occur in blocks with no predecessors for (BasicBlock &BB : F) { Instruction *I = BB.getFirstNonPHI(); if (auto *LPI = dyn_cast<LandingPadInst>(I)) LandingPads.insert(LPI); } Changed |= !LandingPads.empty(); // Handle all the landingpad for this function together, as multiple invokes // may share a single lp for (LandingPadInst *LPI : LandingPads) { IRB.SetInsertPoint(LPI); SmallVector<Value *, 16> FMCArgs; for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) { Constant *Clause = LPI->getClause(I); // TODO Handle filters (= exception specifications). // https://bugs.llvm.org/show_bug.cgi?id=50396 if (LPI->isCatch(I)) FMCArgs.push_back(Clause); } // Create a call to __cxa_find_matching_catch_N function Function *FMCF = getFindMatchingCatch(M, FMCArgs.size()); CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc"); Value *Undef = UndefValue::get(LPI->getType()); Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0"); Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0"); Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1"); LPI->replaceAllUsesWith(Pair1); ToErase.push_back(LPI); } // Erase everything we no longer need in this function for (Instruction *I : ToErase) I->eraseFromParent(); return Changed; } // This tries to get debug info from the instruction before which a new // instruction will be inserted, and if there's no debug info in that // instruction, tries to get the info instead from the previous instruction (if // any). If none of these has debug info and a DISubprogram is provided, it // creates a dummy debug info with the first line of the function, because IR // verifier requires all inlinable callsites should have debug info when both a // caller and callee have DISubprogram. If none of these conditions are met, // returns empty info. static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore, DISubprogram *SP) { assert(InsertBefore); if (InsertBefore->getDebugLoc()) return InsertBefore->getDebugLoc(); const Instruction *Prev = InsertBefore->getPrevNode(); if (Prev && Prev->getDebugLoc()) return Prev->getDebugLoc(); if (SP) return DILocation::get(SP->getContext(), SP->getLine(), 1, SP); return DebugLoc(); } bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) { Module &M = *F.getParent(); LLVMContext &C = F.getContext(); IRBuilder<> IRB(C); SmallVector<Instruction *, 64> ToErase; // Vector of %setjmpTable values std::vector<Instruction *> SetjmpTableInsts; // Vector of %setjmpTableSize values std::vector<Instruction *> SetjmpTableSizeInsts; // Setjmp preparation // This instruction effectively means %setjmpTableSize = 4. // We create this as an instruction intentionally, and we don't want to fold // this instruction to a constant 4, because this value will be used in // SSAUpdater.AddAvailableValue(...) later. BasicBlock &EntryBB = F.getEntryBlock(); DebugLoc FirstDL = getOrCreateDebugLoc(&*EntryBB.begin(), F.getSubprogram()); BinaryOperator *SetjmpTableSize = BinaryOperator::Create( Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize", &*EntryBB.getFirstInsertionPt()); SetjmpTableSize->setDebugLoc(FirstDL); // setjmpTable = (int *) malloc(40); Instruction *SetjmpTable = CallInst::CreateMalloc( SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40), nullptr, nullptr, "setjmpTable"); SetjmpTable->setDebugLoc(FirstDL); // CallInst::CreateMalloc may return a bitcast instruction if the result types // mismatch. We need to set the debug loc for the original call too. auto *MallocCall = SetjmpTable->stripPointerCasts(); if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) { MallocCallI->setDebugLoc(FirstDL); } // setjmpTable[0] = 0; IRB.SetInsertPoint(SetjmpTableSize); IRB.CreateStore(IRB.getInt32(0), SetjmpTable); SetjmpTableInsts.push_back(SetjmpTable); SetjmpTableSizeInsts.push_back(SetjmpTableSize); // Setjmp transformation std::vector<PHINode *> SetjmpRetPHIs; Function *SetjmpF = M.getFunction("setjmp"); for (User *U : SetjmpF->users()) { auto *CI = dyn_cast<CallInst>(U); if (!CI) report_fatal_error("Does not support indirect calls to setjmp"); BasicBlock *BB = CI->getParent(); if (BB->getParent() != &F) // in other function continue; // The tail is everything right after the call, and will be reached once // when setjmp is called, and later when longjmp returns to the setjmp BasicBlock *Tail = SplitBlock(BB, CI->getNextNode()); // Add a phi to the tail, which will be the output of setjmp, which // indicates if this is the first call or a longjmp back. The phi directly // uses the right value based on where we arrive from IRB.SetInsertPoint(Tail->getFirstNonPHI()); PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret"); // setjmp initial call returns 0 SetjmpRet->addIncoming(IRB.getInt32(0), BB); // The proper output is now this, not the setjmp call itself CI->replaceAllUsesWith(SetjmpRet); // longjmp returns to the setjmp will add themselves to this phi SetjmpRetPHIs.push_back(SetjmpRet); // Fix call target // Our index in the function is our place in the array + 1 to avoid index // 0, because index 0 means the longjmp is not ours to handle. IRB.SetInsertPoint(CI); Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()), SetjmpTable, SetjmpTableSize}; Instruction *NewSetjmpTable = IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable"); Instruction *NewSetjmpTableSize = IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize"); SetjmpTableInsts.push_back(NewSetjmpTable); SetjmpTableSizeInsts.push_back(NewSetjmpTableSize); ToErase.push_back(CI); } // Update each call that can longjmp so it can return to a setjmp where // relevant. // Because we are creating new BBs while processing and don't want to make // all these newly created BBs candidates again for longjmp processing, we // first make the vector of candidate BBs. std::vector<BasicBlock *> BBs; for (BasicBlock &BB : F) BBs.push_back(&BB); // BBs.size() will change within the loop, so we query it every time for (unsigned I = 0; I < BBs.size(); I++) { BasicBlock *BB = BBs[I]; for (Instruction &I : *BB) { assert(!isa<InvokeInst>(&I)); auto *CI = dyn_cast<CallInst>(&I); if (!CI) continue; const Value *Callee = CI->getCalledOperand(); if (!canLongjmp(M, Callee)) continue; if (isEmAsmCall(M, Callee)) report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " + F.getName() + ". Please consider using EM_JS, or move the " "EM_ASM into another function.", false); Value *Threw = nullptr; BasicBlock *Tail; if (Callee->getName().startswith("__invoke_")) { // If invoke wrapper has already been generated for this call in // previous EH phase, search for the load instruction // %__THREW__.val = __THREW__; // in postamble after the invoke wrapper call LoadInst *ThrewLI = nullptr; StoreInst *ThrewResetSI = nullptr; for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end(); I != IE; ++I) { if (auto *LI = dyn_cast<LoadInst>(I)) if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) if (GV == ThrewGV) { Threw = ThrewLI = LI; break; } } // Search for the store instruction after the load above // __THREW__ = 0; for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end(); I != IE; ++I) { if (auto *SI = dyn_cast<StoreInst>(I)) if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) { ThrewResetSI = SI; break; } } assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke"); assert(ThrewResetSI && "Cannot find __THREW__ store after invoke"); Tail = SplitBlock(BB, ThrewResetSI->getNextNode()); } else { // Wrap call with invoke wrapper and generate preamble/postamble Threw = wrapInvoke(CI); ToErase.push_back(CI); Tail = SplitBlock(BB, CI->getNextNode()); } // We need to replace the terminator in Tail - SplitBlock makes BB go // straight to Tail, we need to check if a longjmp occurred, and go to the // right setjmp-tail if so ToErase.push_back(BB->getTerminator()); // Generate a function call to testSetjmp function and preamble/postamble // code to figure out (1) whether longjmp occurred (2) if longjmp // occurred, which setjmp it corresponds to Value *Label = nullptr; Value *LongjmpResult = nullptr; BasicBlock *EndBB = nullptr; wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize, Label, LongjmpResult, EndBB); assert(Label && LongjmpResult && EndBB); // Create switch instruction IRB.SetInsertPoint(EndBB); IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc()); SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size()); // -1 means no longjmp happened, continue normally (will hit the default // switch case). 0 means a longjmp that is not ours to handle, needs a // rethrow. Otherwise the index is the same as the index in P+1 (to avoid // 0). for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) { SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent()); SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB); } // We are splitting the block here, and must continue to find other calls // in the block - which is now split. so continue to traverse in the Tail BBs.push_back(Tail); } } // Erase everything we no longer need in this function for (Instruction *I : ToErase) I->eraseFromParent(); // Free setjmpTable buffer before each return instruction for (BasicBlock &BB : F) { Instruction *TI = BB.getTerminator(); if (isa<ReturnInst>(TI)) { DebugLoc DL = getOrCreateDebugLoc(TI, F.getSubprogram()); auto *Free = CallInst::CreateFree(SetjmpTable, TI); Free->setDebugLoc(DL); // CallInst::CreateFree may create a bitcast instruction if its argument // types mismatch. We need to set the debug loc for the bitcast too. if (auto *FreeCallI = dyn_cast<CallInst>(Free)) { if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0))) BitCastI->setDebugLoc(DL); } } } // Every call to saveSetjmp can change setjmpTable and setjmpTableSize // (when buffer reallocation occurs) // entry: // setjmpTableSize = 4; // setjmpTable = (int *) malloc(40); // setjmpTable[0] = 0; // ... // somebb: // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize); // setjmpTableSize = getTempRet0(); // So we need to make sure the SSA for these variables is valid so that every // saveSetjmp and testSetjmp calls have the correct arguments. SSAUpdater SetjmpTableSSA; SSAUpdater SetjmpTableSizeSSA; SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable"); SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize"); for (Instruction *I : SetjmpTableInsts) SetjmpTableSSA.AddAvailableValue(I->getParent(), I); for (Instruction *I : SetjmpTableSizeInsts) SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I); for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end(); UI != UE;) { // Grab the use before incrementing the iterator. Use &U = *UI; // Increment the iterator before removing the use from the list. ++UI; if (auto *I = dyn_cast<Instruction>(U.getUser())) if (I->getParent() != &EntryBB) SetjmpTableSSA.RewriteUse(U); } for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end(); UI != UE;) { Use &U = *UI; ++UI; if (auto *I = dyn_cast<Instruction>(U.getUser())) if (I->getParent() != &EntryBB) SetjmpTableSizeSSA.RewriteUse(U); } // Finally, our modifications to the cfg can break dominance of SSA variables. // For example, in this code, // if (x()) { .. setjmp() .. } // if (y()) { .. longjmp() .. } // We must split the longjmp block, and it can jump into the block splitted // from setjmp one. But that means that when we split the setjmp block, it's // first part no longer dominates its second part - there is a theoretically // possible control flow path where x() is false, then y() is true and we // reach the second part of the setjmp block, without ever reaching the first // part. So, we rebuild SSA form here. rebuildSSA(F); return true; }
// // from http://www.zedwood.com/article/cpp-md5-function // // compile and run in linux: // g++ main.cpp md5.cpp -o md5_sample && ./md5_sample // output: // md5 of 'grape' : b781cbb29054db12f88f08c6e161c199 // md5 of 'gr'+'ape': b781cbb29054db12f88f08c6e161c199 #include <iostream> #include "md5.h" int main(int argc, char *argv[]) { std::cout << "md5 of 'grape' : " << md5("grape") << '\n'; // test2 MD5 m = MD5(); m.update("gr"); m.update("ape"); m.finalize(); std::cout << "md5 of 'gr'+'ape': " << m.hexdigest() << '\n'; return 0; }
// // OpenCLWrapper.hpp // MNN // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef OpenCLWrapper_hpp #define OpenCLWrapper_hpp #if defined(_MSC_VER) #include <Windows.h> #undef min #undef max #undef NO_ERROR #endif #include <memory> #include "core/Macro.h" #define CL_TARGET_OPENCL_VERSION 200 #define CL_HPP_TARGET_OPENCL_VERSION 110 #define CL_HPP_MINIMUM_OPENCL_VERSION 110 // #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Weffc++" // #pragma GCC diagnostic ignored "-Wignored-qualifiers" #include "CL/cl2.hpp" // #pragma GCC diagnostic pop #define MNN_CHECK_NOTNULL(X) MNN_ASSERT(X != NULL) #define MNN_CHECK_CL_SUCCESS(error) \ if (error != CL_SUCCESS) { \ MNN_PRINT("ERROR CODE : %d \n", (int)error); \ } #ifdef MNN_USE_LIB_WRAPPER namespace MNN { void LoadOpenCLSymbols(); void UnLoadOpenCLSymbols(); class OpenCLSymbols { public: bool LoadOpenCLLibrary(); bool UnLoadOpenCLLibrary(); bool isError(); using clGetPlatformIDsFunc = cl_int (CL_API_CALL *)(cl_uint, cl_platform_id *, cl_uint *); using clGetPlatformInfoFunc = cl_int (CL_API_CALL *)(cl_platform_id, cl_platform_info, size_t, void *, size_t *); using clBuildProgramFunc = cl_int (CL_API_CALL *)(cl_program, cl_uint, const cl_device_id *, const char *, void (CL_CALLBACK *pfn_notify)(cl_program, void *), void *); using clEnqueueNDRangeKernelFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_kernel, cl_uint, const size_t *, const size_t *, const size_t *, cl_uint, const cl_event *, cl_event *); using clSetKernelArgFunc = cl_int (CL_API_CALL *)(cl_kernel, cl_uint, size_t, const void *); using clRetainMemObjectFunc = cl_int (CL_API_CALL *)(cl_mem); using clReleaseMemObjectFunc = cl_int (CL_API_CALL *)(cl_mem); using clEnqueueUnmapMemObjectFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, void *, cl_uint, const cl_event *, cl_event *); using clRetainCommandQueueFunc = cl_int (CL_API_CALL *)(cl_command_queue command_queue); using clCreateContextFunc = cl_context (CL_API_CALL *)(const cl_context_properties *, cl_uint, const cl_device_id *, void(CL_CALLBACK *)( // NOLINT(readability/casting) const char *, const void *, size_t, void *), void *, cl_int *); using clEnqueueCopyImageFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); using clCreateContextFromTypeFunc = cl_context (CL_API_CALL *)(const cl_context_properties *, cl_device_type, void(CL_CALLBACK *)( // NOLINT(readability/casting) const char *, const void *, size_t, void *), void *, cl_int *); using clReleaseContextFunc = cl_int (CL_API_CALL *)(cl_context); using clWaitForEventsFunc = cl_int (CL_API_CALL *)(cl_uint, const cl_event *); using clReleaseEventFunc = cl_int (CL_API_CALL *)(cl_event); using clEnqueueWriteBufferFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void *, cl_uint, const cl_event *, cl_event *); using clEnqueueReadBufferFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, const cl_event *, cl_event *); using clEnqueueReadImageFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, const size_t *, const size_t *, size_t, size_t, void *, cl_uint, const cl_event *, cl_event *); using clEnqueueWriteImageFunc = cl_int (CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, const size_t *, const size_t *, size_t, size_t, const void *, cl_uint, const cl_event *, cl_event * ); using clGetProgramBuildInfoFunc = cl_int (CL_API_CALL *)(cl_program, cl_device_id, cl_program_build_info, size_t, void *, size_t *); using clRetainProgramFunc = cl_int (CL_API_CALL *)(cl_program program); using clEnqueueMapBufferFunc = void *(CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event *, cl_event *, cl_int *); using clEnqueueMapImageFunc = void *(CL_API_CALL *)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t *, const size_t *, size_t *, size_t *, cl_uint, const cl_event *, cl_event *, cl_int *); using clCreateCommandQueueFunc = cl_command_queue(CL_API_CALL *)( // NOLINT cl_context, cl_device_id, cl_command_queue_properties, cl_int *); using clReleaseCommandQueueFunc = cl_int (CL_API_CALL *)(cl_command_queue); using clCreateProgramWithBinaryFunc = cl_program (CL_API_CALL *)(cl_context, cl_uint, const cl_device_id *, const size_t *, const unsigned char **, cl_int *, cl_int *); using clRetainContextFunc = cl_int (CL_API_CALL *)(cl_context context); using clGetContextInfoFunc = cl_int (CL_API_CALL *)(cl_context, cl_context_info, size_t, void *, size_t *); using clReleaseProgramFunc = cl_int (CL_API_CALL *)(cl_program program); using clFlushFunc = cl_int (CL_API_CALL *)(cl_command_queue command_queue); using clFinishFunc = cl_int (CL_API_CALL *)(cl_command_queue command_queue); using clGetProgramInfoFunc = cl_int (CL_API_CALL *)(cl_program, cl_program_info, size_t, void *, size_t *); using clCreateKernelFunc = cl_kernel (CL_API_CALL *)(cl_program, const char *, cl_int *); using clRetainKernelFunc = cl_int (CL_API_CALL *)(cl_kernel kernel); using clCreateBufferFunc = cl_mem (CL_API_CALL *)(cl_context, cl_mem_flags, size_t, void *, cl_int *); using clCreateImage2DFunc = cl_mem(CL_API_CALL *)(cl_context, // NOLINT cl_mem_flags, const cl_image_format *, size_t, size_t, size_t, void *, cl_int *); using clCreateImageFunc = cl_mem (CL_API_CALL *)(cl_context, cl_mem_flags, const cl_image_format *, const cl_image_desc *, void *, cl_int *); using clCreateProgramWithSourceFunc = cl_program (CL_API_CALL *)(cl_context, cl_uint, const char **, const size_t *, cl_int *); using clReleaseKernelFunc = cl_int (CL_API_CALL *)(cl_kernel kernel); using clGetDeviceInfoFunc = cl_int (CL_API_CALL *)(cl_device_id, cl_device_info, size_t, void *, size_t *); using clGetDeviceIDsFunc = cl_int (CL_API_CALL *)(cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *); using clRetainDeviceFunc = cl_int (CL_API_CALL *)(cl_device_id); using clReleaseDeviceFunc = cl_int (CL_API_CALL *)(cl_device_id); using clRetainEventFunc = cl_int (CL_API_CALL *)(cl_event); using clGetKernelWorkGroupInfoFunc = cl_int (CL_API_CALL *)(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void *, size_t *); using clGetEventInfoFunc = cl_int (CL_API_CALL *)(cl_event event, cl_event_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret); using clGetEventProfilingInfoFunc = cl_int (CL_API_CALL *)(cl_event event, cl_profiling_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret); using clGetImageInfoFunc = cl_int (CL_API_CALL *)(cl_mem, cl_image_info, size_t, void *, size_t *); #define MNN_CL_DEFINE_FUNC_PTR(func) func##Func func = nullptr MNN_CL_DEFINE_FUNC_PTR(clGetPlatformIDs); MNN_CL_DEFINE_FUNC_PTR(clGetPlatformInfo); MNN_CL_DEFINE_FUNC_PTR(clBuildProgram); MNN_CL_DEFINE_FUNC_PTR(clEnqueueNDRangeKernel); MNN_CL_DEFINE_FUNC_PTR(clSetKernelArg); MNN_CL_DEFINE_FUNC_PTR(clReleaseKernel); MNN_CL_DEFINE_FUNC_PTR(clCreateProgramWithSource); MNN_CL_DEFINE_FUNC_PTR(clCreateBuffer); MNN_CL_DEFINE_FUNC_PTR(clCreateImage); MNN_CL_DEFINE_FUNC_PTR(clCreateImage2D); MNN_CL_DEFINE_FUNC_PTR(clRetainKernel); MNN_CL_DEFINE_FUNC_PTR(clCreateKernel); MNN_CL_DEFINE_FUNC_PTR(clGetProgramInfo); MNN_CL_DEFINE_FUNC_PTR(clFlush); MNN_CL_DEFINE_FUNC_PTR(clFinish); MNN_CL_DEFINE_FUNC_PTR(clReleaseProgram); MNN_CL_DEFINE_FUNC_PTR(clRetainContext); MNN_CL_DEFINE_FUNC_PTR(clGetContextInfo); MNN_CL_DEFINE_FUNC_PTR(clCreateProgramWithBinary); MNN_CL_DEFINE_FUNC_PTR(clCreateCommandQueue); MNN_CL_DEFINE_FUNC_PTR(clReleaseCommandQueue); MNN_CL_DEFINE_FUNC_PTR(clEnqueueMapBuffer); MNN_CL_DEFINE_FUNC_PTR(clEnqueueMapImage); MNN_CL_DEFINE_FUNC_PTR(clEnqueueCopyImage); MNN_CL_DEFINE_FUNC_PTR(clRetainProgram); MNN_CL_DEFINE_FUNC_PTR(clGetProgramBuildInfo); MNN_CL_DEFINE_FUNC_PTR(clEnqueueReadBuffer); MNN_CL_DEFINE_FUNC_PTR(clEnqueueWriteBuffer); MNN_CL_DEFINE_FUNC_PTR(clWaitForEvents); MNN_CL_DEFINE_FUNC_PTR(clReleaseEvent); MNN_CL_DEFINE_FUNC_PTR(clCreateContext); MNN_CL_DEFINE_FUNC_PTR(clCreateContextFromType); MNN_CL_DEFINE_FUNC_PTR(clReleaseContext); MNN_CL_DEFINE_FUNC_PTR(clRetainCommandQueue); MNN_CL_DEFINE_FUNC_PTR(clEnqueueUnmapMemObject); MNN_CL_DEFINE_FUNC_PTR(clRetainMemObject); MNN_CL_DEFINE_FUNC_PTR(clReleaseMemObject); MNN_CL_DEFINE_FUNC_PTR(clGetDeviceInfo); MNN_CL_DEFINE_FUNC_PTR(clGetDeviceIDs); MNN_CL_DEFINE_FUNC_PTR(clRetainDevice); MNN_CL_DEFINE_FUNC_PTR(clReleaseDevice); MNN_CL_DEFINE_FUNC_PTR(clRetainEvent); MNN_CL_DEFINE_FUNC_PTR(clGetKernelWorkGroupInfo); MNN_CL_DEFINE_FUNC_PTR(clGetEventInfo); MNN_CL_DEFINE_FUNC_PTR(clGetEventProfilingInfo); MNN_CL_DEFINE_FUNC_PTR(clGetImageInfo); MNN_CL_DEFINE_FUNC_PTR(clEnqueueReadImage); MNN_CL_DEFINE_FUNC_PTR(clEnqueueWriteImage); #undef MNN_CL_DEFINE_FUNC_PTR private: bool LoadLibraryFromPath(const std::string &path); #if defined(_MSC_VER) HMODULE handle_ = nullptr; #else void *handle_ = nullptr; #endif bool mIsError{false}; }; class OpenCLSymbolsOperator { public: static OpenCLSymbolsOperator *createOpenCLSymbolsOperatorSingleInstance() { static OpenCLSymbolsOperator symbols_operator; return &symbols_operator; } static OpenCLSymbols *getOpenclSymbolsPtr(); private: OpenCLSymbolsOperator(); ~OpenCLSymbolsOperator(); OpenCLSymbolsOperator(const OpenCLSymbolsOperator &) = delete; OpenCLSymbolsOperator &operator=(const OpenCLSymbolsOperator &) = delete; static std::shared_ptr<OpenCLSymbols> gOpenclSymbols; }; } // namespace MNN #endif #endif /* OpenCLWrapper_hpp */
#include "cbase.h" #include "forcefeedback.h" #include "hud_macros.h" #include "input.h" #define FF_CLIENT_FLAG 0x8000 class FFParams { public: FORCEFEEDBACK_t m_nEffectType; FFBaseParams_t m_BaseParams; }; struct FFEffectInfo_t { FORCEFEEDBACK_t effectType; char const *name; }; #define DECLARE_FFEFFECT( name ) { name, #name } static FFEffectInfo_t g_EffectTypes[] = { DECLARE_FFEFFECT( FORCE_FEEDBACK_SHOT_SINGLE ), DECLARE_FFEFFECT( FORCE_FEEDBACK_SHOT_DOUBLE ), DECLARE_FFEFFECT( FORCE_FEEDBACK_TAKEDAMAGE ), DECLARE_FFEFFECT( FORCE_FEEDBACK_SCREENSHAKE ), DECLARE_FFEFFECT( FORCE_FEEDBACK_SKIDDING ), DECLARE_FFEFFECT( FORCE_FEEDBACK_BREAKING ) }; //----------------------------------------------------------------------------- // Purpose: // Input : effect - // Output : char const //----------------------------------------------------------------------------- char const *NameForForceFeedbackEffect( FORCEFEEDBACK_t effect ) { int c = SOURCE_ARRAYSIZE( g_EffectTypes ); if ( (int)effect < 0 || (int)effect >= c ) return "???"; const FFEffectInfo_t& info = g_EffectTypes[ (int)effect ]; Assert( info.effectType == effect ); return info.name; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : FORCEFEEDBACK_t //----------------------------------------------------------------------------- FORCEFEEDBACK_t ForceFeedbackEffectForName( const char *name ) { int c = SOURCE_ARRAYSIZE( g_EffectTypes ); for ( int i = 0 ; i < c; ++i ) { const FFEffectInfo_t& info = g_EffectTypes[ i ]; if ( !Q_stricmp( info.name, name ) ) return info.effectType; } return ( FORCEFEEDBACK_t )-1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CForceFeedback : public IForceFeedback, public CAutoGameSystem { public: virtual bool Init(); virtual void Shutdown(); // API virtual void StopAllEffects( CBasePlayer *player ); virtual void StopEffect( CBasePlayer *player, FORCEFEEDBACK_t effect ); virtual void StartEffect( CBasePlayer *player, FORCEFEEDBACK_t effect, const FFBaseParams_t& params ); virtual void PauseAll( CBasePlayer *player ); virtual void ResumeAll( CBasePlayer *player ); void MsgFunc_ForceFeedback( bf_read &msg ); private: void Internal_StopAllEffects(); void Internal_StopEffect( FORCEFEEDBACK_t effect ); void Internal_StartEffect( FORCEFEEDBACK_t, const FFBaseParams_t& params ); void Internal_PauseAll(); void Internal_ResumeAll(); }; static CForceFeedback g_ForceFeedbackSingleton; IForceFeedback *forcefeedback = &g_ForceFeedbackSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : &msg - //----------------------------------------------------------------------------- void __MsgFunc_ForceFeedback( bf_read &msg ) { g_ForceFeedbackSingleton.MsgFunc_ForceFeedback( msg ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CForceFeedback::Init() { HOOK_MESSAGE( ForceFeedback ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CForceFeedback::Shutdown() { } //----------------------------------------------------------------------------- // Purpose: // Input : *player - //----------------------------------------------------------------------------- void CForceFeedback::StopAllEffects( CBasePlayer *player ) { if ( !player ) return; Internal_StopAllEffects(); } //----------------------------------------------------------------------------- // Purpose: // Input : *player - // effect - //----------------------------------------------------------------------------- void CForceFeedback::StopEffect( CBasePlayer *player, FORCEFEEDBACK_t effect ) { if ( !player ) return; Internal_StopEffect( effect ); } //----------------------------------------------------------------------------- // Purpose: // Input : *player - // effect - // params - //----------------------------------------------------------------------------- void CForceFeedback::StartEffect( CBasePlayer *player, FORCEFEEDBACK_t effect, const FFBaseParams_t& params ) { if ( !player ) { return; } Internal_StartEffect( effect, params ); } //----------------------------------------------------------------------------- // Purpose: // Input : *player - //----------------------------------------------------------------------------- void CForceFeedback::PauseAll( CBasePlayer *player ) { if ( !player ) return; Internal_PauseAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : *player - //----------------------------------------------------------------------------- void CForceFeedback::ResumeAll( CBasePlayer *player ) { if ( !player ) return; Internal_ResumeAll(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CForceFeedback::Internal_StopAllEffects() { input->ForceFeedback_StopAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : heffect - //----------------------------------------------------------------------------- void CForceFeedback::Internal_StopEffect( FORCEFEEDBACK_t effect ) { input->ForceFeedback_Stop( effect ); } //----------------------------------------------------------------------------- // Purpose: // Input : effect - //----------------------------------------------------------------------------- void CForceFeedback::Internal_StartEffect( FORCEFEEDBACK_t effect, const FFBaseParams_t& params) { char const *name = NameForForceFeedbackEffect( effect ); Msg( "Starting FF effect '%s'\n", name ); FFParams p; p.m_nEffectType = effect; p.m_BaseParams = params; input->ForceFeedback_Start( effect, params ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CForceFeedback::Internal_PauseAll() { input->ForceFeedback_Pause(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CForceFeedback::Internal_ResumeAll() { input->ForceFeedback_Resume(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pszName - // iSize - // *pbuf - //----------------------------------------------------------------------------- void CForceFeedback::MsgFunc_ForceFeedback( bf_read &msg ) { byte msgType = msg.ReadByte(); switch ( msgType ) { default: { Warning( "Bad parse in MsgFunc_ForceFeedback!\n" ); } break; case FFMSG_STOPALL: { Internal_StopAllEffects(); } break; case FFMSG_START: { FORCEFEEDBACK_t effectType = (FORCEFEEDBACK_t)msg.ReadByte(); FFBaseParams_t params; params.m_flDirection = 360.0f * ( (byte)msg.ReadByte() / 255.0f ); params.m_flDuration = (float)msg.ReadLong() / 1000.0f; params.m_flGain = ( (byte)msg.ReadByte() / 255.0f ); params.m_nPriority = msg.ReadByte(); params.m_bSolo = msg.ReadByte() == 0 ? false : true; if ( effectType >= 0 && effectType < NUM_FORCE_FEEDBACK_PRESETS ) { Internal_StartEffect( effectType, params ); } else { Warning( "Bad parse in MsgFunc_ForceFeedback, FFMSG_START (%i)!\n", effectType ); } } break; case FFMSG_STOP: { FORCEFEEDBACK_t effectType = (FORCEFEEDBACK_t)msg.ReadByte(); Internal_StopEffect( effectType ); } break; case FFMSG_PAUSE: { Internal_PauseAll(); } break; case FFMSG_RESUME: { Internal_ResumeAll(); } break; } }
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { float result; for(int i=0;i<nums2.size();i++) { nums1.push_back(nums2[i]); } // sort nums1 sort(nums1.begin(),nums1.end()); int len=nums1.size(); if(len%2==0) { result=(float)(nums1[len/2]+nums1[len/2-1])/2; } else { result=(float)nums1[len/2]; } return result; } };
// Copyright (c) 2007-2018 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // Copyright (c) 2011-2017 Thomas Heller // // 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) #if !defined(HPX_RUNTIME_SUPPORT_JUN_02_2008_1145AM) #define HPX_RUNTIME_SUPPORT_JUN_02_2008_1145AM #include <hpx/config.hpp> #include <hpx/compat/condition_variable.hpp> #include <hpx/compat/mutex.hpp> #include <hpx/compat/thread.hpp> #include <hpx/throw_exception.hpp> #include <hpx/lcos/local/condition_variable.hpp> #include <hpx/lcos/local/mutex.hpp> #include <hpx/lcos/local/spinlock.hpp> #include <hpx/performance_counters/counters.hpp> #include <hpx/plugins/plugin_factory_base.hpp> #include <hpx/runtime/actions/component_action.hpp> #include <hpx/runtime/actions/manage_object_action.hpp> #include <hpx/runtime/components/component_type.hpp> #include <hpx/runtime/components/server/create_component.hpp> #include <hpx/runtime/components/static_factory_data.hpp> #include <hpx/runtime/find_here.hpp> #include <hpx/runtime/parcelset/locality.hpp> #include <hpx/traits/action_does_termination_detection.hpp> #include <hpx/traits/is_component.hpp> #include <hpx/util/assert.hpp> #include <hpx/util/plugin.hpp> #include <hpx/util_fwd.hpp> #include <boost/program_options/options_description.hpp> #include <atomic> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include <hpx/config/warnings_prefix.hpp> // Fast termination detection does not work, currently, as the return actions // generated by the futures used by hpx::reduce and hpx::broadcast mark the // sender as black. This causes an infinite loop while waiting for the Dijkstra // termination detection to return. namespace hpx { namespace components { namespace server { /////////////////////////////////////////////////////////////////////////// class runtime_support { private: typedef lcos::local::spinlock plugin_map_mutex_type; struct plugin_factory { plugin_factory( std::shared_ptr<plugins::plugin_factory_base> const& f, hpx::util::plugin::dll const& d, bool enabled) : first(f), second(d), isenabled(enabled) {} std::shared_ptr<plugins::plugin_factory_base> first; hpx::util::plugin::dll const& second; bool isenabled; }; typedef plugin_factory plugin_factory_type; typedef std::map<std::string, plugin_factory_type> plugin_map_type; typedef std::map<std::string, hpx::util::plugin::dll> modules_map_type; typedef std::vector<static_factory_load_data_type> static_modules_type; public: typedef runtime_support type_holder; static component_type get_component_type() { return components::get_component_type<runtime_support>(); } static void set_component_type(component_type t) { components::set_component_type<runtime_support>(t); } // constructor runtime_support(hpx::util::runtime_configuration & cfg); ~runtime_support() { tidy(); } /// \brief finalize() will be called just before the instance gets /// destructed /// /// \param self [in] The HPX \a thread used to execute this function. /// \param appl [in] The applier to be used for finalization of the /// component instance. HPX_CXX14_CONSTEXPR static void finalize() {} void delete_function_lists(); void tidy(); // This component type requires valid locality id for its actions to // be invoked static bool is_target_valid(naming::id_type const& id) { return naming::is_locality(id); } /////////////////////////////////////////////////////////////////////// // exposed functionality of this component /// \brief Actions to create new objects template <typename Component> naming::gid_type create_component(); template <typename Component, typename T, typename ...Ts> naming::gid_type create_component(T v, Ts... vs); template <typename Component> std::vector<naming::gid_type> bulk_create_component(std::size_t count); template <typename Component, typename T, typename ...Ts> std::vector<naming::gid_type> bulk_create_component( std::size_t count, T v, Ts... vs); template <typename Component> naming::gid_type copy_create_component( std::shared_ptr<Component> const& p, bool); template <typename Component> naming::gid_type migrate_component_to_here( std::shared_ptr<Component> const& p, naming::id_type); /// \brief Gracefully shutdown this runtime system instance void shutdown(double timeout, naming::id_type const& respond_to); /// \brief Gracefully shutdown runtime system instances on all localities void shutdown_all(double timeout); /// \brief Shutdown this runtime system instance HPX_NORETURN void terminate( naming::id_type const& respond_to); void terminate_act(naming::id_type const& id) { terminate(id); } /// \brief Shutdown runtime system instances on all localities HPX_NORETURN void terminate_all(); void terminate_all_act() { terminate_all(); } /// \brief Retrieve configuration information util::section get_config(); /// \brief Load all components on this locality. int load_components(); void call_startup_functions(bool pre_startup); void call_shutdown_functions(bool pre_shutdown); /// \brief Force a garbage collection operation in the AGAS layer. void garbage_collect(); /// \brief Create the given performance counter instance. naming::gid_type create_performance_counter( performance_counters::counter_info const& info); /// \brief Remove the given locality from our connection cache void remove_from_connection_cache(naming::gid_type const& gid, parcelset::endpoints_type const& eps); /// \brief termination detection #if defined(HPX_USE_FAST_DIJKSTRA_TERMINATION_DETECTION) bool dijkstra_termination(); #else void dijkstra_termination(std::uint32_t initiating_locality_id, std::uint32_t num_localities, bool dijkstra_token); #endif /////////////////////////////////////////////////////////////////////// // Each of the exposed functions needs to be encapsulated into a action // type, allowing to generate all require boilerplate code for threads, // serialization, etc. HPX_DEFINE_COMPONENT_ACTION(runtime_support, load_components); HPX_DEFINE_COMPONENT_ACTION(runtime_support, call_startup_functions); HPX_DEFINE_COMPONENT_ACTION(runtime_support, call_shutdown_functions); HPX_DEFINE_COMPONENT_ACTION(runtime_support, shutdown); HPX_DEFINE_COMPONENT_ACTION(runtime_support, shutdown_all); HPX_DEFINE_COMPONENT_ACTION(runtime_support, terminate_act, terminate_action); HPX_DEFINE_COMPONENT_ACTION(runtime_support, terminate_all_act, terminate_all_action); // even if this is not a short/minimal action, we still execute it // directly to avoid a deadlock condition inside the thread manager // waiting for this thread to finish, which waits for the thread // manager to exit HPX_DEFINE_COMPONENT_DIRECT_ACTION(runtime_support, get_config); HPX_DEFINE_COMPONENT_ACTION(runtime_support, garbage_collect); HPX_DEFINE_COMPONENT_ACTION(runtime_support, create_performance_counter); HPX_DEFINE_COMPONENT_ACTION(runtime_support, remove_from_connection_cache); HPX_DEFINE_COMPONENT_ACTION(runtime_support, dijkstra_termination); /////////////////////////////////////////////////////////////////////// /// \brief Start the runtime_support component void run(); /// \brief Wait for the runtime_support component to notify the calling /// thread. /// /// This function will be called from the main thread, causing it to /// block while the HPX functionality is executed. The main thread will /// block until the shutdown_action is executed, which in turn notifies /// all waiting threads. void wait(); /// \brief Notify all waiting (blocking) threads allowing the system to /// be properly stopped. /// /// \note This function can be called from any thread. void stop(double timeout, naming::id_type const& respond_to, bool remove_from_remote_caches); /// called locally only void stopped(); void notify_waiting_main(); bool was_stopped() const { return stop_called_; } void add_pre_startup_function(startup_function_type f); void add_startup_function(startup_function_type f); void add_pre_shutdown_function(shutdown_function_type f); void add_shutdown_function(shutdown_function_type f); void remove_here_from_connection_cache(); void remove_here_from_console_connection_cache(); /////////////////////////////////////////////////////////////////////// void register_message_handler(char const* message_handler_type, char const* action, error_code& ec); parcelset::policies::message_handler* create_message_handler( char const* message_handler_type, char const* action, parcelset::parcelport* pp, std::size_t num_messages, std::size_t interval, error_code& ec); serialization::binary_filter* create_binary_filter( char const* binary_filter_type, bool compress, serialization::binary_filter* next_filter, error_code& ec); // notify of message being sent void dijkstra_make_black(); protected: // Load all components from the ini files found in the configuration int load_components(util::section& ini, naming::gid_type const& prefix, naming::resolver_client& agas_client, boost::program_options::options_description& options, std::set<std::string>& startup_handled); #if !defined(HPX_HAVE_STATIC_LINKING) bool load_component(hpx::util::plugin::dll& d, util::section& ini, std::string const& instance, std::string const& component, boost::filesystem::path const& lib, naming::gid_type const& prefix, naming::resolver_client& agas_client, bool isdefault, bool isenabled, boost::program_options::options_description& options, std::set<std::string>& startup_handled); bool load_component_dynamic( util::section& ini, std::string const& instance, std::string const& component, boost::filesystem::path lib, naming::gid_type const& prefix, naming::resolver_client& agas_client, bool isdefault, bool isenabled, boost::program_options::options_description& options, std::set<std::string>& startup_handled); bool load_startup_shutdown_functions(hpx::util::plugin::dll& d, error_code& ec); bool load_commandline_options(hpx::util::plugin::dll& d, boost::program_options::options_description& options, error_code& ec); #endif bool load_component_static( util::section& ini, std::string const& instance, std::string const& component, boost::filesystem::path const& lib, naming::gid_type const& prefix, naming::resolver_client& agas_client, bool isdefault, bool isenabled, boost::program_options::options_description& options, std::set<std::string>& startup_handled); bool load_startup_shutdown_functions_static(std::string const& module, error_code& ec); bool load_commandline_options_static( std::string const& module, boost::program_options::options_description& options, error_code& ec); // Load all plugins from the ini files found in the configuration bool load_plugins(util::section& ini, boost::program_options::options_description& options, std::set<std::string>& startup_handled); #if !defined(HPX_HAVE_STATIC_LINKING) bool load_plugin(hpx::util::plugin::dll& d, util::section& ini, std::string const& instance, std::string const& component, boost::filesystem::path const& lib, bool isenabled, boost::program_options::options_description& options, std::set<std::string>& startup_handled); bool load_plugin_dynamic( util::section& ini, std::string const& instance, std::string const& component, boost::filesystem::path lib, bool isenabled, boost::program_options::options_description& options, std::set<std::string>& startup_handled); #endif // the name says it all std::size_t dijkstra_termination_detection( std::vector<naming::id_type> const& locality_ids); #if !defined(HPX_USE_FAST_DIJKSTRA_TERMINATION_DETECTION) void send_dijkstra_termination_token( std::uint32_t target_locality_id, std::uint32_t initiating_locality_id, std::uint32_t num_localities, bool dijkstra_token); #endif private: compat::mutex mtx_; compat::condition_variable wait_condition_; compat::condition_variable stop_condition_; bool stop_called_; bool stop_done_; bool terminated_; compat::thread::id main_thread_id_; bool dijkstra_color_; // false: white, true: black std::atomic<bool> shutdown_all_invoked_; typedef hpx::lcos::local::spinlock dijkstra_mtx_type; dijkstra_mtx_type dijkstra_mtx_; lcos::local::condition_variable_any dijkstra_cond_; plugin_map_mutex_type p_mtx_; plugin_map_type plugins_; modules_map_type & modules_; static_modules_type static_modules_; lcos::local::spinlock globals_mtx_; std::list<startup_function_type> pre_startup_functions_; std::list<startup_function_type> startup_functions_; std::list<shutdown_function_type> pre_shutdown_functions_; std::list<shutdown_function_type> shutdown_functions_; }; /////////////////////////////////////////////////////////////////////////// // Functions wrapped by create_component actions below #if defined(__NVCC__) template <typename Component> naming::gid_type runtime_support::create_component() { HPX_ASSERT(false); return naming::gid_type(); } template <typename Component, typename T, typename ...Ts> naming::gid_type runtime_support::create_component(T v, Ts... vs) { HPX_ASSERT(false); return naming::gid_type(); } #else template <typename Component> naming::gid_type runtime_support::create_component() { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); typedef typename Component::wrapping_type wrapping_type; naming::gid_type id = create<wrapping_type>(); LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component, typename T, typename ...Ts> naming::gid_type runtime_support::create_component(T v, Ts... vs) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); typedef typename Component::wrapping_type wrapping_type; // Note, T and Ts can't be (non-const) references, and parameters // should be moved to allow for move-only constructor argument // types. naming::gid_type id = create<wrapping_type>(std::move(v), std::move(vs)...); LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } #endif template <typename Component> std::vector<naming::gid_type> runtime_support::bulk_create_component(std::size_t count) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); std::vector<naming::gid_type> ids; ids.reserve(count); typedef typename Component::wrapping_type wrapping_type; for (std::size_t i = 0; i != count; ++i) { ids.push_back(create<wrapping_type>()); } LRT_(info) << "successfully created " << count //-V128 << " component(s) of type: " << components::get_component_type_name(type); return ids; } template <typename Component, typename T, typename ...Ts> std::vector<naming::gid_type> runtime_support::bulk_create_component(std::size_t count, T v, Ts ... vs) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); std::vector<naming::gid_type> ids; ids.reserve(count); typedef typename Component::wrapping_type wrapping_type; for (std::size_t i = 0; i != count; ++i) { ids.push_back(create<wrapping_type>(v, vs...)); } LRT_(info) << "successfully created " << count //-V128 << " component(s) of type: " << components::get_component_type_name(type); return ids; } template <typename Component> naming::gid_type runtime_support::copy_create_component( std::shared_ptr<Component> const& p, bool local_op) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); typedef typename Component::wrapping_type wrapping_type; naming::gid_type id; if (!local_op) { id = create<wrapping_type>(std::move(*p)); } else { id = create<wrapping_type>(*p); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } /////////////////////////////////////////////////////////////////////////// template <typename Component> naming::gid_type runtime_support::migrate_component_to_here( std::shared_ptr<Component> const& p, naming::id_type to_migrate) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); // create a local instance by copying the bits and remapping the id in // AGAS naming::gid_type migrated_id = to_migrate.get_gid(); typedef typename Component::wrapping_type wrapping_type; typename wrapping_type::derived_type* new_instance = nullptr; naming::gid_type id = create_migrated<wrapping_type>(migrated_id, reinterpret_cast<void**>(&new_instance), std::move(*p)); // sanity checks if (!id || new_instance == nullptr) { // we should not get here (id should not be invalid) HPX_THROW_EXCEPTION(hpx::invalid_status, "runtime_support::migrate_component_to_here", "could not create copy of given component"); return naming::invalid_gid; } if (id != migrated_id) { // we should not get here either (the ids should be the same) HPX_THROW_EXCEPTION(hpx::invalid_status, "runtime_support::migrate_component_to_here", "could not create copy of given component (the new id is " "different from the original id)"); return naming::invalid_gid; } LRT_(info) << "successfully migrated component " << id << " of type: " << components::get_component_type_name(type) << " to locality: " << find_here(); // inform the newly created component that it has been migrated new_instance->on_migrated(); // At this point the object has been fully migrated. We now remove // the object from the AGAS table of migrated objects. This is // necessary as this object might have been migrated off this locality // before it was migrated back. agas::unmark_as_migrated(id); to_migrate.make_unmanaged(); return id; } }}} #include <hpx/config/warnings_suffix.hpp> HPX_ACTION_USES_LARGE_STACK( hpx::components::server::runtime_support::load_components_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::call_startup_functions_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::call_shutdown_functions_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::shutdown_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::shutdown_all_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::create_performance_counter_action) HPX_ACTION_USES_MEDIUM_STACK( hpx::components::server::runtime_support::dijkstra_termination_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::load_components_action, load_components_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::call_startup_functions_action, call_startup_functions_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::call_shutdown_functions_action, call_shutdown_functions_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::shutdown_action, shutdown_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::shutdown_all_action, shutdown_all_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::terminate_action, terminate_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::terminate_all_action, terminate_all_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::get_config_action, get_config_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::garbage_collect_action, garbage_collect_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::create_performance_counter_action, create_performance_counter_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::remove_from_connection_cache_action, remove_from_connection_cache_action) HPX_REGISTER_ACTION_DECLARATION( hpx::components::server::runtime_support::dijkstra_termination_action, dijkstra_termination_action) namespace hpx { namespace components { namespace server { template <typename Component, typename ...Ts> struct create_component_action : ::hpx::actions::action< naming::gid_type (runtime_support::*)(Ts...) , &runtime_support::create_component<Component, Ts...> , create_component_action<Component, Ts...> > {}; template <typename Component> struct create_component_action<Component> : ::hpx::actions::action< naming::gid_type (runtime_support::*)() , &runtime_support::create_component<Component> , create_component_action<Component> > {}; template <typename Component, typename ...Ts> struct create_component_direct_action : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(Ts...) , &runtime_support::create_component<Component, Ts...> , create_component_direct_action<Component, Ts...> > {}; template <typename Component> struct create_component_direct_action<Component> : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)() , &runtime_support::create_component<Component> , create_component_direct_action<Component> > {}; /////////////////////////////////////////////////////////////////////////// template <typename Component, typename ...Ts> struct bulk_create_component_action : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)(std::size_t, Ts...) , &runtime_support::bulk_create_component<Component, Ts...> , bulk_create_component_action<Component, Ts...> > {}; template <typename Component> struct bulk_create_component_action<Component> : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)(std::size_t) , &runtime_support::bulk_create_component<Component> , bulk_create_component_action<Component> > {}; template <typename Component, typename ...Ts> struct bulk_create_component_direct_action : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)(std::size_t, Ts...) , &runtime_support::bulk_create_component<Component, Ts...> , bulk_create_component_direct_action<Component, Ts...> > {}; template <typename Component> struct bulk_create_component_direct_action<Component> : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)(std::size_t) , &runtime_support::bulk_create_component<Component> , bulk_create_component_direct_action<Component> > {}; /////////////////////////////////////////////////////////////////////////// template <typename Component> struct copy_create_component_action : ::hpx::actions::action< naming::gid_type (runtime_support::*)( std::shared_ptr<Component> const&, bool) , &runtime_support::copy_create_component<Component> , copy_create_component_action<Component> > {}; template <typename Component> struct migrate_component_here_action : ::hpx::actions::action< naming::gid_type (runtime_support::*)( std::shared_ptr<Component> const&, naming::id_type) , &runtime_support::migrate_component_to_here<Component> , migrate_component_here_action<Component> > {}; }}} namespace hpx { namespace traits { /////////////////////////////////////////////////////////////////////////// // Termination detection does not make this locality black template <> struct action_does_termination_detection< hpx::components::server::runtime_support::dijkstra_termination_action> { static bool call() { return true; } }; // runtime_support is a (hand-rolled) component template <> struct is_component<components::server::runtime_support> : std::true_type {}; }} #endif // HPX_RUNTIME_SUPPORT_JUN_02_2008_1145AM
/* * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * * @section DESCRIPTION * * This class contains the implementation of the EuclideanVector2D class. */ #include "EuclideanVector2D.h" namespace cupcfd { namespace geometry { namespace euclidean { } } }
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <functional> #include <vector> #include <deque> #include <queue> #include <map> #include <set> #include <stack> #include <list> #include <unordered_map> #include <unordered_set> #include <iterator> #include <bitset> #include <limits> #include <numeric> #include <iomanip> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> #include <climits> #include <regex> using namespace std; typedef unsigned int ui; typedef long long int ll; typedef unsigned long long int ull; #define $1 first #define $2 second #define pb push_back #define INF 0x5A5B5C5D #define INF2 0x77777777 #define PI 3.1415926535897932 #define MAX(x,y) ((x)>(y)?(x):(y)) #define MIN(x,y) ((x)<(y)?(x):(y)) #define MAX3(x,y,z) (MAX(MAX(x,y),z)) #define MIN3(x,y,z) (MIN(MIN(x,y),z)) #define MAX4(a,b,c,d) (MAX(MAX3(a,b,c),d)) #define MIN4(a,b,c,d) (MIN(MIN3(a,b,c),d)) #define MEDIAN(x,y,z) (MIN(MAX(x,y),z)==z?MAX(MIN(x,y),z):MAX(x,y)) #define REP(i,n) for(ull (i)=0;(i)<ull(n);(i)++) #define ALL(list) (list).begin(),(list).end() #define PRESENT(list,x) (find(ALL(list),x)!=(list).end()) #define INPUT(cin_a) cin>>(cin_a) #define INPUT2(cin_a,cin_b) cin>>(cin_a)>>(cin_b) #define INPUT3(cin_a,cin_b,cin_c) cin>>(cin_a)>>(cin_b)>>(cin_c) #define DINPUT(int_a) int (int_a);INPUT(int_a) #define DINPUT2(int_a,int_b) int (int_a),(int_b);INPUT2(int_a,int_b) #define DINPUT3(int_a,int_b,int_c) int (int_a),(int_b),(int_c);INPUT3(int_a,int_b,int_c) #define DSCANF(int_a) int (int_a);scanf("%d",&(int_a)) #define DSCANF2(int_a,int_b) int (int_a),(int_b);scanf("%d%d",&(int_a),&(int_b)) #define DSCANF3(int_a,int_b,int_c) int (int_a),(int_b),(int_c);scanf("%d%d%d",&(int_a),&(int_b),&(int_c)) #define TESTCASE(T) DINPUT(i_i__ai);for(int (T)=1;(T)<=i_i__ai;(T)++) #define INIT(arr) memset((arr),0,sizeof(arr)) #define FILL(a,x) for(auto& acm_icpc:(a))acm_icpc=(x); #define BETWEEN(x,low,high) ((x)>=(low)&&(x)<=(high)) #define ctoi(ch) ((ch)-'0') #define countof(arr) (sizeof(arr)/sizeof((arr)[0])) #define endl '\n' #define PRINT(cout_x) cout<<(cout_x)<<endl #define DEBUG(cout_x) cout<<">> "<<#cout_x<<" = "<<(cout_x)<<endl #ifndef ONLINE_JUDGE #define READTXT freopen(TXTPATH,"r",stdin) #define UNSYNC ios_base::sync_with_stdio(false) #else #define READTXT #define UNSYNC ios_base::sync_with_stdio(false);cin.tie(nullptr) #endif #define TXTPATH "_input.txt" inline ull GCD(ull a, ull b) { while (b != 0) { ull t = a % b; a = b; b = t; } return a; } inline ull LCM(ull a, ull b) { return a * b / GCD(a, b); } int arr[10005]; int main() { UNSYNC; READTXT; DINPUT2(N, M); for (int i = 1; i <= N; i++) cin >> arr[i]; int left = 1, right = 0; int sum = 0, ans = 0; for (int i = 1; i <= N; i++) { sum += arr[i]; if (sum == M) ans++; if (sum >= M) { sum -= arr[left]; left++; if (left <= i) { sum -= arr[i]; i--; } } } cout << ans; }
/* * Copyright (c) 2020, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <memory> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "platform/mbed_error.h" #include "blockdevice/internal/SFDP.h" #if (DEVICE_SPI || DEVICE_QSPI || DEVICE_OSPI) #include "mbed-trace/mbed_trace.h" #define TRACE_GROUP "SFDP" namespace { /* Extracts Parameter ID MSB from the second DWORD of a parameter header */ inline uint8_t sfdp_get_param_id_msb(uint32_t dword2) { return (dword2 & 0xFF000000) >> 24; } /* Extracts Parameter Table Pointer from the second DWORD of a parameter header */ inline uint32_t sfdp_get_param_tbl_ptr(uint32_t dword2) { return dword2 & 0x00FFFFFF; } } namespace mbed { // Erase Types Params constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_1_BYTE = 29; ///< Erase Type 1 Instruction constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_2_BYTE = 31; ///< Erase Type 2 Instruction constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_3_BYTE = 33; ///< Erase Type 3 Instruction constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_4_BYTE = 35; ///< Erase Type 4 Instruction constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_1_SIZE_BYTE = 28; ///< Erase Type 1 Size constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_2_SIZE_BYTE = 30; ///< Erase Type 2 Size constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_3_SIZE_BYTE = 32; ///< Erase Type 3 Size constexpr int SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_4_SIZE_BYTE = 34; ///< Erase Type 4 Size constexpr int SFDP_BASIC_PARAM_TABLE_4K_ERASE_TYPE_BYTE = 1; ///< 4 Kilobyte Erase Instruction constexpr int SFDP_ERASE_BITMASK_TYPE_4K_ERASE_UNSUPPORTED = 0xFF; /** SFDP Header */ struct sfdp_hdr { uint8_t SIG_B0; ///< SFDP Signature, Byte 0 uint8_t SIG_B1; ///< SFDP Signature, Byte 1 uint8_t SIG_B2; ///< SFDP Signature, Byte 2 uint8_t SIG_B3; ///< SFDP Signature, Byte 3 uint8_t R_MINOR; ///< SFDP Minor Revision uint8_t R_MAJOR; ///< SFDP Major Revision uint8_t NPH; ///< Number of parameter headers (0-based, 0 indicates 1 parameter header) uint8_t ACP; ///< SFDP Access Protocol }; /** SFDP Parameter header */ struct sfdp_prm_hdr { uint8_t PID_LSB; ///< Parameter ID LSB uint8_t P_MINOR; ///< Parameter Minor Revision uint8_t P_MAJOR; ///< Parameter Major Revision uint8_t P_LEN; ///< Parameter length in DWORDS uint32_t DWORD2; ///< Parameter ID MSB + Parameter Table Pointer }; /** Parse SFDP Header * @param sfdp_hdr_ptr Pointer to memory holding an SFDP header * @return Number of Parameter Headers on success, -1 on failure */ int sfdp_parse_sfdp_header(sfdp_hdr *sfdp_hdr_ptr) { if (!(memcmp(sfdp_hdr_ptr, "SFDP", 4) == 0 && sfdp_hdr_ptr->R_MAJOR == 1)) { tr_error("Verify SFDP signature and version Failed"); return -1; } tr_debug("Verified SFDP Signature and version successfully"); int hdr_cnt = sfdp_hdr_ptr->NPH + 1; tr_debug("Number of parameter headers: %d", hdr_cnt); return hdr_cnt; } /** Parse Parameter Header * @param phdr_ptr Pointer to memory holding a single SFDP Parameter header * @param hdr_info Reference to a Parameter Table structure where info about the table is written * @return 0 on success, -1 on failure */ int sfdp_parse_single_param_header(sfdp_prm_hdr *phdr_ptr, sfdp_hdr_info &hdr_info) { if (phdr_ptr->P_MAJOR != 1) { tr_error("Parameter header: Major Version must be 1!"); return -1; } int param_id_msb = sfdp_get_param_id_msb(phdr_ptr->DWORD2); /* MSB JEDEC ID */ if (param_id_msb == 0xFF) { /* LSB JEDEC ID */ switch (phdr_ptr->PID_LSB) { case 0x0: tr_debug("Parameter header: JEDEC Basic Flash - Revision %" PRIX8 ".%" PRIX8 "", phdr_ptr->P_MAJOR, phdr_ptr->P_MINOR); hdr_info.bptbl.addr = sfdp_get_param_tbl_ptr(phdr_ptr->DWORD2); hdr_info.bptbl.size = std::min((phdr_ptr->P_LEN * 4), SFDP_BASIC_PARAMS_TBL_SIZE); break; case 0x81: tr_info("Parameter header: Sector Map"); hdr_info.smptbl.addr = sfdp_get_param_tbl_ptr(phdr_ptr->DWORD2); hdr_info.smptbl.size = phdr_ptr->P_LEN * 4; break; case 0x84: tr_info("Parameter header: 4-byte Address Instruction"); hdr_info.fbatbl.addr = sfdp_get_param_tbl_ptr(phdr_ptr->DWORD2); hdr_info.fbatbl.size = phdr_ptr->P_LEN * 4; break; /* Unsupported */ case 0x03: tr_info("UNSUPPORTED:Parameter header: Replay Protected Monotonic Counters"); break; case 0x05: tr_info("UNSUPPORTED:Parameter header: eXtended Serial Peripheral Interface (xSPI) Profile 1.0"); break; case 0x06: tr_info("UNSUPPORTED:Parameter header: eXtended Serial Peripheral Interface (xSPI) Profile 2.0"); break; case 0x87: tr_info("UNSUPPORTED:Parameter header: SCCR Map for SPI Memory Devices"); break; case 0x88: tr_info("UNSUPPORTED:Parameter header: SCCR Map Offsets for Multi-Chip SPI Memory Devices"); break; case 0x09: tr_info("UNSUPPORTED:Parameter header: SCCR Map for xSPI Profile 2.0 Memory Devices"); break; case 0x0A: tr_info("UNSUPPORTED:Parameter header: Command Sequences to Change to Octal DDR (8D-8D-8D) mode"); break; case 0x0C: tr_info("UNSUPPORTED:Parameter header: x4 Quad IO with DS"); break; case 0x8D: tr_info("UNSUPPORTED:Parameter header: Command Sequences to Change to Quad DDR (4S-4D-4D) mode"); break; default: tr_debug("Parameter header: unknown JEDEC header. Parameter ID LSB: 0x%" PRIX8 "; MSB: 0x%" PRIX8 "", phdr_ptr->PID_LSB, sfdp_get_param_id_msb(phdr_ptr->DWORD2)); } } else if (param_id_msb >= 0x80) { // MSB JEDEC ID tr_debug("Parameter header: unknown JEDEC header. Parameter ID LSB: 0x%" PRIX8 "; MSB: 0x%" PRIX8 "", phdr_ptr->PID_LSB, sfdp_get_param_id_msb(phdr_ptr->DWORD2)); } else { // MSB Vendor ID tr_info("Parameter header: vendor specific header. Parameter ID LSB: 0x%" PRIX8 "; MSB: 0x%" PRIX8 "", phdr_ptr->PID_LSB, sfdp_get_param_id_msb(phdr_ptr->DWORD2)); } return 0; } int sfdp_parse_headers(Callback<int(bd_addr_t, void *, bd_size_t)> sfdp_reader, sfdp_hdr_info &sfdp_info) { bd_addr_t addr = 0x0; int number_of_param_headers = 0; size_t data_length; { data_length = SFDP_HEADER_SIZE; uint8_t sfdp_header[SFDP_HEADER_SIZE]; int status = sfdp_reader(addr, sfdp_header, data_length); if (status < 0) { tr_error("Retrieving SFDP Header failed"); return -1; } number_of_param_headers = sfdp_parse_sfdp_header((sfdp_hdr *)sfdp_header); if (number_of_param_headers < 0) { return number_of_param_headers; } } addr += SFDP_HEADER_SIZE; { data_length = SFDP_HEADER_SIZE; uint8_t param_header[SFDP_HEADER_SIZE]; int status; int hdr_status; // Loop over Param Headers and parse them (currently supports Basic Param Table and Sector Region Map Table) for (int idx = 0; idx < number_of_param_headers; idx++) { status = sfdp_reader(addr, param_header, data_length); if (status < 0) { tr_error("Retrieving a parameter header %d failed", idx + 1); return -1; } hdr_status = sfdp_parse_single_param_header((sfdp_prm_hdr *)param_header, sfdp_info); if (hdr_status < 0) { return hdr_status; } addr += SFDP_HEADER_SIZE; } } return 0; } int sfdp_parse_sector_map_table(Callback<int(bd_addr_t, void *, bd_size_t)> sfdp_reader, sfdp_hdr_info &sfdp_info) { uint32_t tmp_region_size = 0; uint8_t type_mask; int prev_boundary = 0; // Default set to all type bits 1-4 are common int min_common_erase_type_bits = SFDP_ERASE_BITMASK_ALL; // If there's no region map, we have a single region sized the entire device size sfdp_info.smptbl.region_size[0] = sfdp_info.bptbl.device_size_bytes; sfdp_info.smptbl.region_high_boundary[0] = sfdp_info.bptbl.device_size_bytes - 1; if (!sfdp_info.smptbl.addr || !sfdp_info.smptbl.size) { tr_debug("No Sector Map Table"); return MBED_SUCCESS; } /* The number of * - sector map configuration detection commands * - configurations * - regions in each configuration * is variable -> the size of this table is variable */ auto smptbl_buff = std::make_unique<uint8_t[]>(sfdp_info.smptbl.size); if (!smptbl_buff) { tr_error("Failed to allocate memory"); return -1; } tr_debug("Parsing Sector Map Table - addr: 0x%" PRIx32 ", Size: %d", sfdp_info.smptbl.addr, sfdp_info.smptbl.size); int status = sfdp_reader(sfdp_info.smptbl.addr, smptbl_buff.get(), sfdp_info.smptbl.size); if (status < 0) { tr_error("Sector Map: Table retrieval failed"); return -1; } // Currently we support only Single Map Descriptor if (!((smptbl_buff[0] & 0x3) == 0x03) && (smptbl_buff[1] == 0x0)) { tr_error("Sector Map: Supporting Only Single Map Descriptor (not map commands)"); return -1; } sfdp_info.smptbl.region_cnt = smptbl_buff[2] + 1; if (sfdp_info.smptbl.region_cnt > SFDP_SECTOR_MAP_MAX_REGIONS) { tr_error("Sector Map: Supporting up to %d regions, current setup to %d regions - fail", SFDP_SECTOR_MAP_MAX_REGIONS, sfdp_info.smptbl.region_cnt); return -1; } // Loop through Regions and set for each one: size, supported erase types, high boundary offset // Calculate minimum Common Erase Type for all Regions for (auto idx = 0; idx < sfdp_info.smptbl.region_cnt; idx++) { tmp_region_size = ((*((uint32_t *)&smptbl_buff[(idx + 1) * 4])) >> 8) & 0x00FFFFFF; // bits 9-32 sfdp_info.smptbl.region_size[idx] = (tmp_region_size + 1) * 256; // Region size is 0 based multiple of 256 bytes; sfdp_info.smptbl.region_erase_types_bitfld[idx] = smptbl_buff[(idx + 1) * 4] & 0x0F; // bits 1-4 min_common_erase_type_bits &= sfdp_info.smptbl.region_erase_types_bitfld[idx]; sfdp_info.smptbl.region_high_boundary[idx] = (sfdp_info.smptbl.region_size[idx] - 1) + prev_boundary; prev_boundary = sfdp_info.smptbl.region_high_boundary[idx] + 1; } // Calc minimum Common Erase Size from min_common_erase_type_bits type_mask = SFDP_ERASE_BITMASK_TYPE1; // If no common erase type is found between regions sfdp_info.smptbl.regions_min_common_erase_size = 0; for (auto idx = 0; idx < 4; idx++) { if (min_common_erase_type_bits & type_mask) { sfdp_info.smptbl.regions_min_common_erase_size = sfdp_info.smptbl.erase_type_size_arr[idx]; break; } type_mask = type_mask << 1; } return 0; } size_t sfdp_detect_page_size(uint8_t *basic_param_table_ptr, size_t basic_param_table_size) { constexpr int SFDP_BASIC_PARAM_TABLE_PAGE_SIZE = 40; constexpr int SFDP_DEFAULT_PAGE_SIZE = 256; unsigned int page_size = SFDP_DEFAULT_PAGE_SIZE; if (basic_param_table_size > SFDP_BASIC_PARAM_TABLE_PAGE_SIZE) { // Page Size is specified by 4 Bits (N), calculated by 2^N int page_to_power_size = ((int)basic_param_table_ptr[SFDP_BASIC_PARAM_TABLE_PAGE_SIZE]) >> 4; page_size = 1 << page_to_power_size; tr_debug("Detected Page Size: %d", page_size); } else { tr_debug("Using Default Page Size: %d", page_size); } return page_size; } int sfdp_detect_erase_types_inst_and_size(uint8_t *bptbl_ptr, sfdp_hdr_info &sfdp_info) { uint8_t bitfield = 0x01; // Erase 4K Inst is taken either from param table legacy 4K erase or superseded by erase Instruction for type of size 4K if (sfdp_info.bptbl.size > SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_1_SIZE_BYTE) { // Loop Erase Types 1-4 for (int idx = 0; idx < 4; idx++) { sfdp_info.smptbl.erase_type_inst_arr[idx] = -1; // Default for unsupported type sfdp_info.smptbl.erase_type_size_arr[idx] = 1 << bptbl_ptr[SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_1_SIZE_BYTE + 2 * idx]; // Size is 2^N where N is the table value tr_debug("Erase Type(A) %d - Inst: 0x%xh, Size: %d", (idx + 1), sfdp_info.smptbl.erase_type_inst_arr[idx], sfdp_info.smptbl.erase_type_size_arr[idx]); if (sfdp_info.smptbl.erase_type_size_arr[idx] > 1) { // if size==1 type is not supported sfdp_info.smptbl.erase_type_inst_arr[idx] = bptbl_ptr[SFDP_BASIC_PARAM_TABLE_ERASE_TYPE_1_BYTE + 2 * idx]; if ((sfdp_info.smptbl.erase_type_size_arr[idx] < sfdp_info.smptbl.regions_min_common_erase_size) || (sfdp_info.smptbl.regions_min_common_erase_size == 0)) { //Set default minimal common erase for signal region sfdp_info.smptbl.regions_min_common_erase_size = sfdp_info.smptbl.erase_type_size_arr[idx]; } sfdp_info.smptbl.region_erase_types_bitfld[0] |= bitfield; // If there's no region map, set region "0" types bitfield as default } tr_debug("Erase Type %d - Inst: 0x%xh, Size: %d", (idx + 1), sfdp_info.smptbl.erase_type_inst_arr[idx], sfdp_info.smptbl.erase_type_size_arr[idx]); bitfield = bitfield << 1; } } else { tr_debug("Erase types are not available - falling back to legacy 4k erase instruction"); sfdp_info.bptbl.legacy_erase_instruction = bptbl_ptr[SFDP_BASIC_PARAM_TABLE_4K_ERASE_TYPE_BYTE]; if (sfdp_info.bptbl.legacy_erase_instruction == SFDP_ERASE_BITMASK_TYPE_4K_ERASE_UNSUPPORTED) { tr_error("Legacy 4k erase instruction not supported"); return -1; } } return 0; } int sfdp_find_addr_region(bd_addr_t offset, const sfdp_hdr_info &sfdp_info) { if ((offset >= sfdp_info.bptbl.device_size_bytes) || (sfdp_info.smptbl.region_cnt == 0)) { return -1; } if (sfdp_info.smptbl.region_cnt == 1) { return 0; } for (int idx = 0; idx < sfdp_info.smptbl.region_cnt; idx++) { if (offset <= sfdp_info.smptbl.region_high_boundary[idx]) { return idx; } } return -1; } int sfdp_iterate_next_largest_erase_type(uint8_t bitfield, bd_size_t size, bd_addr_t offset, int region, const sfdp_smptbl_info &smptbl) { uint8_t type_mask = SFDP_ERASE_BITMASK_TYPE4; unsigned int erase_size; for (int idx = 3; idx >= 0; idx--) { if (bitfield & type_mask) { erase_size = smptbl.erase_type_size_arr[idx]; // Criteria: // * offset is aligned to the type's erase size // * erase size is no larger than the requested size, // * erase range does not exceed the region boundary if ((offset % erase_size == 0) && (size >= erase_size) && (offset + erase_size - 1 <= smptbl.region_high_boundary[region])) { return idx; } } type_mask = type_mask >> 1; } tr_error("No erase type was found for current region addr"); return -1; } int sfdp_detect_device_density(uint8_t *bptbl_ptr, sfdp_bptbl_info &bptbl_info) { // stored in bits - 1 uint32_t density_bits = ( (bptbl_ptr[7] << 24) | (bptbl_ptr[6] << 16) | (bptbl_ptr[5] << 8) | bptbl_ptr[4]); bptbl_info.device_size_bytes = (density_bits + 1) / 8; tr_info("Density bits: %" PRIu32 " , device size: %llu bytes", density_bits, bptbl_info.device_size_bytes); return 0; } #if (DEVICE_QSPI || DEVICE_OSPI) int sfdp_detect_addressability(uint8_t *bptbl_ptr, sfdp_bptbl_info &bptbl_info) { // Check that density is not greater than 4 gigabits (i.e. that addressing beyond 4 bytes is not required) if ((bptbl_ptr[7] & 0x80) != 0) { return -1; } return 0; } #elif DEVICE_SPI int sfdp_detect_addressability(uint8_t *bptbl_ptr, sfdp_bptbl_info &bptbl_info) { // Check address size, currently only supports 3byte addresses if ((bptbl_ptr[2] & 0x4) != 0 || (bptbl_ptr[7] & 0x80) != 0) { return -1; } return 0; } #endif } /* namespace mbed */ #endif /* (DEVICE_SPI || DEVICE_QSPI || DEVICE_OSPI) */
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "JSONUtils.h" #include <vector> #include <string> #include <functional> #include <pugixml.hpp> #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "gsl/gsl-lite.hpp"; namespace org { namespace apache { namespace nifi { namespace minifi { namespace wel { namespace { rapidjson::Value xmlElementToJSON(const pugi::xml_node& node, rapidjson::Document& doc) { gsl_Expects(node.type() == pugi::xml_node_type::node_element); rapidjson::Value object(rapidjson::kObjectType); object.AddMember("name", rapidjson::StringRef(node.name()), doc.GetAllocator()); auto& attributes = object.AddMember("attributes", rapidjson::kObjectType, doc.GetAllocator())["attributes"]; for (const auto& attr : node.attributes()) { attributes.AddMember(rapidjson::StringRef(attr.name()), rapidjson::StringRef(attr.value()), doc.GetAllocator()); } auto& children = object.AddMember("children", rapidjson::kArrayType, doc.GetAllocator())["children"]; for (const auto& child : node.children()) { if (child.type() == pugi::xml_node_type::node_element) { children.PushBack(xmlElementToJSON(child, doc), doc.GetAllocator()); } } object.AddMember("text", rapidjson::StringRef(node.text().get()), doc.GetAllocator()); return object; } rapidjson::Value xmlDocumentToJSON(const pugi::xml_node& node, rapidjson::Document& doc) { gsl_Expects(node.type() == pugi::xml_node_type::node_document); rapidjson::Value children(rapidjson::kArrayType); for (const auto& child : node.children()) { if (child.type() == pugi::xml_node_type::node_element) { children.PushBack(xmlElementToJSON(child, doc), doc.GetAllocator()); } } return children; } rapidjson::Document toJSONImpl(const pugi::xml_node& root, bool flatten) { rapidjson::Document doc{rapidjson::kObjectType}; auto event_xml = root.child("Event"); { auto system_xml = event_xml.child("System"); auto& system = flatten ? doc : doc.AddMember("System", rapidjson::kObjectType, doc.GetAllocator())["System"]; { auto provider_xml = system_xml.child("Provider"); auto& provider = flatten ? doc : system.AddMember("Provider", rapidjson::kObjectType, doc.GetAllocator())["Provider"]; provider.AddMember("Name", rapidjson::StringRef(provider_xml.attribute("Name").value()), doc.GetAllocator()); provider.AddMember("Guid", rapidjson::StringRef(provider_xml.attribute("Guid").value()), doc.GetAllocator()); } system.AddMember("EventID", rapidjson::StringRef(system_xml.child("EventID").text().get()), doc.GetAllocator()); system.AddMember("Version", rapidjson::StringRef(system_xml.child("Version").text().get()), doc.GetAllocator()); system.AddMember("Level", rapidjson::StringRef(system_xml.child("Level").text().get()), doc.GetAllocator()); system.AddMember("Task", rapidjson::StringRef(system_xml.child("Task").text().get()), doc.GetAllocator()); system.AddMember("Opcode", rapidjson::StringRef(system_xml.child("Opcode").text().get()), doc.GetAllocator()); system.AddMember("Keywords", rapidjson::StringRef(system_xml.child("Keywords").text().get()), doc.GetAllocator()); { auto timeCreated_xml = system_xml.child("TimeCreated"); auto& timeCreated = flatten ? doc : system.AddMember("TimeCreated", rapidjson::kObjectType, doc.GetAllocator())["TimeCreated"]; timeCreated.AddMember("SystemTime", rapidjson::StringRef(timeCreated_xml.attribute("SystemTime").value()), doc.GetAllocator()); } system.AddMember("EventRecordID", rapidjson::StringRef(system_xml.child("EventRecordID").text().get()), doc.GetAllocator()); { auto correlation_xml = system_xml.child("Correlation"); auto& correlation = flatten ? doc : system.AddMember("Correlation", rapidjson::kObjectType, doc.GetAllocator())["Correlation"]; correlation.AddMember("ActivityID", rapidjson::StringRef(correlation_xml.attribute("ActivityID").value()), doc.GetAllocator()); } { auto execution_xml = system_xml.child("Execution"); auto& execution = flatten ? doc : system.AddMember("Execution", rapidjson::kObjectType, doc.GetAllocator())["Execution"]; execution.AddMember("ProcessID", rapidjson::StringRef(execution_xml.attribute("ProcessID").value()), doc.GetAllocator()); execution.AddMember("ThreadID", rapidjson::StringRef(execution_xml.attribute("ThreadID").value()), doc.GetAllocator()); } system.AddMember("Channel", rapidjson::StringRef(system_xml.child("Channel").text().get()), doc.GetAllocator()); system.AddMember("Computer", rapidjson::StringRef(system_xml.child("Computer").text().get()), doc.GetAllocator()); } { auto eventData_xml = event_xml.child("EventData"); // create EventData subarray even if flatten requested doc.AddMember("EventData", rapidjson::kArrayType, doc.GetAllocator()); for (const auto& data : eventData_xml.children()) { auto name_attr = data.attribute("Name"); rapidjson::Value item(rapidjson::kObjectType); item.AddMember("Name", rapidjson::StringRef(name_attr.value()), doc.GetAllocator()); item.AddMember("Content", rapidjson::StringRef(data.text().get()), doc.GetAllocator()); item.AddMember("Type", rapidjson::StringRef(data.name()), doc.GetAllocator()); // we need to query EventData because a reference to it wouldn't be stable, as we // possibly add members to its parent which could result in reallocation doc["EventData"].PushBack(item, doc.GetAllocator()); // check collision if (flatten && !name_attr.empty() && !doc.HasMember(name_attr.value())) { doc.AddMember(rapidjson::StringRef(name_attr.value()), rapidjson::StringRef(data.text().get()), doc.GetAllocator()); } } } return doc; } } // namespace rapidjson::Document toRawJSON(const pugi::xml_node& root) { rapidjson::Document doc; if (root.type() == pugi::xml_node_type::node_document) { static_cast<rapidjson::Value&>(doc) = xmlDocumentToJSON(root, doc); } return doc; } rapidjson::Document toSimpleJSON(const pugi::xml_node& root) { return toJSONImpl(root, false); } rapidjson::Document toFlattenedJSON(const pugi::xml_node& root) { return toJSONImpl(root, true); } std::string jsonToString(const rapidjson::Document& doc) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return buffer.GetString(); } } // namespace wel } // namespace minifi } // namespace nifi } // namespace apache } // namespace org
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: 21015_S2CNewRoomAddNotify.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "21015_S2CNewRoomAddNotify.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace Protocol { namespace { const ::google::protobuf::Descriptor* S2CNewRoomAddNotify_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* S2CNewRoomAddNotify_reflection_ = NULL; } // namespace void protobuf_AssignDesc_21015_5fS2CNewRoomAddNotify_2eproto() { protobuf_AddDesc_21015_5fS2CNewRoomAddNotify_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "21015_S2CNewRoomAddNotify.proto"); GOOGLE_CHECK(file != NULL); S2CNewRoomAddNotify_descriptor_ = file->message_type(0); static const int S2CNewRoomAddNotify_offsets_[3] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(S2CNewRoomAddNotify, room_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(S2CNewRoomAddNotify, room_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(S2CNewRoomAddNotify, public__), }; S2CNewRoomAddNotify_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( S2CNewRoomAddNotify_descriptor_, S2CNewRoomAddNotify::default_instance_, S2CNewRoomAddNotify_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(S2CNewRoomAddNotify, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(S2CNewRoomAddNotify, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(S2CNewRoomAddNotify)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_21015_5fS2CNewRoomAddNotify_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( S2CNewRoomAddNotify_descriptor_, &S2CNewRoomAddNotify::default_instance()); } } // namespace void protobuf_ShutdownFile_21015_5fS2CNewRoomAddNotify_2eproto() { delete S2CNewRoomAddNotify::default_instance_; delete S2CNewRoomAddNotify_reflection_; } void protobuf_AddDesc_21015_5fS2CNewRoomAddNotify_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\03721015_S2CNewRoomAddNotify.proto\022\010Proto" "col\"I\n\023S2CNewRoomAddNotify\022\017\n\007room_id\030\001 " "\002(\r\022\021\n\troom_name\030\002 \002(\t\022\016\n\006public\030\003 \002(\010", 118); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "21015_S2CNewRoomAddNotify.proto", &protobuf_RegisterTypes); S2CNewRoomAddNotify::default_instance_ = new S2CNewRoomAddNotify(); S2CNewRoomAddNotify::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_21015_5fS2CNewRoomAddNotify_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_21015_5fS2CNewRoomAddNotify_2eproto { StaticDescriptorInitializer_21015_5fS2CNewRoomAddNotify_2eproto() { protobuf_AddDesc_21015_5fS2CNewRoomAddNotify_2eproto(); } } static_descriptor_initializer_21015_5fS2CNewRoomAddNotify_2eproto_; // =================================================================== #ifndef _MSC_VER const int S2CNewRoomAddNotify::kRoomIdFieldNumber; const int S2CNewRoomAddNotify::kRoomNameFieldNumber; const int S2CNewRoomAddNotify::kPublicFieldNumber; #endif // !_MSC_VER S2CNewRoomAddNotify::S2CNewRoomAddNotify() : ::google::protobuf::Message() { SharedCtor(); } void S2CNewRoomAddNotify::InitAsDefaultInstance() { } S2CNewRoomAddNotify::S2CNewRoomAddNotify(const S2CNewRoomAddNotify& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void S2CNewRoomAddNotify::SharedCtor() { _cached_size_ = 0; room_id_ = 0u; room_name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); public__ = false; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } S2CNewRoomAddNotify::~S2CNewRoomAddNotify() { SharedDtor(); } void S2CNewRoomAddNotify::SharedDtor() { if (room_name_ != &::google::protobuf::internal::kEmptyString) { delete room_name_; } if (this != default_instance_) { } } void S2CNewRoomAddNotify::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* S2CNewRoomAddNotify::descriptor() { protobuf_AssignDescriptorsOnce(); return S2CNewRoomAddNotify_descriptor_; } const S2CNewRoomAddNotify& S2CNewRoomAddNotify::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_21015_5fS2CNewRoomAddNotify_2eproto(); return *default_instance_; } S2CNewRoomAddNotify* S2CNewRoomAddNotify::default_instance_ = NULL; S2CNewRoomAddNotify* S2CNewRoomAddNotify::New() const { return new S2CNewRoomAddNotify; } void S2CNewRoomAddNotify::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { room_id_ = 0u; if (has_room_name()) { if (room_name_ != &::google::protobuf::internal::kEmptyString) { room_name_->clear(); } } public__ = false; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool S2CNewRoomAddNotify::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required uint32 room_id = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &room_id_))); set_has_room_id(); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_room_name; break; } // required string room_name = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_room_name: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_room_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->room_name().data(), this->room_name().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_public; break; } // required bool public = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_public: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &public__))); set_has_public_(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void S2CNewRoomAddNotify::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required uint32 room_id = 1; if (has_room_id()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->room_id(), output); } // required string room_name = 2; if (has_room_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->room_name().data(), this->room_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 2, this->room_name(), output); } // required bool public = 3; if (has_public_()) { ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->public_(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* S2CNewRoomAddNotify::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required uint32 room_id = 1; if (has_room_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->room_id(), target); } // required string room_name = 2; if (has_room_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->room_name().data(), this->room_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->room_name(), target); } // required bool public = 3; if (has_public_()) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->public_(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int S2CNewRoomAddNotify::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required uint32 room_id = 1; if (has_room_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->room_id()); } // required string room_name = 2; if (has_room_name()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->room_name()); } // required bool public = 3; if (has_public_()) { total_size += 1 + 1; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void S2CNewRoomAddNotify::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const S2CNewRoomAddNotify* source = ::google::protobuf::internal::dynamic_cast_if_available<const S2CNewRoomAddNotify*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void S2CNewRoomAddNotify::MergeFrom(const S2CNewRoomAddNotify& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_room_id()) { set_room_id(from.room_id()); } if (from.has_room_name()) { set_room_name(from.room_name()); } if (from.has_public_()) { set_public_(from.public_()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void S2CNewRoomAddNotify::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void S2CNewRoomAddNotify::CopyFrom(const S2CNewRoomAddNotify& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool S2CNewRoomAddNotify::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void S2CNewRoomAddNotify::Swap(S2CNewRoomAddNotify* other) { if (other != this) { std::swap(room_id_, other->room_id_); std::swap(room_name_, other->room_name_); std::swap(public__, other->public__); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata S2CNewRoomAddNotify::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = S2CNewRoomAddNotify_descriptor_; metadata.reflection = S2CNewRoomAddNotify_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace Protocol // @@protoc_insertion_point(global_scope)
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #define DEBUG_TYPE "vm" #include "hermes/VM/Runtime.h" #include "hermes/AST/SemValidate.h" #include "hermes/BCGen/HBC/Bytecode.h" #include "hermes/BCGen/HBC/BytecodeGenerator.h" #include "hermes/BCGen/HBC/HBC.h" #include "hermes/BCGen/HBC/SimpleBytecodeBuilder.h" #include "hermes/IR/IR.h" #include "hermes/IRGen/IRGen.h" #include "hermes/Inst/Builtins.h" #include "hermes/Parser/JSParser.h" #include "hermes/Platform/Logging.h" #include "hermes/Runtime/Libhermes.h" #include "hermes/Support/CheckedMalloc.h" #include "hermes/Support/OSCompat.h" #include "hermes/Support/PerfSection.h" #include "hermes/VM/AlignedStorage.h" #include "hermes/VM/BuildMetadata.h" #include "hermes/VM/Callable.h" #include "hermes/VM/CodeBlock.h" #include "hermes/VM/Domain.h" #include "hermes/VM/FillerCell.h" #include "hermes/VM/IdentifierTable.h" #include "hermes/VM/JSError.h" #include "hermes/VM/JSLib.h" #include "hermes/VM/JSLib/RuntimeCommonStorage.h" #include "hermes/VM/Operations.h" #include "hermes/VM/PointerBase.h" #include "hermes/VM/Profiler/SamplingProfiler.h" #include "hermes/VM/RuntimeModule-inline.h" #include "hermes/VM/StackFrame-inline.h" #include "hermes/VM/StringView.h" #ifndef HERMESVM_LEAN #include "hermes/Support/MemoryBuffer.h" #endif #include "llvm/ADT/Hashing.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" namespace hermes { namespace vm { namespace { /// The maximum number of registers that can be requested in a RuntimeConfig. static constexpr uint32_t kMaxSupportedNumRegisters = UINT32_MAX / sizeof(PinnedHermesValue); // Only track I/O for buffers > 64 kB (which excludes things like // Runtime::generateSpecialRuntimeBytecode). static constexpr size_t MIN_IO_TRACKING_SIZE = 64 * 1024; static const Predefined::Str fixedPropCacheNames[(size_t)PropCacheID::_COUNT] = { #define V(id, predef) predef, PROP_CACHE_IDS(V) #undef V }; } // namespace /* static */ std::shared_ptr<Runtime> Runtime::create(const RuntimeConfig &runtimeConfig) { const GCConfig &gcConfig = runtimeConfig.getGCConfig(); GC::Size sz{gcConfig.getMinHeapSize(), gcConfig.getMaxHeapSize()}; #ifdef HERMESVM_COMPRESSED_POINTERS if (sizeof(void *) != sizeof(uint64_t)) { hermes_fatal("Non-64 bit build with contiguous backing storage on"); } // TODO(T31421960): This can become a unique_ptr with C++14 lambda // initializers. auto storageResult = StorageProvider::preAllocatedProvider( sz.storageFootprint(), sz.minStorageFootprint(), sizeof(Runtime)); if (!storageResult) { hermes_fatal((llvm::Twine("Could not allocate backing storage for heap: ") + convert_error_to_message(storageResult.getError()) + ", requested size: " + llvm::Twine(sz.storageFootprint())) .str()); } std::shared_ptr<StorageProvider> provider{std::move(storageResult.get())}; // Place Runtime in the first allocated storage. static_assert( sizeof(Runtime) <= AlignedStorage::size(), "Runtime must fit into a single storage"); auto result = provider->newStorage("hermes-runtime-segment"); if (!result) { hermes_fatal( (llvm::Twine("Could not allocate initial storage for Runtime: ") + convert_error_to_message(result.getError())) .str()); } void *storage = *result; Runtime *rt = new (storage) Runtime(provider.get(), runtimeConfig); // Return a shared pointer with a custom deleter to delete the underlying // storage of the runtime. return std::shared_ptr<Runtime>{rt, [provider](Runtime *runtime) { runtime->~Runtime(); provider->deleteStorage(runtime); }}; #else // TODO(T31421960): This can become a unique_ptr with C++14 lambda // initializers. std::shared_ptr<StorageProvider> provider{StorageProvider::mmapProvider()}; // When not using the flat address space, allocate runtime normally. Runtime *rt = new Runtime(provider.get(), runtimeConfig); // Return a shared pointer with a custom deleter to delete the underlying // storage of the runtime. return std::shared_ptr<Runtime>{rt, [provider](Runtime *runtime) { delete runtime; // Provider is only captured to keep it // alive until after the Runtime is // deleted. (void)provider; }}; #endif } CallResult<HermesValue> Runtime::getNamed( Handle<JSObject> obj, PropCacheID id) { auto *clazz = obj->getClass(this); auto *cacheEntry = &fixedPropCache_[static_cast<int>(id)]; if (LLVM_LIKELY(cacheEntry->clazz == clazz)) { return JSObject::getNamedSlotValue<PropStorage::Inline::Yes>( *obj, this, cacheEntry->slot); } auto sym = Predefined::getSymbolID(fixedPropCacheNames[static_cast<int>(id)]); NamedPropertyDescriptor desc; // Check writable and internalSetter flags since the cache slot is shared for // get/put. if (LLVM_LIKELY( JSObject::tryGetOwnNamedDescriptorFast(*obj, this, sym, desc)) && !desc.flags.accessor && desc.flags.writable && !desc.flags.internalSetter) { if (LLVM_LIKELY(!clazz->isDictionary())) { // Cache the class, id and property slot. cacheEntry->clazz = clazz; cacheEntry->slot = desc.slot; } return JSObject::getNamedSlotValue(*obj, this, desc); } return JSObject::getNamed_RJS(obj, this, sym); } ExecutionStatus Runtime::putNamedThrowOnError( Handle<JSObject> obj, PropCacheID id, HermesValue hv) { auto *clazz = obj->getClass(this); auto *cacheEntry = &fixedPropCache_[static_cast<int>(id)]; if (LLVM_LIKELY(cacheEntry->clazz == clazz)) { JSObject::setNamedSlotValue<PropStorage::Inline::Yes>( *obj, this, cacheEntry->slot, hv); return ExecutionStatus::RETURNED; } auto sym = Predefined::getSymbolID(fixedPropCacheNames[static_cast<int>(id)]); NamedPropertyDescriptor desc; if (LLVM_LIKELY( JSObject::tryGetOwnNamedDescriptorFast(*obj, this, sym, desc)) && !desc.flags.accessor && desc.flags.writable && !desc.flags.internalSetter) { if (LLVM_LIKELY(!clazz->isDictionary())) { // Cache the class and property slot. cacheEntry->clazz = clazz; cacheEntry->slot = desc.slot; } JSObject::setNamedSlotValue(*obj, this, desc.slot, hv); return ExecutionStatus::RETURNED; } return JSObject::putNamed_RJS( obj, this, sym, makeHandle(hv), PropOpFlags().plusThrowOnError()) .getStatus(); } Runtime::Runtime(StorageProvider *provider, const RuntimeConfig &runtimeConfig) // The initial heap size can't be larger than the max. : enableEval(runtimeConfig.getEnableEval()), verifyEvalIR(runtimeConfig.getVerifyEvalIR()), heap_( getMetadataTable(), this, this, runtimeConfig.getGCConfig(), runtimeConfig.getCrashMgr(), provider), jitContext_(runtimeConfig.getEnableJIT(), (1 << 20) * 8, (1 << 20) * 32), hasES6Symbol_(runtimeConfig.getES6Symbol()), shouldRandomizeMemoryLayout_(runtimeConfig.getRandomizeMemoryLayout()), bytecodeWarmupPercent_(runtimeConfig.getBytecodeWarmupPercent()), trackIO_(runtimeConfig.getTrackIO()), vmExperimentFlags_(runtimeConfig.getVMExperimentFlags()), runtimeStats_(runtimeConfig.getEnableSampledStats()), commonStorage_(createRuntimeCommonStorage()), stackPointer_(), crashMgr_(runtimeConfig.getCrashMgr()), crashCallbackKey_( crashMgr_->registerCallback([this](int fd) { crashCallback(fd); })) { assert( (void *)this == (void *)(HandleRootOwner *)this && "cast to HandleRootOwner should be no-op"); auto maxNumRegisters = runtimeConfig.getMaxNumRegisters(); if (LLVM_UNLIKELY(maxNumRegisters > kMaxSupportedNumRegisters)) { hermes_fatal("RuntimeConfig maxNumRegisters too big"); } registerStack_ = runtimeConfig.getRegisterStack(); if (!registerStack_) { // registerStack_ should be allocated with malloc instead of new so that the // default constructors don't run for the whole stack space. const auto numBytesForRegisters = sizeof(PinnedHermesValue) * maxNumRegisters; registerStack_ = static_cast<PinnedHermesValue *>(checkedMalloc(numBytesForRegisters)); crashMgr_->registerMemory(registerStack_, numBytesForRegisters); } else { freeRegisterStack_ = false; } registerStackEnd_ = registerStack_ + maxNumRegisters; if (shouldRandomizeMemoryLayout_) { const unsigned bytesOff = std::random_device()() % oscompat::page_size(); registerStackEnd_ -= bytesOff / sizeof(PinnedHermesValue); assert(registerStackEnd_ >= registerStack_ && "register stack too small"); } stackPointer_ = registerStackEnd_; // Setup the "root" stack frame. setCurrentFrameToTopOfStack(); // Allocate the "reserved" registers in the root frame. allocStack( StackFrameLayout::CalleeExtraRegistersAtStart, HermesValue::encodeUndefinedValue()); // Initialize Predefined Strings. // This function does not do any allocations. initPredefinedStrings(); // Initialize special code blocks pointing to their own runtime module. // specialCodeBlockRuntimeModule_ will be owned by runtimeModuleList_. RuntimeModuleFlags flags; flags.hidesEpilogue = true; specialCodeBlockDomain_ = Domain::create(this).getHermesValue(); specialCodeBlockRuntimeModule_ = RuntimeModule::createUninitialized( this, Handle<Domain>::vmcast(&specialCodeBlockDomain_), flags); assert( &runtimeModuleList_.back() == specialCodeBlockRuntimeModule_ && "specialCodeBlockRuntimeModule_ not added to runtimeModuleList_"); // At this point, allocations can begin, as all the roots are markable. // Initialize the pre-allocated character strings. initCharacterStrings(); GCScope scope(this); // Explicitly initialize the specialCodeBlockRuntimeModule_ without CJS // modules. specialCodeBlockRuntimeModule_->initializeWithoutCJSModulesMayAllocate( hbc::BCProviderFromBuffer::createBCProviderFromBuffer( generateSpecialRuntimeBytecode()) .first); emptyCodeBlock_ = specialCodeBlockRuntimeModule_->getCodeBlockMayAllocate(0); returnThisCodeBlock_ = specialCodeBlockRuntimeModule_->getCodeBlockMayAllocate(1); // Initialize the root hidden class. rootClazz_ = ignoreAllocationFailure(HiddenClass::createRoot(this)); rootClazzRawPtr_ = vmcast<HiddenClass>(rootClazz_); // Initialize the global object. global_ = JSObject::create(this, Handle<JSObject>(this, nullptr)).getHermesValue(); initGlobalObject(this); // Once the global object has been initialized, populate the builtins table. initBuiltinTable(); stringCycleCheckVisited_ = ignoreAllocationFailure(ArrayStorage::create(this, 8)); // Set the prototype of the global object to the standard object prototype, // which has now been defined. ignoreAllocationFailure(JSObject::setParent( vmcast<JSObject>(global_), this, vmcast<JSObject>(objectPrototype))); symbolRegistry_.init(this); LLVM_DEBUG(llvm::dbgs() << "Runtime initialized\n"); samplingProfiler_ = SamplingProfiler::getInstance(); samplingProfiler_->registerRuntime(this); } Runtime::~Runtime() { samplingProfiler_->unregisterRuntime(this); heap_.finalizeAll(); crashMgr_->unregisterCallback(crashCallbackKey_); if (freeRegisterStack_) { crashMgr_->unregisterMemory(registerStack_); ::free(registerStack_); } // Remove inter-module dependencies so we can delete them in any order. for (auto &module : runtimeModuleList_) { module.prepareForRuntimeShutdown(); } while (!runtimeModuleList_.empty()) { // Calling delete will automatically remove it from the list. delete &runtimeModuleList_.back(); } } /// A helper class used to measure the duration of GC marking different roots. /// It accumulates the times in \c Runtime::markRootsPhaseTimes[] and \c /// Runtime::totalMarkRootsTime. class Runtime::MarkRootsPhaseTimer { public: MarkRootsPhaseTimer(Runtime *rt, Runtime::MarkRootsPhase phase) : rt_(rt), phase_(phase), start_(std::chrono::steady_clock::now()) { if (static_cast<unsigned>(phase) == 0) { // The first phase; record the start as the start of markRoots. rt_->startOfMarkRoots_ = start_; } } ~MarkRootsPhaseTimer() { auto tp = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed = (tp - start_); start_ = tp; unsigned index = static_cast<unsigned>(phase_); rt_->markRootsPhaseTimes_[index] += elapsed.count(); if (index + 1 == static_cast<unsigned>(Runtime::MarkRootsPhase::NumPhases)) { std::chrono::duration<double> totalElapsed = (tp - rt_->startOfMarkRoots_); rt_->totalMarkRootsTime_ += totalElapsed.count(); } } private: Runtime *rt_; MarkRootsPhase phase_; std::chrono::time_point<std::chrono::steady_clock> start_; }; void Runtime::markRoots( GC *gc, SlotAcceptorWithNames &acceptor, bool markLongLived) { // The body of markRoots should be sequence of blocks, each of which // starts with the declaration of an appropriate MarkRootsPhase // instance. { MarkRootsPhaseTimer timer(this, MarkRootsPhase::Registers); for (auto *p = stackPointer_, *e = registerStackEnd_; p != e; ++p) acceptor.accept(*p); } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::RuntimeInstanceVars); acceptor.accept(thrownValue_, "@thrownValue"); acceptor.accept(nullPointer_, "@nullPointer"); acceptor.accept(rootClazz_, "@rootClass"); acceptor.acceptPtr(rootClazzRawPtr_, "@rootClass"); acceptor.accept(stringCycleCheckVisited_, "@stringCycleCheckVisited"); acceptor.accept(global_, "@global"); #ifdef HERMES_ENABLE_DEBUGGER acceptor.accept(debuggerInternalObject_, "@debuggerInternal"); #endif // HERMES_ENABLE_DEBUGGER } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::RuntimeModules); acceptor.accept(specialCodeBlockDomain_); for (auto &rm : runtimeModuleList_) rm.markRoots(acceptor, markLongLived); for (auto &entry : fixedPropCache_) { acceptor.acceptPtr(entry.clazz); } } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::CharStrings); if (markLongLived) { for (auto &hv : charStrings_) acceptor.accept(hv); } } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::Builtins); for (NativeFunction *&nf : builtins_) acceptor.accept((void *&)nf); } #ifdef MARK #error "Shouldn't have defined mark already" #endif #define MARK(field) acceptor.accept((field), "@" #field) { MarkRootsPhaseTimer timer(this, MarkRootsPhase::Prototypes); // Prototypes. MARK(objectPrototype); acceptor.acceptPtr(objectPrototypeRawPtr, "@objectPrototype"); MARK(functionPrototype); acceptor.acceptPtr(functionPrototypeRawPtr, "@functionPrototype"); MARK(stringPrototype); MARK(numberPrototype); MARK(booleanPrototype); MARK(symbolPrototype); MARK(datePrototype); MARK(arrayPrototype); acceptor.acceptPtr(arrayPrototypeRawPtr, "@arrayPrototype"); MARK(arrayBufferPrototype); MARK(dataViewPrototype); MARK(typedArrayBasePrototype); MARK(setPrototype); MARK(setIteratorPrototype); MARK(mapPrototype); MARK(mapIteratorPrototype); MARK(weakMapPrototype); MARK(weakSetPrototype); MARK(regExpPrototype); // Constructors. MARK(typedArrayBaseConstructor); // Miscellaneous. MARK(regExpLastInput); MARK(regExpLastRegExp); MARK(throwTypeErrorAccessor); MARK(arrayClass); acceptor.acceptPtr(arrayClassRawPtr, "@arrayClass"); MARK(iteratorPrototype); MARK(arrayIteratorPrototype); MARK(arrayPrototypeValues); MARK(stringIteratorPrototype); MARK(generatorFunctionPrototype); MARK(generatorPrototype); MARK(jsErrorStackAccessor); MARK(parseIntFunction); MARK(parseFloatFunction); MARK(requireFunction); #define TYPED_ARRAY(name, type) \ acceptor.accept(name##ArrayPrototype, "@" #name "ArrayPrototype"); \ acceptor.accept(name##ArrayConstructor, "@" #name "ArrayConstructor"); #include "hermes/VM/TypedArrays.def" MARK(errorConstructor); #define ALL_ERROR_TYPE(name) \ acceptor.accept(name##Prototype, "@" #name "Prototype"); #include "hermes/VM/NativeErrorTypes.def" #undef MARK } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::IdentifierTable); if (markLongLived) { identifierTable_.markIdentifiers(acceptor, &getHeap()); } } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::GCScopes); markGCScopes(acceptor); } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::WeakRefs); markWeakRefs(gc); } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::SymbolRegistry); symbolRegistry_.markRoots(acceptor); } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::SamplingProfiler); if (samplingProfiler_) { samplingProfiler_->markRoots(acceptor); } } { MarkRootsPhaseTimer timer(this, MarkRootsPhase::Custom); for (auto &fn : customMarkRootFuncs_) fn(gc, acceptor); } } void Runtime::markWeakRoots(GCBase *gc, SlotAcceptorWithNames &acceptor) { for (auto &rm : runtimeModuleList_) rm.markWeakRoots(acceptor); } void Runtime::visitIdentifiers( const std::function<void(UTF16Ref, uint32_t)> &acceptor) { identifierTable_.visitIdentifiers(acceptor); } void Runtime::printRuntimeGCStats(llvm::raw_ostream &os) const { const unsigned kNumPhases = static_cast<unsigned>(MarkRootsPhase::NumPhases); #define MARK_ROOTS_PHASE(phase) "MarkRoots_" #phase, static const char *markRootsPhaseNames[kNumPhases] = { #include "hermes/VM/MarkRootsPhases.def" }; #undef MARK_ROOTS_PHASE os << "\t\"runtime\": {\n"; os << "\t\t\"totalMarkRootsTime\": " << formatSecs(totalMarkRootsTime_).secs << ",\n"; bool first = true; for (unsigned phaseNum = 0; phaseNum < kNumPhases; phaseNum++) { if (first) { first = false; } else { os << ",\n"; } os << "\t\t\"" << markRootsPhaseNames[phaseNum] << "Time" << "\": " << formatSecs(markRootsPhaseTimes_[phaseNum]).secs; } os << "\n\t}"; } void Runtime::printHeapStats(llvm::raw_ostream &os) { getHeap().printAllCollectedStats(os); for (auto &module : getRuntimeModules()) { auto tracker = module.getBytecode()->getPageAccessTracker(); if (tracker) { tracker->printStats(os, true); os << "\n"; } } } unsigned Runtime::getSymbolsEnd() const { return identifierTable_.getSymbolsEnd(); } void Runtime::freeSymbols(const std::vector<bool> &markedSymbols) { identifierTable_.freeUnmarkedSymbols(markedSymbols); } size_t Runtime::mallocSize() const { size_t totalSize = 0; // Capacity of the register stack. totalSize += sizeof(*registerStack_) * (registerStackEnd_ - registerStack_); // IdentifierTable size totalSize += sizeof(IdentifierTable) + identifierTable_.additionalMemorySize(); // Runtime modules for (const RuntimeModule &rtm : runtimeModuleList_) { totalSize += sizeof(RuntimeModule) + rtm.additionalMemorySize(); } return totalSize; } #ifdef HERMESVM_SANITIZE_HANDLES void Runtime::potentiallyMoveHeap() { // Do a dummy allocation which could force a heap move if handle sanitization // is on. FillerCell::create(this, sizeof(FillerCell)); } #endif void Runtime::setMockedEnvironment(const MockedEnvironment &env) { #ifdef HERMESVM_SYNTH_REPLAY getCommonStorage()->env = env; #endif } LLVM_ATTRIBUTE_NOINLINE static CallResult<HermesValue> interpretFunctionWithRandomStack( Runtime *runtime, CodeBlock *globalCode) { static void *volatile dummy; const unsigned amount = std::random_device()() % oscompat::page_size(); // Prevent compiler from optimizing alloca away by assigning to volatile dummy = alloca(amount); (void)dummy; return runtime->interpretFunction(globalCode); } CallResult<HermesValue> Runtime::run( llvm::StringRef code, llvm::StringRef sourceURL, const hbc::CompileFlags &compileFlags) { #ifdef HERMESVM_LEAN return raiseEvalUnsupported(code); #else std::unique_ptr<hermes::Buffer> buffer; if (compileFlags.lazy) { buffer.reset(new hermes::OwnedMemoryBuffer( llvm::MemoryBuffer::getMemBufferCopy(code))); } else { buffer.reset( new hermes::OwnedMemoryBuffer(llvm::MemoryBuffer::getMemBuffer(code))); } return run(std::move(buffer), sourceURL, compileFlags); #endif } CallResult<HermesValue> Runtime::run( std::unique_ptr<hermes::Buffer> code, llvm::StringRef sourceURL, const hbc::CompileFlags &compileFlags) { #ifdef HERMESVM_LEAN auto buffer = code.get(); return raiseEvalUnsupported(llvm::StringRef( reinterpret_cast<const char *>(buffer->data()), buffer->size())); #else std::unique_ptr<hbc::BCProviderFromSrc> bytecode; { PerfSection loading("Loading new JavaScript code"); loading.addArg("url", sourceURL); auto bytecode_err = hbc::BCProviderFromSrc::createBCProviderFromSrc( std::move(code), sourceURL, compileFlags); if (!bytecode_err.first) { return raiseSyntaxError(TwineChar16(bytecode_err.second)); } bytecode = std::move(bytecode_err.first); } PerfSection loading("Executing global function"); RuntimeModuleFlags rmflags; rmflags.persistent = true; return runBytecode( std::move(bytecode), rmflags, sourceURL, makeNullHandle<Environment>()); #endif } CallResult<HermesValue> Runtime::runBytecode( std::shared_ptr<hbc::BCProvider> &&bytecode, RuntimeModuleFlags flags, llvm::StringRef sourceURL, Handle<Environment> environment, Handle<> thisArg) { clearThrownValue(); auto globalFunctionIndex = bytecode->getGlobalFunctionIndex(); // TODO(T35544739): clean up the experiment after we are done. // In non-debug builds, only freeze builtins when we are in experimental groups. #ifdef NDEBUG if (vmExperimentFlags_ & (experiments::FreezeBuiltinsAndFatalOnOverride | experiments::FreezeBuiltinsAndThrowOnOverride)) { #endif if (bytecode->getBytecodeOptions().staticBuiltins && !builtinsFrozen_) { if (assertBuiltinsUnmodified() == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } freezeBuiltins(); assert(builtinsFrozen_ && "Builtins must be frozen by now."); } #ifdef NDEBUG } #endif if (flags.persistent) { persistentBCProviders_.push_back(bytecode); if (bytecodeWarmupPercent_ > 0) { // Start the warmup thread for this bytecode if it's a buffer. bytecode->startWarmup(bytecodeWarmupPercent_); } if (getVMExperimentFlags() & experiments::MAdviseRandom) { bytecode->madvise(oscompat::MAdvice::Random); } else if (getVMExperimentFlags() & experiments::MAdviseSequential) { bytecode->madvise(oscompat::MAdvice::Sequential); } } // Only track I/O for buffers > 64 kB (which excludes things like // Runtime::generateSpecialRuntimeBytecode). if (flags.persistent && trackIO_ && bytecode->getRawBuffer().size() > MIN_IO_TRACKING_SIZE) { bytecode->startPageAccessTracker(); if (!bytecode->getPageAccessTracker()) { hermesLog( "Hermes", "Failed to start bytecode I/O instrumentation, " "maybe not supported on this platform."); } } GCScope scope(this); Handle<Domain> domain = toHandle(this, Domain::create(this)); auto runtimeModuleRes = RuntimeModule::create( this, domain, std::move(bytecode), flags, sourceURL); if (LLVM_UNLIKELY(runtimeModuleRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto runtimeModule = *runtimeModuleRes; auto globalCode = runtimeModule->getCodeBlockMayAllocate(globalFunctionIndex); #ifdef HERMES_ENABLE_DEBUGGER // If the debugger is configured to pause on load, give it a chance to pause. getDebugger().willExecuteModule(runtimeModule, globalCode); #endif if (runtimeModule->hasCJSModules()) { auto requireContext = RequireContext::create( this, domain, getPredefinedStringHandle(Predefined::dotSlash)); return runRequireCall( this, requireContext, domain, *domain->getCJSModuleOffset(this, 0)); } else if (runtimeModule->hasCJSModulesStatic()) { return runRequireCall( this, makeNullHandle<RequireContext>(), domain, *domain->getCJSModuleOffset(this, 0)); } else { // Create a JSFunction which will reference count the runtime module. // Note that its handle gets registered in the scope, so we don't need to // save it. Also note that environment will often be null here, except if // this is local eval. auto funcRes = JSFunction::create( this, domain, Handle<JSObject>::vmcast(&functionPrototype), environment, globalCode); if (funcRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; ScopedNativeCallFrame newFrame{ this, 0, *funcRes, HermesValue::encodeUndefinedValue(), *thisArg}; if (LLVM_UNLIKELY(newFrame.overflowed())) return raiseStackOverflow(); return shouldRandomizeMemoryLayout_ ? interpretFunctionWithRandomStack(this, globalCode) : interpretFunction(globalCode); } } ExecutionStatus Runtime::loadSegment( std::shared_ptr<hbc::BCProvider> &&bytecode, Handle<RequireContext> requireContext, RuntimeModuleFlags flags) { GCScopeMarkerRAII marker{this}; auto domain = makeHandle(RequireContext::getDomain(this, *requireContext)); if (LLVM_UNLIKELY( RuntimeModule::create(this, domain, std::move(bytecode), flags, "") == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return ExecutionStatus::RETURNED; } void Runtime::printException(llvm::raw_ostream &os, Handle<> valueHandle) { clearThrownValue(); // Try to fetch the stack trace. CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION}; if (auto objHandle = Handle<JSObject>::dyn_vmcast(this, valueHandle)) { if (LLVM_UNLIKELY( (propRes = JSObject::getNamed_RJS( objHandle, this, Predefined::getSymbolID(Predefined::stack))) == ExecutionStatus::EXCEPTION)) { os << "exception thrown while getting stack trace\n"; return; } } SmallU16String<32> tmp; if (LLVM_UNLIKELY( propRes == ExecutionStatus::EXCEPTION || propRes->isUndefined())) { // If stack trace is unavailable, we just print error.toString. auto strRes = toString_RJS(this, valueHandle); if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) { os << "exception thrown in toString of original exception\n"; return; } strRes->get()->copyUTF16String(tmp); os << tmp << "\n"; return; } // stack trace is available, try to convert it to string. auto strRes = toString_RJS(this, makeHandle(*propRes)); if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) { os << "exception thrown in toString of stack trace\n"; return; } PseudoHandle<StringPrimitive> str = std::move(*strRes); if (str->getStringLength() == 0) { str.invalidate(); // If the final value is the empty string, // fall back to just printing the error.toString directly. auto errToStringRes = toString_RJS(this, valueHandle); if (LLVM_UNLIKELY(errToStringRes == ExecutionStatus::EXCEPTION)) { os << "exception thrown in toString of original exception\n"; return; } str = std::move(*errToStringRes); } str->copyUTF16String(tmp); os << tmp << "\n"; } Handle<HiddenClass> Runtime::getHiddenClassForPrototype( Handle<JSObject> proto) { return Handle<HiddenClass>::vmcast(&rootClazz_); } Handle<HiddenClass> Runtime::getHiddenClassForPrototype( PinnedHermesValue *proto) { return getHiddenClassForPrototype(Handle<JSObject>::vmcast(proto)); } Handle<JSObject> Runtime::getGlobal() { return Handle<JSObject>::vmcast(&global_); } std::vector<llvm::ArrayRef<uint8_t>> Runtime::getEpilogues() { std::vector<llvm::ArrayRef<uint8_t>> result; for (const auto &m : runtimeModuleList_) { if (!m.hidesEpilogue()) { result.push_back(m.getEpilogue()); } } return result; } #ifdef HERMES_ENABLE_DEBUGGER llvm::Optional<Runtime::StackFrameInfo> Runtime::stackFrameInfoByIndex( uint32_t frameIdx) const { // Locate the frame. auto frames = getStackFrames(); auto it = frames.begin(); for (; frameIdx && it != frames.end(); ++it, --frameIdx) { } if (it == frames.end()) return llvm::None; StackFrameInfo info; info.frame = *it++; info.isGlobal = it == frames.end(); return info; } /// Calculate and \return the offset between the location of the specified /// frame and the start of the stack. This value increases with every nested /// call. uint32_t Runtime::calcFrameOffset(ConstStackFrameIterator it) const { assert(it != getStackFrames().end() && "invalid frame"); return registerStackEnd_ - it->ptr(); } /// \return the offset between the location of the current frame and the /// start of the stack. This value increases with every nested call. uint32_t Runtime::getCurrentFrameOffset() const { return calcFrameOffset(getStackFrames().begin()); } #endif static ExecutionStatus raisePlaceholder(Runtime *runtime, Handle<JSError> errorObj, Handle<> message) { JSError::recordStackTrace(errorObj, runtime); JSError::setupStack(errorObj, runtime); JSError::setMessage(errorObj, runtime, message); return runtime->setThrownValue(errorObj.getHermesValue()); } /// A placeholder used to construct a Error Object that takes in a the specified /// message. static ExecutionStatus raisePlaceholder( Runtime *runtime, Handle<JSObject> prototype, Handle<> message) { GCScopeMarkerRAII gcScope{runtime}; // Create the error object, initialize stack property and set message. auto errRes = JSError::create(runtime, prototype); if (LLVM_UNLIKELY(errRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto errorObj = runtime->makeHandle<JSError>(*errRes); return raisePlaceholder(runtime, errorObj, message); } /// A placeholder used to construct a Error Object that takes in a const /// message. A new StringPrimitive is created each time. // TODO: Predefine each error message. static ExecutionStatus raisePlaceholder( Runtime *runtime, Handle<JSObject> prototype, const TwineChar16 &msg) { // Since this happens unexpectedly and rarely, don't rely on the parent // GCScope. GCScope gcScope{runtime}; SmallU16String<64> buf; msg.toVector(buf); auto strRes = StringPrimitive::create(runtime, buf); if (strRes == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto str = runtime->makeHandle<StringPrimitive>(*strRes); LLVM_DEBUG(llvm::errs() << buf.arrayRef() << "\n"); return raisePlaceholder(runtime, prototype, str); } ExecutionStatus Runtime::raiseTypeError(Handle<> message) { // Since this happens unexpectedly and rarely, don't rely on the parent // GCScope. GCScope gcScope{this}; return raisePlaceholder( this, Handle<JSObject>::vmcast(&TypeErrorPrototype), message); } ExecutionStatus Runtime::raiseTypeErrorForValue( Handle<> value, llvm::StringRef msg) { switch (value->getTag()) { case ObjectTag: return raiseTypeError(TwineChar16("Object") + msg); case StrTag: return raiseTypeError( TwineChar16("\"") + vmcast<StringPrimitive>(*value) + "\"" + msg); case BoolTag: if (value->getBool()) { return raiseTypeError(TwineChar16("true") + msg); } else { return raiseTypeError(TwineChar16("false") + msg); } case NullTag: return raiseTypeError(TwineChar16("null") + msg); case UndefinedTag: return raiseTypeError(TwineChar16("undefined") + msg); default: if (value->isNumber()) { char buf[hermes::NUMBER_TO_STRING_BUF_SIZE]; size_t len = numberToString( value->getNumber(), buf, hermes::NUMBER_TO_STRING_BUF_SIZE); return raiseTypeError(TwineChar16(llvm::StringRef{buf, len}) + msg); } return raiseTypeError(TwineChar16("Value") + msg); } } ExecutionStatus Runtime::raiseTypeError(const TwineChar16 &msg) { return raisePlaceholder( this, Handle<JSObject>::vmcast(&TypeErrorPrototype), msg); } ExecutionStatus Runtime::raiseSyntaxError(const TwineChar16 &msg) { return raisePlaceholder( this, Handle<JSObject>::vmcast(&SyntaxErrorPrototype), msg); } ExecutionStatus Runtime::raiseRangeError(const TwineChar16 &msg) { return raisePlaceholder( this, Handle<JSObject>::vmcast(&RangeErrorPrototype), msg); } ExecutionStatus Runtime::raiseReferenceError(const TwineChar16 &msg) { return raisePlaceholder( this, Handle<JSObject>::vmcast(&ReferenceErrorPrototype), msg); } ExecutionStatus Runtime::raiseURIError(const TwineChar16 &msg) { return raisePlaceholder( this, Handle<JSObject>::vmcast(&URIErrorPrototype), msg); } ExecutionStatus Runtime::raiseStackOverflow() { return raisePlaceholder( this, Handle<JSObject>::vmcast(&RangeErrorPrototype), "Maximum call stack size exceeded"); } ExecutionStatus Runtime::raiseQuitError() { auto res = JSError::createUncatchable( this, Handle<JSObject>::vmcast(&ErrorPrototype)); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto err = makeHandle<JSError>(*res); res = StringPrimitive::create(this, llvm::ASCIIRef{"Quit"}); if (res == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } auto str = makeHandle(*res); return raisePlaceholder(this, err, str); } ExecutionStatus Runtime::raiseEvalUnsupported(llvm::StringRef code) { return raiseSyntaxError( TwineChar16("Parsing source code unsupported: ") + code.substr(0, 32)); } CallResult<bool> Runtime::insertVisitedObject(Handle<JSObject> obj) { bool foundCycle = false; MutableHandle<ArrayStorage> stack{ this, vmcast<ArrayStorage>(stringCycleCheckVisited_)}; for (uint32_t i = 0, len = stack->size(); i < len; ++i) { if (stack->at(i).getObject() == obj.get()) { foundCycle = true; break; } } if (ArrayStorage::push_back(stack, this, obj) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } stringCycleCheckVisited_ = stack.getHermesValue(); return foundCycle; } void Runtime::removeVisitedObject(Handle<JSObject> obj) { (void)obj; auto stack = Handle<ArrayStorage>::vmcast(&stringCycleCheckVisited_); auto elem = stack->pop_back(); (void)elem; assert( elem.isObject() && elem.getObject() == obj.get() && "string cycle check: stack corrupted"); } std::unique_ptr<Buffer> Runtime::generateSpecialRuntimeBytecode() { hbc::SimpleBytecodeBuilder builder; { hbc::BytecodeInstructionGenerator bcGen; bcGen.emitLoadConstUndefined(0); bcGen.emitRet(0); builder.addFunction(1, bcGen.acquireBytecode()); } { hbc::BytecodeInstructionGenerator bcGen; bcGen.emitGetGlobalObject(0); bcGen.emitRet(0); builder.addFunction(1, bcGen.acquireBytecode()); } auto buffer = builder.generateBytecodeBuffer(); assert(buffer->size() < MIN_IO_TRACKING_SIZE); return buffer; } void Runtime::initPredefinedStrings() { assert(!getTopGCScope() && "There shouldn't be any handles allocated yet"); /// Create a buffer containing all strings. /// This ensures that all the strings live together in memory, /// and that we don't touch multiple separate pages to run this. static const char buffer[] = #define STR(name, string) string #include "hermes/VM/PredefinedStrings.def" #define SYM(name, desc) desc #include "hermes/VM/PredefinedSymbols.def" ; static const uint8_t strLengths[] = { #define STR(name, string) sizeof(string) - 1, #include "hermes/VM/PredefinedStrings.def" }; static const uint32_t hashes[] = { #define STR(name, string) constexprHashString(string), #include "hermes/VM/PredefinedStrings.def" }; static const uint8_t symLengths[] = { #define SYM(name, desc) sizeof(desc) - 1, #include "hermes/VM/PredefinedSymbols.def" }; uint32_t offset = 0; uint32_t registered = 0; (void)registered; for (uint32_t idx = 0; idx < Predefined::_IPROP_AFTER_LAST; ++idx) { SymbolID sym = identifierTable_.createNotUniquedLazySymbol(""); assert(sym == Predefined::getSymbolID((Predefined::IProp)registered++)); (void)sym; } constexpr uint32_t strCount = sizeof strLengths / sizeof strLengths[0]; static_assert( strCount == sizeof hashes / sizeof hashes[0], "Arrays should have same length"); for (uint32_t idx = 0; idx < strCount; idx++) { SymbolID sym = identifierTable_.registerLazyIdentifier( ASCIIRef{&buffer[offset], strLengths[idx]}, hashes[idx]); assert(sym == Predefined::getSymbolID((Predefined::Str)registered++)); (void)sym; offset += strLengths[idx]; } constexpr uint32_t symCount = sizeof symLengths / sizeof symLengths[0]; for (uint32_t idx = 0; idx < symCount; ++idx) { SymbolID sym = identifierTable_.createNotUniquedLazySymbol( ASCIIRef{&buffer[offset], symLengths[idx]}); assert(sym == Predefined::getSymbolID((Predefined::Sym)registered++)); (void)sym; offset += symLengths[idx]; } assert( !getTopGCScope() && "There shouldn't be any handles allocated during initializing the predefined strings"); } void Runtime::initCharacterStrings() { GCScope gc(this); auto marker = gc.createMarker(); charStrings_.reserve(256); for (char16_t ch = 0; ch < 256; ++ch) { gc.flushToMarker(marker); charStrings_.push_back(allocateCharacterString(ch).getHermesValue()); } } Handle<StringPrimitive> Runtime::allocateCharacterString(char16_t ch) { // This can in theory throw when called out of initialization phase. // However there is only that many character strings and in practice this // is not a problem. Note that we allocate these as "long-lived" objects, // so we don't have to scan the charStrings_ array in // young-generation collections. PinnedHermesValue strRes; if (LLVM_LIKELY(ch < 128)) { strRes = ignoreAllocationFailure( StringPrimitive::createLongLived(this, ASCIIRef(ch))); } else { strRes = ignoreAllocationFailure( StringPrimitive::createLongLived(this, UTF16Ref(ch))); } return makeHandle<StringPrimitive>(strRes); } Handle<StringPrimitive> Runtime::getCharacterString(char16_t ch) { if (LLVM_LIKELY(ch < 256)) return Handle<StringPrimitive>::vmcast(&charStrings_[ch]); return makeHandle<StringPrimitive>( ignoreAllocationFailure(StringPrimitive::create(this, UTF16Ref(ch)))); } // Store all object and symbol ids in a static table to conserve code size. static const struct { uint16_t object, method; #ifndef NDEBUG const char *name; #define BUILTIN_METHOD(object, method) \ {(uint16_t)Predefined::object, \ (uint16_t)Predefined::method, \ #object "::" #method}, #else #define BUILTIN_METHOD(object, method) \ {(uint16_t)Predefined::object, (uint16_t)Predefined::method}, #endif } builtinMethods[] = { #include "hermes/Inst/Builtins.def" }; static_assert( sizeof(builtinMethods) / sizeof(builtinMethods[0]) == inst::BuiltinMethod::_count, "builtin method table mismatch"); ExecutionStatus Runtime::forEachBuiltin(const std::function<ExecutionStatus( unsigned methodIndex, Predefined::Str objectName, Handle<JSObject> &object, SymbolID methodID)> &callback) { MutableHandle<JSObject> lastObject{this}; Predefined::Str lastObjectName = Predefined::_STRING_AFTER_LAST; for (unsigned methodIndex = 0; methodIndex < inst::BuiltinMethod::_count; ++methodIndex) { GCScopeMarkerRAII marker{this}; LLVM_DEBUG(llvm::dbgs() << builtinMethods[methodIndex].name << "\n"); // Find the object first, if it changed. auto objectName = (Predefined::Str)builtinMethods[methodIndex].object; if (objectName != lastObjectName) { auto objectID = Predefined::getSymbolID(objectName); auto cr = JSObject::getNamed_RJS(getGlobal(), this, objectID); assert( cr.getStatus() != ExecutionStatus::EXCEPTION && "getNamed() of builtin object failed"); assert( vmisa<JSObject>(cr.getValue()) && "getNamed() of builtin object must be an object"); lastObject = vmcast<JSObject>(cr.getValue()); lastObjectName = objectName; } // Find the method. auto methodName = (Predefined::Str)builtinMethods[methodIndex].method; auto methodID = Predefined::getSymbolID(methodName); ExecutionStatus status = callback(methodIndex, objectName, lastObject, methodID); if (status != ExecutionStatus::RETURNED) { return ExecutionStatus::EXCEPTION; } } return ExecutionStatus::RETURNED; } void Runtime::initBuiltinTable() { GCScopeMarkerRAII gcScope{this}; builtins_.resize(inst::BuiltinMethod::_count); (void)forEachBuiltin([this]( unsigned methodIndex, Predefined::Str /* objectName */, Handle<JSObject> &currentObject, SymbolID methodID) { auto cr = JSObject::getNamed_RJS(currentObject, this, methodID); assert( cr.getStatus() != ExecutionStatus::EXCEPTION && "getNamed() of builtin method failed"); assert( vmisa<NativeFunction>(cr.getValue()) && "getNamed() of builtin method must be a NativeFunction"); builtins_[methodIndex] = vmcast<NativeFunction>(cr.getValue()); return ExecutionStatus::RETURNED; }); } ExecutionStatus Runtime::assertBuiltinsUnmodified() { assert(!builtinsFrozen_ && "Builtins are already frozen."); GCScope gcScope(this); return forEachBuiltin([this]( unsigned methodIndex, Predefined::Str /* objectName */, Handle<JSObject> &currentObject, SymbolID methodID) { auto cr = JSObject::getNamed_RJS(currentObject, this, methodID); assert( cr.getStatus() != ExecutionStatus::EXCEPTION && "getNamed() of builtin method failed"); // Check if the builtin is overridden. auto currentBuiltin = dyn_vmcast<NativeFunction>(cr.getValue()); if (!currentBuiltin || currentBuiltin != builtins_[methodIndex]) { return raiseTypeError( "Cannot execute a bytecode compiled with -fstatic-builtins when builtin functions are overriden."); } return ExecutionStatus::RETURNED; }); } void Runtime::freezeBuiltins() { assert(!builtinsFrozen_ && "Builtins are already frozen."); GCScope gcScope{this}; // A list storing all the object ids that we will freeze on the global object // in the end. std::vector<SymbolID> objectList; // A list storing all the method ids on the same object that we will freeze on // each object. std::vector<SymbolID> methodList; // Masks for setting the property a static builtin and read-only. PropertyFlags clearFlags; clearFlags.configurable = 1; clearFlags.writable = 1; PropertyFlags setFlags; setFlags.staticBuiltin = 1; (void)forEachBuiltin([this, &objectList, &methodList, &clearFlags, &setFlags]( unsigned methodIndex, Predefined::Str objectName, Handle<JSObject> &currentObject, SymbolID methodID) { methodList.push_back(methodID); // This is the last method on current object. if (methodIndex + 1 == inst::BuiltinMethod::_count || objectName != builtinMethods[methodIndex + 1].object) { // Store the object id in the object set. SymbolID objectID = Predefined::getSymbolID(objectName); objectList.push_back(objectID); // Freeze all methods and mark them as static builtins on the current // object. JSObject::updatePropertyFlagsWithoutTransitions( currentObject, this, clearFlags, setFlags, llvm::ArrayRef<SymbolID>(methodList)); methodList.clear(); } return ExecutionStatus::RETURNED; }); // Freeze all builtin objects and mark them as static builtins on the global // object. JSObject::updatePropertyFlagsWithoutTransitions( getGlobal(), this, clearFlags, setFlags, llvm::ArrayRef<SymbolID>(objectList)); builtinsFrozen_ = true; } uint64_t Runtime::gcStableHashHermesValue(Handle<HermesValue> value) { switch (value->getTag()) { case ObjectTag: { // For objects, because pointers can move, we need a unique ID // that does not change for each object. auto id = JSObject::getObjectID(vmcast<JSObject>(*value), this); return llvm::hash_value(id); } case StrTag: { // For strings, we hash the string content. auto strView = StringPrimitive::createStringView( this, Handle<StringPrimitive>::vmcast(value)); return llvm::hash_combine_range(strView.begin(), strView.end()); } default: assert(!value->isPointer() && "Unhandled pointer type"); if (value->isNumber() && value->getNumber() == 0) { // To normalize -0 to 0. return 0; } else { // For everything else, we just take advantage of HermesValue. return llvm::hash_value(value->getRaw()); } } } bool Runtime::symbolEqualsToStringPrim(SymbolID id, StringPrimitive *strPrim) { auto view = identifierTable_.getStringView(this, id); return strPrim->equals(view); } LLVM_ATTRIBUTE_NOINLINE void Runtime::allocStack(uint32_t count, HermesValue initValue) { // Note: it is important that allocStack be defined out-of-line. If inline, // constants are propagated into initValue, which enables clang to use // memset_pattern_16. This ends up being a significant loss as it is an // indirect call. allocUninitializedStack(count); // Initialize the new registers. std::uninitialized_fill_n(stackPointer_, count, initValue); } void Runtime::dumpCallFrames(llvm::raw_ostream &OS) { OS << "== Call Frames ==\n"; const PinnedHermesValue *next = getStackPointer(); unsigned i = 0; for (StackFramePtr sf : getStackFrames()) { OS << i++ << " "; if (auto *closure = sf.getCalleeClosure()) { OS << cellKindStr(closure->getKind()) << " "; } if (auto *cb = sf.getCalleeCodeBlock()) { OS << formatSymbolID(cb->getNameMayAllocate()) << " "; } dumpStackFrame(sf, OS, next); next = sf.ptr(); } } LLVM_ATTRIBUTE_NOINLINE void Runtime::dumpCallFrames() { dumpCallFrames(llvm::errs()); } StackRuntime::StackRuntime( StorageProvider *provider, const RuntimeConfig &config) : Runtime(provider, config) {} StackRuntime::~StackRuntime() {} /// Serialize a SymbolID. llvm::raw_ostream &operator<<( llvm::raw_ostream &OS, Runtime::FormatSymbolID format) { if (!format.symbolID.isValid()) return OS << "SymbolID(INVALID)"; OS << "SymbolID(" << (format.symbolID.isNotUniqued() ? "(External)" : "(Internal)") << format.symbolID.unsafeGetIndex() << " \""; llvm::SmallString<16> buf; format.runtime->getIdentifierTable().debugGetSymbolName( format.runtime, format.symbolID, buf); OS << buf; return OS << "\")"; } template <typename T> static std::string &llvmStreamableToString(const T &v) { // Use a static string to back this function to avoid allocations. We should // only be calling this from the crash dumper so not have to worry about // multi-threaded usage. static std::string buf; buf.clear(); llvm::raw_string_ostream strstrm(buf); strstrm << v; strstrm.flush(); return buf; } /**************************************************************************** * WARNING: This code is run after a crash. Avoid walking data structures, * doing memory allocation, or using libc etc. as much as possible ****************************************************************************/ void Runtime::crashCallback(int fd) { llvm::raw_fd_ostream jsonStream(fd, false); JSONEmitter json(jsonStream); json.openDict(); json.emitKeyValue("type", "runtime"); json.emitKeyValue( "address", llvmStreamableToString(llvm::format_hex((uintptr_t)this, 10))); json.emitKeyValue( "registerStack", llvmStreamableToString(llvm::format_hex((uintptr_t)registerStack_, 10))); json.emitKeyValue( "registerStackPointer", llvmStreamableToString(llvm::format_hex((uintptr_t)stackPointer_, 10))); json.emitKeyValue( "registerStackEnd", llvmStreamableToString( llvm::format_hex((uintptr_t)registerStackEnd_, 10))); json.emitKey("callstack"); crashWriteCallStack(json); json.closeDict(); } /**************************************************************************** * WARNING: This code is run after a crash. Avoid walking data structures, * doing memory allocation, or using libc etc. as much as possible ****************************************************************************/ void Runtime::crashWriteCallStack(JSONEmitter &json) { json.openArray(); for (auto frame : getStackFrames()) { json.openDict(); json.emitKeyValue( "StackFrameRegOffs", (uint32_t)(registerStackEnd_ - frame.ptr())); auto codeBlock = frame.getSavedCodeBlock(); if (codeBlock) { json.emitKeyValue("FunctionID", codeBlock->getFunctionID()); auto bytecodeOffs = codeBlock->getOffsetOf(frame.getSavedIP()); json.emitKeyValue("ByteCodeOffset", bytecodeOffs); auto blockSourceCode = codeBlock->getDebugSourceLocationsOffset(); if (blockSourceCode.hasValue()) { auto debugInfo = codeBlock->getRuntimeModule()->getBytecode()->getDebugInfo(); auto sourceLocation = debugInfo->getLocationForAddress( blockSourceCode.getValue(), bytecodeOffs); if (sourceLocation) { auto file = debugInfo->getFilenameByID(sourceLocation->filenameId); llvm::SmallString<256> srcLocStorage; json.emitKeyValue( "SourceLocation", (llvm::Twine(file) + llvm::Twine(":") + llvm::Twine(sourceLocation->line) + llvm::Twine(":") + llvm::Twine(sourceLocation->column)) .toStringRef(srcLocStorage)); } } } else { json.emitKeyValue("NativeCode", true); } json.closeDict(); // frame } json.closeArray(); // frames } std::string Runtime::getCallStackNoAlloc() { std::string res; // We can't get the IP of the leaf frame. For subsequent frames, we'll get // the IP of the caller at the end of the iteration, so that it will be // correct. const Inst *ip = nullptr; // Note that the order of iteration is youngest (leaf) frame to oldest. for (auto frame : getStackFrames()) { auto codeBlock = frame->getCalleeCodeBlock(); if (codeBlock) { std::string funcName; if (codeBlock->getNameString(this, funcName)) { res += funcName; } else { res += "<UTF16 string>"; } if (ip != nullptr) { auto bytecodeOffs = codeBlock->getOffsetOf(ip); auto blockSourceCode = codeBlock->getDebugSourceLocationsOffset(); if (blockSourceCode.hasValue()) { auto debugInfo = codeBlock->getRuntimeModule()->getBytecode()->getDebugInfo(); auto sourceLocation = debugInfo->getLocationForAddress( blockSourceCode.getValue(), bytecodeOffs); if (sourceLocation) { auto file = debugInfo->getFilenameByID(sourceLocation->filenameId); res += ": " + file + ":" + oscompat::to_string(sourceLocation->line) + ":" + oscompat::to_string(sourceLocation->column); } } } res += "\n"; } else { res += "<Native code>\n"; } // Get the ip of the caller frame -- which will then be correct for the // next iteration. ip = frame.getSavedIP(); } return res; } } // namespace vm } // namespace hermes
/** * \file QryWznmPrjPrj1NVersion.cpp * job handler for job QryWznmPrjPrj1NVersion (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 16 Dec 2020 */ // IP header --- ABOVE #ifdef WZNMCMBD #include <Wznmcmbd.h> #else #include <Wznmd.h> #endif #include "QryWznmPrjPrj1NVersion.h" #include "QryWznmPrjPrj1NVersion_blks.cpp" using namespace std; using namespace Sbecore; using namespace Xmlio; // IP ns.cust --- INSERT /****************************************************************************** class QryWznmPrjPrj1NVersion ******************************************************************************/ QryWznmPrjPrj1NVersion::QryWznmPrjPrj1NVersion( XchgWznm* xchg , DbsWznm* dbswznm , const ubigint jrefSup , const uint ixWznmVLocale ) : JobWznm(xchg, VecWznmVJob::QRYWZNMPRJPRJ1NVERSION, jrefSup, ixWznmVLocale) { jref = xchg->addJob(dbswznm, this, jrefSup); // IP constructor.cust1 --- INSERT xchg->addStmgr(jref, Stub::VecVNonetype::SHORT); ixWznmVQrystate = VecWznmVQrystate::OOD; // IP constructor.cust2 --- INSERT rerun(dbswznm); xchg->addClstn(VecWznmVCall::CALLWZNMSTUBCHG, jref, Clstn::VecVJobmask::SELF, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK); // IP constructor.cust3 --- INSERT // IP constructor.spec3 --- INSERT }; QryWznmPrjPrj1NVersion::~QryWznmPrjPrj1NVersion() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT void QryWznmPrjPrj1NVersion::refreshJnum() { ubigint preRefSel = xchg->getRefPreset(VecWznmVPreset::PREWZNMREFSEL, jref); stgiac.jnum = getJnumByRef(preRefSel); }; void QryWznmPrjPrj1NVersion::rerun( DbsWznm* dbswznm , const bool call ) { string sqlstr; uint cnt; ubigint preRefPrj = xchg->getRefPreset(VecWznmVPreset::PREWZNMREFPRJ, jref); xchg->removeClstns(VecWznmVCall::CALLWZNMVERMOD_PRJEQ, jref); dbswznm->tblwznmqselect->removeRstByJref(jref); dbswznm->tblwznmqprjprj1nversion->removeRstByJref(jref); sqlstr = "SELECT COUNT(TblWznmMVersion.ref)"; sqlstr += " FROM TblWznmMVersion"; sqlstr += " WHERE TblWznmMVersion.prjRefWznmMProject = " + to_string(preRefPrj) + ""; dbswznm->loadUintBySQL(sqlstr, cnt); statshr.ntot = cnt; statshr.nload = 0; if (stgiac.jnumFirstload > cnt) { if (cnt >= stgiac.nload) stgiac.jnumFirstload = cnt-stgiac.nload+1; else stgiac.jnumFirstload = 1; }; sqlstr = "INSERT INTO TblWznmQPrjPrj1NVersion(jref, jnum, ref, prjNum)"; sqlstr += " SELECT " + to_string(jref) + ", 0, TblWznmMVersion.ref, TblWznmMVersion.prjNum"; sqlstr += " FROM TblWznmMVersion"; sqlstr += " WHERE TblWznmMVersion.prjRefWznmMProject = " + to_string(preRefPrj) + ""; sqlstr += " ORDER BY prjNum ASC"; sqlstr += " LIMIT " + to_string(stgiac.nload) + " OFFSET " + to_string(stgiac.jnumFirstload-1); dbswznm->executeQuery(sqlstr); sqlstr = "UPDATE TblWznmQPrjPrj1NVersion SET jnum = qref WHERE jref = " + to_string(jref); dbswznm->executeQuery(sqlstr); ixWznmVQrystate = VecWznmVQrystate::UTD; statshr.jnumFirstload = stgiac.jnumFirstload; fetch(dbswznm); if (call) xchg->triggerCall(dbswznm, VecWznmVCall::CALLWZNMSTATCHG, jref); xchg->addRefClstn(VecWznmVCall::CALLWZNMVERMOD_PRJEQ, jref, Clstn::VecVJobmask::ALL, 0, false, preRefPrj); }; void QryWznmPrjPrj1NVersion::fetch( DbsWznm* dbswznm ) { string sqlstr; StmgrWznm* stmgr = NULL; Stcch* stcch = NULL; WznmQPrjPrj1NVersion* rec = NULL; dbswznm->tblwznmqprjprj1nversion->loadRstByJref(jref, false, rst); statshr.nload = rst.nodes.size(); stmgr = xchg->getStmgrByJref(jref); if (stmgr) { stmgr->begin(); stcch = stmgr->stcch; stcch->clear(); for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; rec->jnum = statshr.jnumFirstload + i; rec->stubRef = StubWznm::getStubVerStd(dbswznm, rec->ref, ixWznmVLocale, Stub::VecVNonetype::SHORT, stcch); }; stmgr->commit(); stmgr->unlockAccess("QryWznmPrjPrj1NVersion", "fetch"); }; refreshJnum(); }; uint QryWznmPrjPrj1NVersion::getJnumByRef( const ubigint ref ) { uint retval = 0; WznmQPrjPrj1NVersion* rec = NULL; for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; if (rec->ref == ref) { retval = rec->jnum; break; }; }; return retval; }; ubigint QryWznmPrjPrj1NVersion::getRefByJnum( const uint jnum ) { uint ref = 0; WznmQPrjPrj1NVersion* rec = getRecByJnum(jnum); if (rec) ref = rec->ref; return ref; }; WznmQPrjPrj1NVersion* QryWznmPrjPrj1NVersion::getRecByJnum( const uint jnum ) { WznmQPrjPrj1NVersion* rec = NULL; for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; if (rec->jnum == jnum) break; }; if (rec) if (rec->jnum != jnum) rec = NULL; return rec; }; void QryWznmPrjPrj1NVersion::handleRequest( DbsWznm* dbswznm , ReqWznm* req ) { if (req->ixVBasetype == ReqWznm::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { cout << "\trerun" << endl; cout << "\tshow" << endl; } else if (req->cmd == "rerun") { req->retain = handleRerun(dbswznm); } else if (req->cmd == "show") { req->retain = handleShow(dbswznm); } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; }; }; bool QryWznmPrjPrj1NVersion::handleRerun( DbsWznm* dbswznm ) { bool retval = false; string input; cout << "\tjnumFirstload (" << stgiac.jnumFirstload << "): "; cin >> input; stgiac.jnumFirstload = atol(input.c_str()); cout << "\tnload (" << stgiac.nload << "): "; cin >> input; stgiac.nload = atol(input.c_str()); rerun(dbswznm); return retval; }; bool QryWznmPrjPrj1NVersion::handleShow( DbsWznm* dbswznm ) { bool retval = false; WznmQPrjPrj1NVersion* rec = NULL; // header row cout << "\tqref"; cout << "\tjref"; cout << "\tjnum"; cout << "\tref"; cout << "\tstubRef"; cout << "\tprjNum"; cout << endl; // record rows for (unsigned int i = 0; i < rst.nodes.size(); i++) { rec = rst.nodes[i]; cout << "\t" << rec->qref; cout << "\t" << rec->jref; cout << "\t" << rec->jnum; cout << "\t" << rec->ref; cout << "\t" << rec->stubRef; cout << "\t" << rec->prjNum; cout << endl; }; return retval; }; void QryWznmPrjPrj1NVersion::handleCall( DbsWznm* dbswznm , Call* call ) { if (call->ixVCall == VecWznmVCall::CALLWZNMVERMOD_PRJEQ) { call->abort = handleCallWznmVerMod_prjEq(dbswznm, call->jref); } else if ((call->ixVCall == VecWznmVCall::CALLWZNMSTUBCHG) && (call->jref == jref)) { call->abort = handleCallWznmStubChgFromSelf(dbswznm); }; }; bool QryWznmPrjPrj1NVersion::handleCallWznmVerMod_prjEq( DbsWznm* dbswznm , const ubigint jrefTrig ) { bool retval = false; if (ixWznmVQrystate != VecWznmVQrystate::OOD) { ixWznmVQrystate = VecWznmVQrystate::OOD; xchg->triggerCall(dbswznm, VecWznmVCall::CALLWZNMSTATCHG, jref); }; return retval; }; bool QryWznmPrjPrj1NVersion::handleCallWznmStubChgFromSelf( DbsWznm* dbswznm ) { bool retval = false; // IP handleCallWznmStubChgFromSelf --- INSERT return retval; };
// // UnityInterstitialAd.cpp // ee_x // // Created by Zinge on 10/10/17. // // #include "ee/unity_ads/private/UnityInterstitialAd.hpp" #include <cassert> #include <ee/ads/internal/IAsyncHelper.hpp> #include <ee/core/ILogger.hpp> #include <ee/core/NoAwait.hpp> #include <ee/core/Task.hpp> #include <ee/core/Utils.hpp> #include "ee/unity_ads/private/UnityAdsBridge.hpp" namespace ee { namespace unity_ads { using Self = InterstitialAd; Self::InterstitialAd( ILogger& logger, const std::shared_ptr<ads::IAsyncHelper<AdResult>>& displayer, Bridge* plugin, const std::string& adId) : logger_(logger) , displayer_(displayer) , plugin_(plugin) , adId_(adId) { logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId_.c_str()); } Self::~InterstitialAd() = default; void Self::destroy() { logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId_.c_str()); plugin_->destroyFullScreenAd(adId_); } bool Self::isLoaded() const { return plugin_->hasRewardedAd(adId_); } Task<bool> Self::load() { noAwait([this]() -> Task<> { // co_await plugin_->loadRewardedAd(adId_); }); // Should return whether this ad is loaded. co_return isLoaded(); } Task<AdResult> Self::show() { logger_.debug("%s: adId = %s displaying = %s", __PRETTY_FUNCTION__, adId_.c_str(), core::toString(displayer_->isProcessing()).c_str()); auto result = co_await displayer_->process( [this] { // plugin_->showRewardedAd(adId_); }, [](AdResult result) { // OK. }); co_return result; } void Self::onLoaded() { logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId_.c_str()); dispatchEvent([](auto&& observer) { if (observer.onLoaded) { observer.onLoaded(); } }); } void Self::onFailedToShow(const std::string& message) { logger_.debug("%s: adId = %s displaying = %s message = %s", __PRETTY_FUNCTION__, adId_.c_str(), core::toString(displayer_->isProcessing()).c_str(), message.c_str()); if (displayer_->isProcessing()) { displayer_->resolve(AdResult::Failed); } else { logger_.error("%s: this ad is expected to be displaying", __PRETTY_FUNCTION__); assert(false); } } void Self::onClosed() { logger_.debug("%s: adId = %s displaying = %s", __PRETTY_FUNCTION__, adId_.c_str(), core::toString(displayer_->isProcessing()).c_str()); if (displayer_->isProcessing()) { displayer_->resolve(AdResult::Completed); } else { logger_.error("%s: this ad is expected to be displaying", __PRETTY_FUNCTION__); assert(false); } } } // namespace unity_ads } // namespace ee
// Copyright 2019 The Fuchsia 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 "gtest/gtest.h" #include "interception_workflow_test.h" namespace fidlcat { // zx_fifo_create tests. std::unique_ptr<SystemCallTest> ZxFifoCreate(int64_t result, std::string_view result_name, size_t elem_count, size_t elem_size, uint32_t options, zx_handle_t* out0, zx_handle_t* out1) { auto value = std::make_unique<SystemCallTest>("zx_fifo_create", result, result_name); value->AddInput(elem_count); value->AddInput(elem_size); value->AddInput(options); value->AddInput(reinterpret_cast<uint64_t>(out0)); value->AddInput(reinterpret_cast<uint64_t>(out1)); return value; } #define FIFO_CREATE_DISPLAY_TEST_CONTENT(result, expected) \ zx_handle_t out0 = kHandleOut; \ zx_handle_t out1 = kHandleOut2; \ PerformDisplayTest("$plt(zx_fifo_create)", ZxFifoCreate(result, #result, 4, 3, 0, &out0, &out1), \ expected); #define FIFO_CREATE_DISPLAY_TEST(name, errno, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { FIFO_CREATE_DISPLAY_TEST_CONTENT(errno, expected); } \ TEST_F(InterceptionWorkflowTestArm, name) { FIFO_CREATE_DISPLAY_TEST_CONTENT(errno, expected); } FIFO_CREATE_DISPLAY_TEST(ZxFifoCreate, ZX_OK, "\n" "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_fifo_create(" "elem_count:\x1B[32msize_t\x1B[0m: \x1B[34m4\x1B[0m, " "elem_size:\x1B[32msize_t\x1B[0m: \x1B[34m3\x1B[0m, " "options:\x1B[32muint32\x1B[0m: \x1B[34m0\x1B[0m)\n" " -> \x1B[32mZX_OK\x1B[0m (" "out0:\x1B[32mhandle\x1B[0m: \x1B[31mbde90caf\x1B[0m, " "out1:\x1B[32mhandle\x1B[0m: \x1B[31mbde90222\x1B[0m)\n"); // zx_fifo_read tests. std::unique_ptr<SystemCallTest> ZxFifoRead(int64_t result, std::string_view result_name, zx_handle_t handle, size_t elem_size, void* data, size_t count, size_t* actual_count) { auto value = std::make_unique<SystemCallTest>("zx_fifo_read", result, result_name); value->AddInput(handle); value->AddInput(elem_size); value->AddInput(reinterpret_cast<uint64_t>(data)); value->AddInput(count); value->AddInput(reinterpret_cast<uint64_t>(actual_count)); return value; } #define FIFO_READ_DISPLAY_TEST_CONTENT(result, expected) \ constexpr size_t kElemSize = 4; \ std::vector<uint8_t> buffer; \ for (int i = 0; i < 20; ++i) { \ buffer.emplace_back(i); \ } \ size_t actual_count = buffer.size() / kElemSize; \ PerformDisplayTest( \ "$plt(zx_fifo_read)", \ ZxFifoRead(result, #result, kHandle, kElemSize, buffer.data(), 10, &actual_count), \ expected); #define FIFO_READ_DISPLAY_TEST(name, errno, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { FIFO_READ_DISPLAY_TEST_CONTENT(errno, expected); } \ TEST_F(InterceptionWorkflowTestArm, name) { FIFO_READ_DISPLAY_TEST_CONTENT(errno, expected); } FIFO_READ_DISPLAY_TEST( ZxFifoRead, ZX_OK, "\n" "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_fifo_read(" "handle:\x1B[32mhandle\x1B[0m: \x1B[31mcefa1db0\x1B[0m, " "elem_size:\x1B[32msize_t\x1B[0m: \x1B[34m4\x1B[0m, " "count:\x1B[32msize_t\x1B[0m: \x1B[34m10\x1B[0m)\n" " -> \x1B[32mZX_OK\x1B[0m (actual:\x1B[32msize_t\x1B[0m: \x1B[34m5\x1B[0m/\x1B[34m10\x1B[0m)\n" " data:\x1B[32muint8\x1B[0m: " "\x1B[34m00\x1B[0m, \x1B[34m01\x1B[0m, \x1B[34m02\x1B[0m, \x1B[34m03\x1B[0m, " "\x1B[34m04\x1B[0m, \x1B[34m05\x1B[0m, \x1B[34m06\x1B[0m, \x1B[34m07\x1B[0m, " "\x1B[34m08\x1B[0m, \x1B[34m09\x1B[0m, \x1B[34m0a\x1B[0m, \x1B[34m0b\x1B[0m, " "\x1B[34m0c\x1B[0m, \x1B[34m0d\x1B[0m, \x1B[34m0e\x1B[0m, \x1B[34m0f\x1B[0m, " "\x1B[34m10\x1B[0m, \x1B[34m11\x1B[0m, \x1B[34m12\x1B[0m, \x1B[34m13\x1B[0m\n"); // zx_fifo_write tests. std::unique_ptr<SystemCallTest> ZxFifoWrite(int64_t result, std::string_view result_name, zx_handle_t handle, size_t elem_size, const void* data, size_t count, size_t* actual_count) { auto value = std::make_unique<SystemCallTest>("zx_fifo_write", result, result_name); value->AddInput(handle); value->AddInput(elem_size); value->AddInput(reinterpret_cast<uint64_t>(data)); value->AddInput(count); value->AddInput(reinterpret_cast<uint64_t>(actual_count)); return value; } #define FIFO_WRITE_DISPLAY_TEST_CONTENT(result, expected) \ constexpr size_t kElemSize = 4; \ std::vector<uint8_t> buffer; \ for (int i = 0; i < 20; ++i) { \ buffer.emplace_back(i); \ } \ size_t actual_count = 2; \ PerformDisplayTest("$plt(zx_fifo_write)", \ ZxFifoWrite(result, #result, kHandle, kElemSize, buffer.data(), \ buffer.size() / kElemSize, &actual_count), \ expected); #define FIFO_WRITE_DISPLAY_TEST(name, errno, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { FIFO_WRITE_DISPLAY_TEST_CONTENT(errno, expected); } \ TEST_F(InterceptionWorkflowTestArm, name) { FIFO_WRITE_DISPLAY_TEST_CONTENT(errno, expected); } FIFO_WRITE_DISPLAY_TEST( ZxFifoWrite, ZX_OK, "\n" "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_fifo_write(" "handle:\x1B[32mhandle\x1B[0m: \x1B[31mcefa1db0\x1B[0m, " "elem_size:\x1B[32msize_t\x1B[0m: \x1B[34m4\x1B[0m, " "count:\x1B[32msize_t\x1B[0m: \x1B[34m5\x1B[0m)\n" " data:\x1B[32muint8\x1B[0m: " "\x1B[34m00\x1B[0m, \x1B[34m01\x1B[0m, \x1B[34m02\x1B[0m, \x1B[34m03\x1B[0m, " "\x1B[34m04\x1B[0m, \x1B[34m05\x1B[0m, \x1B[34m06\x1B[0m, \x1B[34m07\x1B[0m, " "\x1B[34m08\x1B[0m, \x1B[34m09\x1B[0m, \x1B[34m0a\x1B[0m, \x1B[34m0b\x1B[0m, " "\x1B[34m0c\x1B[0m, \x1B[34m0d\x1B[0m, \x1B[34m0e\x1B[0m, \x1B[34m0f\x1B[0m, " "\x1B[34m10\x1B[0m, \x1B[34m11\x1B[0m, \x1B[34m12\x1B[0m, \x1B[34m13\x1B[0m\n" " -> \x1B[32mZX_OK\x1B[0m (" "actual:\x1B[32msize_t\x1B[0m: \x1B[34m2\x1B[0m/\x1B[34m5\x1B[0m)\n"); } // namespace fidlcat
// Copyright 2022 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/managedidentities/v1/managed_identities_service.proto #include "google/cloud/managedidentities/internal/managed_identities_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/managedidentities/v1/managed_identities_service.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace managedidentities_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ManagedIdentitiesServiceLogging::ManagedIdentitiesServiceLogging( std::shared_ptr<ManagedIdentitiesServiceStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncCreateMicrosoftAdDomain( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::CreateMicrosoftAdDomainRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1:: CreateMicrosoftAdDomainRequest const& request) { return child_->AsyncCreateMicrosoftAdDomain(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } StatusOr<google::cloud::managedidentities::v1::ResetAdminPasswordResponse> ManagedIdentitiesServiceLogging::ResetAdminPassword( grpc::ClientContext& context, google::cloud::managedidentities::v1::ResetAdminPasswordRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::managedidentities::v1::ResetAdminPasswordRequest const& request) { return child_->ResetAdminPassword(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::managedidentities::v1::ListDomainsResponse> ManagedIdentitiesServiceLogging::ListDomains( grpc::ClientContext& context, google::cloud::managedidentities::v1::ListDomainsRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::managedidentities::v1::ListDomainsRequest const& request) { return child_->ListDomains(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::managedidentities::v1::Domain> ManagedIdentitiesServiceLogging::GetDomain( grpc::ClientContext& context, google::cloud::managedidentities::v1::GetDomainRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::managedidentities::v1::GetDomainRequest const& request) { return child_->GetDomain(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncUpdateDomain( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::UpdateDomainRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::UpdateDomainRequest const& request) { return child_->AsyncUpdateDomain(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncDeleteDomain( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::DeleteDomainRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::DeleteDomainRequest const& request) { return child_->AsyncDeleteDomain(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncAttachTrust( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::AttachTrustRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::AttachTrustRequest const& request) { return child_->AsyncAttachTrust(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncReconfigureTrust( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::ReconfigureTrustRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::ReconfigureTrustRequest const& request) { return child_->AsyncReconfigureTrust(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncDetachTrust( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::DetachTrustRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::DetachTrustRequest const& request) { return child_->AsyncDetachTrust(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncValidateTrust( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::ValidateTrustRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::managedidentities::v1::ValidateTrustRequest const& request) { return child_->AsyncValidateTrust(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> ManagedIdentitiesServiceLogging::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return child_->AsyncGetOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<Status> ManagedIdentitiesServiceLogging::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return child_->AsyncCancelOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace managedidentities_internal } // namespace cloud } // namespace google
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from bitcoin_like_wallet.djinni #ifndef DJINNI_GENERATED_BITCOINLIKEBLOCK_HPP #define DJINNI_GENERATED_BITCOINLIKEBLOCK_HPP #include <chrono> #include <cstdint> #include <string> namespace ledger { namespace core { namespace api { /**Class representing Bitcoin block */ class BitcoinLikeBlock { public: virtual ~BitcoinLikeBlock() {} /** *Hash of block *@return string representing hash of this block */ virtual std::string getHash() = 0; /** *Height of block in blockchain *@return 64 bits integer, height of block */ virtual int64_t getHeight() = 0; /** *Timestamp when block was mined *@return Date object, date when block was appended to blockchain */ virtual std::chrono::system_clock::time_point getTime() = 0; }; } } } // namespace ledger::core::api #endif //DJINNI_GENERATED_BITCOINLIKEBLOCK_HPP
#include "stdafx.h" #include "Config.h" #include "BaseToBotImpl.h" #include "BaseConnection.h" #include "Vision.h" #include "PeriodicTimer.h" #include "PositionMonitor.h" #include "Arduino.h" #include "Fpga.h" #include "VisionCommImpl.h" #include "Util.h" using namespace R2D2; const char CONFIG_FILE[] = "config.txt"; // Period between updates to Base (in milliseconds) const int WHEEL_POS_UPDATE_PERIOD = 200; const int POWER_UPDATE_PERIOD = 2000; const int IMU_UPDATE_PERIOD = 500; const int INVENTORY_UPDATE_PERIOD = 2000; const int RANGEFINDER_UPDATE_PERIOD = 200; int _tmain(int argc, _TCHAR* argv[]) { Log::trace("Program started"); Config config = Config::fromFile(CONFIG_FILE); Log::level = config.verbose; while (true) { try { // IO service used for async callbacks. boost::asio::io_service service; // Initialize system components. WheelController wctrl(config.wheelsComPort); HeadController hctrl(config.headComPort, config.flapComPort); BaseToBotImpl* baseToBot = new BaseToBotImpl(wctrl, hctrl, config.connTimeout, service); BaseConnection baseConn(baseToBot, config.botPort, config.basePort); Arduino arduino(config.arduinoComPort); //PowerMonitor powerMonitor(arduino, baseConn); //PeriodicTimer<PowerMonitor> powerTimer(powerMonitor, POWER_UPDATE_PERIOD, service); Fpga fpga; InventoryMonitor invMonitor(fpga, baseConn); PeriodicTimer<InventoryMonitor> invTimer(invMonitor, INVENTORY_UPDATE_PERIOD, service); //RangeFinderMonitor rfMonitor(fpga, wctrl); //PeriodicTimer<RangeFinderMonitor> rfTimer(rfMonitor, RANGEFINDER_UPDATE_PERIOD, service); // Start vision system. VisionCommImpl visionComm(baseConn, wctrl, arduino); Vision vision(visionComm, config.lidarComPort); // Add dummy work to prevent service.run() from exiting immediately. boost::asio::io_service::work work(service); service.run(); } catch (const std::runtime_error& e) { Log::error("main: runtime_error: %s", e.what()); throw; } catch (...) { Log::error("main: Unknown error"); throw; } Log::info("Restarting connection"); } }
/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file PreFlightCheck.hpp * * Check if flight is safely possible * if not prevent it and inform the user. */ #pragma once #include <uORB/topics/safety.h> #include <uORB/topics/vehicle_status_flags.h> #include <uORB/topics/vehicle_status.h> #include <drivers/drv_hrt.h> class PreFlightCheck { public: PreFlightCheck() = default; ~PreFlightCheck() = default; /** * Runs a preflight check on all sensors to see if they are properly calibrated and healthy * * The function won't fail the test if optional sensors are not found, however, * it will fail the test if optional sensors are found but not in working condition. * * @param mavlink_log_pub * Mavlink output orb handle reference for feedback when a sensor fails * @param checkMag * true if the magneteometer should be checked * @param checkAcc * true if the accelerometers should be checked * @param checkGyro * true if the gyroscopes should be checked * @param checkBaro * true if the barometer should be checked * @param checkAirspeed * true if the airspeed sensor should be checked * @param checkRC * true if the Remote Controller should be checked * @param checkGNSS * true if the GNSS receiver should be checked * @param checkPower * true if the system power should be checked **/ static bool preflightCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, vehicle_status_flags_s &status_flags, const bool checkGNSS, bool reportFailures, const bool prearm, const hrt_abstime &time_since_boot); struct arm_requirements_t { bool arm_authorization = false; bool esc_check = false; bool global_position = false; bool mission = false; }; static bool preArmCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_flags_s &status_flags, const safety_s &safety, const arm_requirements_t &arm_requirements, vehicle_status_s &status, bool report_fail = true); private: static bool magnetometerCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const uint8_t instance, const bool optional, int32_t &device_id, const bool report_fail); static bool magConsistencyCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const bool report_status); static bool accelerometerCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const uint8_t instance, const bool optional, int32_t &device_id, const bool report_fail); static bool gyroCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const uint8_t instance, const bool optional, int32_t &device_id, const bool report_fail); static bool baroCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const uint8_t instance, const bool optional, int32_t &device_id, const bool report_fail); static bool imuConsistencyCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const bool report_status); static bool airspeedCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const bool optional, const bool report_fail, const bool prearm); static int rcCalibrationCheck(orb_advert_t *mavlink_log_pub, bool report_fail, bool isVTOL); static bool powerCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_s &status, const bool report_fail, const bool prearm); static bool ekf2Check(orb_advert_t *mavlink_log_pub, vehicle_status_s &vehicle_status, const bool optional, const bool report_fail, const bool enforce_gps_required); static bool ekf2CheckStates(orb_advert_t *mavlink_log_pub, const bool report_fail); static bool failureDetectorCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_s &status, const bool report_fail, const bool prearm); static bool manualControlCheck(orb_advert_t *mavlink_log_pub, const bool report_fail); static bool airframeCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_s &status); static bool cpuResourceCheck(orb_advert_t *mavlink_log_pub, const bool report_fail); };
/* liblightify -- library to control OSRAM's LIGHTIFY Copyright (c) 2015, Tobias Frost <tobi@coldtobi.de> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** This files serves as an example how to use the C++ class (and also for me as a testbed)*/ #include <liblightify++/liblightify++.hpp> #include <iostream> #include <iomanip> using namespace std; static const char *decode_lamptype(int type) { switch (type) { case LIGHTIFY_ONOFF_PLUG: return "oo-plug"; case LIGHTIFY_DIMABLE_LIGHT: return "dim"; case LIGHTIFY_COLOUR_LIGHT: return "color"; case LIGHTIFY_EXT_COLOUR_LIGHT: return "ext-col"; case LIGHTIFY_CCT_LIGHT: return "cct"; case LIGHTIFY_4WAY_SWITCH: return "4way-sw"; default: return "unknown"; } } static const char *decode_onoff_sate(int state) { if (state < 0) return "err"; switch (state) { case 0: return "off"; case 1: return "on"; default: return "???"; } } static const char *decode_online_state(int state) { switch (state) { case LIGHTIFY_OFFLINE: return "offline"; case LIGHTIFY_ONLINE: return "online"; default: return "unknown"; } } int main(void) { int err; Lightify l("lightify", 4000); err = l.Open(); if (err < 0) cerr << "Lightify::Open failed: " << -err << " " << strerror(-err) << endl; l.ScanNodes(); Lightify_Node *node = 0; cout << "|-----------------|------------------|---------|-------|---------|-----|-----|------|-----|-----|-----|-----|---|" << endl; cout << "| Name | MAC | type | group | online | 0/1 | dim | CCT | Red | Grn | Blu | Wht | s |" << endl; cout << "|-----------------|------------------|---------|-------|---------|-----|-----|------|-----|-----|-----|-----|---|" << endl; for(int i = 0; i< l.GetNodesCount(); i++) { node = l.GetNodeAtPosX(i); cout << '|' << setw(16) << node->GetName() << " | " << setw(16) << hex << node->GetMAC() << " | " << setw(7) << decode_lamptype(node->GetLampType()) << " | " << setw(5) << dec << node->GetGroup() << " | " << setw(7) << decode_online_state(node->GetOnlineState()) << " | " << setw(3) << decode_onoff_sate(node->IsOn()) << " | " << setw(3) << node->GetBrightness() << " | " << setw(4) << node->GetCCT() << " | " << setw(3) << node->GetRed() << " | " << setw(3) << node->GetGreen() << " | " << setw(3) << node->GetBlue() << " | " << setw(3) << node->GetWhite() << " | " << setw(1) << (node->IsStale() ? '*' :' ') << " |" << endl; } cout << "|-----------------|------------------|---------|-------|---------|-----|-----|------|-----|-----|-----|-----|---|" << endl << endl; l.ScanGroups(); cout << "|------------------|--------|" << endl; cout << "| Group Name | id |" << endl; cout << "|------------------|--------|" << endl; Lightify_Group *group = NULL; for (int i = 0; i < l.GetGroupsCount(); i++) { group = l.GetGroupAtPosX(i); cout << '|' << setw(17) << group->GetName() << " | " << setw(6) << group->GetId() << " |" << endl; } cout << "|------------------|--------|" << endl; return 0; }
/*************************************************************************** * * Author: "Sjors H.W. Scheres" * MRC Laboratory of Molecular Biology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This complete copyright notice must be included in any revised version of the * source code. Additional authorship citations may be added, but existing * author citations must be preserved. ***************************************************************************/ #include <src/autopicker_mpi.h> #ifdef CUDA #include <src/gpu_utils/cuda_autopicker.h> #endif int main(int argc, char *argv[]) { AutoPickerMpi prm; try { prm.read(argc, argv); prm.initialise(); if (prm.todo_anything) { #ifdef CUDA if (prm.do_gpu) { std::stringstream didSs; didSs << "APr" << prm.getRank(); int dev_id = prm.deviceInitialise(); prm.cudaPicker = (void*) new AutoPickerCuda((AutoPickerMpi*)&prm, dev_id, didSs.str().c_str() ); ((AutoPickerCuda*)prm.cudaPicker)->run(); } else #endif prm.run(); } } catch (RelionError XE) { if (prm.verb > 0) //prm.usage(); std::cerr << XE; MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); return EXIT_FAILURE; } return EXIT_SUCCESS; }
/* * Copyright (c) 2002-2012, California Institute of Technology. * All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and/or NAS7-03001. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the California Institute of Technology (Caltech), its operating division the Jet Propulsion Laboratory (JPL), * the National Aeronautics and Space Administration (NASA), 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 CALIFORNIA INSTITUTE OF TECHNOLOGY 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. * * Portions copyright 2014-2017 Esri * * 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. */ /****************************************************************************** * * Project: Meta Raster File Format Driver Implementation, Dataset * Purpose: Implementation of GDAL dataset * * Author: Lucian Plesea, Lucian.Plesea@jpl.nasa.gov, lplesea@esri.com * ****************************************************************************** * * The MRF dataset and the band are closely tied together, they should be * considered a single class, or a class (dataset) with extensions (bands). * * ****************************************************************************/ #include "marfa.h" #include "cpl_multiproc.h" /* for CPLSleep() */ #include <gdal_priv.h> #include <assert.h> #include <algorithm> #include <vector> CPL_CVSID("$Id$") using std::vector; using std::string; NAMESPACE_MRF_START #if GDAL_VERSION_MAJOR >= 2 #define BOOLTEST CPLTestBool #else #define BOOLTEST CSLTestBoolean #endif // Initialize as invalid GDALMRFDataset::GDALMRFDataset() : zslice(0), idxSize(0), clonedSource(FALSE), nocopy(FALSE), bypass_cache(BOOLTEST(CPLGetConfigOption("MRF_BYPASSCACHING", "FALSE"))), mp_safe(FALSE), hasVersions(FALSE), verCount(0), bCrystalized(TRUE), // Assume not in create mode spacing(0), no_errors(0), missing(0), poSrcDS(nullptr), level(-1), cds(nullptr), scale(0.0), pbuffer(nullptr), pbsize(0), tile(ILSize()), bdirty(0), bGeoTransformValid(TRUE), poColorTable(nullptr), Quality(0) { // X0 Xx Xy Y0 Yx Yy double gt[6] = { 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; memcpy(GeoTransform, gt, sizeof(gt)); ifp.FP = dfp.FP = nullptr; dfp.acc = GF_Read; ifp.acc = GF_Read; } bool GDALMRFDataset::SetPBuffer(unsigned int sz) { if (sz == 0) { CPLFree(pbuffer); pbuffer = nullptr; } void* pbufferNew = VSIRealloc(pbuffer, sz); if( pbufferNew == nullptr ) { CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate %u bytes", sz); return false; } pbuffer = pbufferNew; pbsize = (pbuffer == nullptr) ? 0 : sz; return true; } // // Called by dataset destructor or at GDAL termination, to avoid // closing datasets whose drivers have already been unloaded // int GDALMRFDataset::CloseDependentDatasets() { int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets(); if (poSrcDS) { bHasDroppedRef = TRUE; GDALClose(reinterpret_cast<GDALDatasetH>(poSrcDS)); poSrcDS = nullptr; } if (cds) { bHasDroppedRef = TRUE; GDALClose(reinterpret_cast<GDALDatasetH>(cds)); cds = nullptr; } return bHasDroppedRef; } GDALMRFDataset::~GDALMRFDataset() { // Make sure everything gets written GDALMRFDataset::FlushCache(); GDALMRFDataset::CloseDependentDatasets(); if (ifp.FP) VSIFCloseL(ifp.FP); if (dfp.FP) VSIFCloseL(dfp.FP); delete poColorTable; // CPLFree ignores being called with NULL CPLFree(pbuffer); pbsize = 0; } #ifdef unused /* *\brief Called before the IRaster IO gets called * * * */ CPLErr GDALMRFDataset::AdviseRead(int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eDT, int nBandCount, int *panBandList, char **papszOptions) { CPLDebug("MRF_IO", "AdviseRead %d, %d, %d, %d, bufsz %d,%d,%d\n", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBandCount); return CE_None; } #endif /* *\brief Format specific RasterIO, may be bypassed by BlockBasedRasterIO by setting * GDAL_FORCE_CACHING to Yes, in which case the band ReadBlock and WriteBLock are called * directly * * */ CPLErr GDALMRFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int *panBandMap, #if GDAL_VERSION_MAJOR >= 2 GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg* psExtraArgs #else int nPixelSpace, int nLineSpace, int nBandSpace #endif ) { CPLDebug("MRF_IO", "IRasterIO %s, %d, %d, %d, %d, bufsz %d,%d,%d strides P %d, L %d, B %d \n", eRWFlag == GF_Write ? "Write" : "Read", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBandCount, static_cast<int>(nPixelSpace), static_cast<int>(nLineSpace), static_cast<int>(nBandSpace)); // // Call the parent implementation, which splits it into bands and calls their IRasterIO // return GDALPamDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace #if GDAL_VERSION_MAJOR >= 2 ,psExtraArgs #endif ); } /** *\brief Build some overviews * * if nOverviews is 0, erase the overviews (reduce to base image only) */ CPLErr GDALMRFDataset::IBuildOverviews( const char * pszResampling, int nOverviews, int * panOverviewList, int nBandsIn, int * panBandList, GDALProgressFunc pfnProgress, void * pProgressData) { CPLErr eErr = CE_None; CPLDebug("MRF_OVERLAY", "IBuildOverviews %d, bands %d\n", nOverviews, nBandsIn); if( nBands != nBandsIn ) { CPLError(CE_Failure, CPLE_NotSupported, "nBands = %d not supported", nBandsIn); return CE_Failure; } /* -------------------------------------------------------------------- */ /* If we don't have write access, then create the overviews */ /* externally. */ /* -------------------------------------------------------------------- */ if (GetAccess() != GA_Update) { CPLDebug("MRF", "File open read-only, creating overviews externally."); return GDALDataset::IBuildOverviews( pszResampling, nOverviews, panOverviewList, nBands, panBandList, pfnProgress, pProgressData); } /* -------------------------------------------------------------------- */ /* If zero overviews were requested, we need to clear all */ /* existing overviews. */ /* This should just clear the index file */ /* Right now it just fails or does nothing */ /* -------------------------------------------------------------------- */ if (nOverviews == 0) { if (current.size.l == 0) return GDALDataset::IBuildOverviews(pszResampling, nOverviews, panOverviewList, nBands, panBandList, pfnProgress, pProgressData); else return CleanOverviews(); } // Array of source bands GDALRasterBand **papoBandList = (GDALRasterBand **)CPLCalloc(sizeof(void*), nBands); // Array of destination bands GDALRasterBand **papoOverviewBandList = (GDALRasterBand **)CPLCalloc(sizeof(void*), nBands); // Triple level pointer, that's what GDAL ROMB wants GDALRasterBand ***papapoOverviewBands = (GDALRasterBand ***)CPLCalloc(sizeof(void*), nBands); int* panOverviewListNew = (int*)CPLMalloc( sizeof(int) * nOverviews ); memcpy( panOverviewListNew, panOverviewList, sizeof(int) * nOverviews ); try { // Throw an error code, to make sure memory gets freed properly // Modify the metadata file if it doesn't already have the Rset model set if (0.0 == scale) { CPLXMLNode *config = ReadConfig(); try { const char* model = CPLGetXMLValue(config, "Rsets.model", "uniform"); if (!EQUAL(model, "uniform")) { CPLError(CE_Failure, CPLE_AppDefined, "MRF:IBuildOverviews, Overviews not implemented for model %s", model); throw CE_Failure; } // The scale value is the same as first overview scale = strtod(CPLGetXMLValue(config, "Rsets.scale", CPLString().Printf("%d", panOverviewList[0]).c_str()), nullptr); if (static_cast<int>(scale) != 2 && (EQUALN("Avg", pszResampling, 3) || EQUALN("Nnb", pszResampling, 3))) { CPLError(CE_Failure, CPLE_IllegalArg, "MRF internal resampling only works for a scale factor of two"); throw CE_Failure; } // Initialize the empty overlays, all of them for a given scale // They could already exist, in which case they are not erased idxSize = AddOverviews(int(scale)); if (!CheckFileSize(current.idxfname, idxSize, GA_Update)) { CPLError(CE_Failure, CPLE_AppDefined, "MRF: Can't extend index file"); throw CE_Failure; } // Set the uniform node, in case it was not set before, and save the new configuration CPLSetXMLValue(config, "Rsets.#model", "uniform"); CPLSetXMLValue(config, "Rsets.#scale", CPLString().Printf("%g", scale).c_str()); if (!WriteConfig(config)) { CPLError(CE_Failure, CPLE_AppDefined, "MRF: Can't rewrite the metadata file"); throw CE_Failure; } CPLDestroyXMLNode(config); config = nullptr; } catch (const CPLErr& ) { CPLDestroyXMLNode(config); throw; // Rethrow } // To avoid issues with blacks overviews, generate all of them // if the user asked for a couple of overviews in the correct sequence // and starting with the lowest one if( !EQUAL(pszResampling, "NONE") && nOverviews != GetRasterBand(1)->GetOverviewCount() && BOOLTEST(CPLGetConfigOption("MRF_ALL_OVERVIEW_LEVELS", "YES")) ) { bool bIncreasingPowers = (panOverviewList[0] == static_cast<int>(scale)); for (int i = 1; i < nOverviews; i++) bIncreasingPowers = bIncreasingPowers && (panOverviewList[i] == static_cast<int>(scale * panOverviewList[i - 1])); int ovrcount = GetRasterBand(1)->GetOverviewCount(); if (bIncreasingPowers && nOverviews != ovrcount) { CPLDebug("MRF", "Generating %d levels instead of the %d requested", ovrcount, nOverviews); nOverviews = ovrcount; panOverviewListNew = reinterpret_cast<int*>(CPLRealloc(panOverviewListNew, sizeof(int) * nOverviews )); panOverviewListNew[0] = static_cast<int>(scale); for (int i = 1; i < nOverviews; i++) panOverviewListNew[i] = static_cast<int>(scale * panOverviewListNew[i - 1]); } } } if (static_cast<int>(scale) != 2 && (EQUALN("Avg", pszResampling, 3) || EQUALN("Nnb", pszResampling, 3))) { CPLError(CE_Failure, CPLE_IllegalArg, "MRF internal resampling only works for a scale factor of two"); throw CE_Failure; } for (int i = 0; i < nOverviews; i++) { // Verify that scales are reasonable, val/scale has to be an integer if (!IsPower(panOverviewListNew[i], scale)) { CPLError(CE_Warning, CPLE_AppDefined, "MRF:IBuildOverviews, overview factor %d is not a power of %f", panOverviewListNew[i], scale); continue; }; int srclevel = int(logbase(panOverviewListNew[i], scale) - 0.5); GDALMRFRasterBand *b = static_cast<GDALMRFRasterBand *>(GetRasterBand(1)); // Warn for requests for invalid levels if (srclevel >= b->GetOverviewCount()) { CPLError(CE_Warning, CPLE_AppDefined, "MRF:IBuildOverviews, overview factor %d is not valid for this dataset", panOverviewListNew[i]); continue; } // Generate the overview using the previous level as the source // Use "avg" flag to trigger the internal average sampling if (EQUALN("Avg", pszResampling, 3) || EQUALN("Nnb", pszResampling, 3)) { int sampling = EQUALN("Avg", pszResampling, 3) ? SAMPLING_Avg : SAMPLING_Near; // Internal, using PatchOverview if (srclevel > 0) b = static_cast<GDALMRFRasterBand *>(b->GetOverview(srclevel - 1)); eErr = PatchOverview(0, 0, b->nBlocksPerRow, b->nBlocksPerColumn, srclevel, 0, sampling); if (eErr == CE_Failure) throw eErr; } else { // // Use the GDAL method, which is slightly different for bilinear interpolation // and also handles nearest mode // // for (int iBand = 0; iBand < nBands; iBand++) { // This is the base level papoBandList[iBand] = GetRasterBand(panBandList[iBand]); // Set up the destination papoOverviewBandList[iBand] = papoBandList[iBand]->GetOverview(srclevel); // Use the previous level as the source, the overviews are 0 based // thus an extra -1 if (srclevel > 0) papoBandList[iBand] = papoBandList[iBand]->GetOverview(srclevel - 1); // Hook it up, via triple pointer level papapoOverviewBands[iBand] = &(papoOverviewBandList[iBand]); } // // Ready, generate this overview // Note that this function has a bug in GDAL, the block stepping is incorect // It can generate multiple overview in one call, // Could rewrite this loop so this function only gets called once // GDALRegenerateOverviewsMultiBand(nBands, papoBandList, 1, papapoOverviewBands, pszResampling, pfnProgress, pProgressData); } } } catch (const CPLErr& e) { eErr = e; } CPLFree(panOverviewListNew); CPLFree(papapoOverviewBands); CPLFree(papoOverviewBandList); CPLFree(papoBandList); return eErr; } /* *\brief blank separated list to vector of doubles */ static void list2vec(std::vector<double> &v, const char *pszList) { if ((pszList == nullptr) || (pszList[0] == 0)) return; char **papszTokens = CSLTokenizeString2(pszList, " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES); v.clear(); for (int i = 0; i < CSLCount(papszTokens); i++) v.push_back(CPLStrtod(papszTokens[i], nullptr)); CSLDestroy(papszTokens); } void GDALMRFDataset::SetNoDataValue(const char *pszVal) { list2vec(vNoData, pszVal); } void GDALMRFDataset::SetMinValue(const char *pszVal) { list2vec(vMin, pszVal); } void GDALMRFDataset::SetMaxValue(const char *pszVal) { list2vec(vMax, pszVal); } /** *\brief Idenfity a MRF file, lightweight * * Lightweight test, otherwise Open gets called. * */ int GDALMRFDataset::Identify(GDALOpenInfo *poOpenInfo) { if (STARTS_WITH(poOpenInfo->pszFilename, "<MRF_META>")) return TRUE; CPLString fn(poOpenInfo->pszFilename); if (fn.find(":MRF:") != string::npos) return TRUE; if (poOpenInfo->nHeaderBytes < 10) return FALSE; const char *pszHeader = reinterpret_cast<char *>(poOpenInfo->pabyHeader); fn.assign(pszHeader, pszHeader + poOpenInfo->nHeaderBytes); if (STARTS_WITH(fn, "<MRF_META>")) return TRUE; #if defined(LERC) // Could be single LERC tile if (LERC_Band::IsLerc(fn)) return TRUE; #endif return FALSE; } /** * *\brief Read the XML config tree, from file * Caller is responsible for freeing the memory * * @return NULL on failure, or the document tree on success. * */ CPLXMLNode *GDALMRFDataset::ReadConfig() const { if (fname[0] == '<') return CPLParseXMLString(fname); else return CPLParseXMLFile(fname); } /** *\brief Write the XML config tree * Caller is responsible for correctness of data * and for freeing the memory * * @param config The document tree to write * @return TRUE on success, FALSE otherwise */ int GDALMRFDataset::WriteConfig(CPLXMLNode *config) { if (fname[0] == '<') return FALSE; return CPLSerializeXMLTreeToFile(config, fname); } static void stringSplit(vector<string> & theStringVector, // Altered/returned value const string &theString, size_t start = 0, const char theDelimiter = ' ') { while( true ) { size_t end = theString.find(theDelimiter, start); if (string::npos == end) { theStringVector.push_back(theString.substr(start)); return; } theStringVector.push_back(theString.substr(start, end - start)); start = end + 1; } } // Returns the number following the prefix if it exists in one of the vector strings // Otherwise it returns the default static int getnum(const vector<string> &theStringVector, const char prefix, int def) { for (unsigned int i = 0; i < theStringVector.size(); i++) if (theStringVector[i][0] == prefix) return atoi(theStringVector[i].c_str() + 1); return def; } /** *\brief Open a MRF file * */ GDALDataset *GDALMRFDataset::Open(GDALOpenInfo *poOpenInfo) { if( !Identify(poOpenInfo) ) return nullptr; CPLXMLNode *config = nullptr; CPLErr ret = CE_None; const char* pszFileName = poOpenInfo->pszFilename; int level = -1; // All levels int version = 0; // Current int zslice = 0; string fn; // Used to parse and adjust the file name // Different ways to open an MRF if (poOpenInfo->nHeaderBytes >= 10) { const char *pszHeader = reinterpret_cast<char *>(poOpenInfo->pabyHeader); if (STARTS_WITH(pszHeader, "<MRF_META>")) // Regular file name config = CPLParseXMLFile(pszFileName); #if defined(LERC) else config = LERC_Band::GetMRFConfig(poOpenInfo); #endif } else { if (EQUALN(pszFileName, "<MRF_META>", 10)) // Content as file name config = CPLParseXMLString(pszFileName); else { // Try Ornate file name fn = pszFileName; size_t pos = fn.find(":MRF:"); if (string::npos != pos) { // Tokenize and pick known options vector<string> tokens; stringSplit(tokens, fn, pos + 5, ':'); level = getnum(tokens, 'L', -1); version = getnum(tokens, 'V', 0); zslice = getnum(tokens, 'Z', 0); fn.resize(pos); // Cut the ornamentations pszFileName = fn.c_str(); config = CPLParseXMLFile(pszFileName); } } } if (!config) return nullptr; GDALMRFDataset *ds = new GDALMRFDataset(); ds->fname = pszFileName; ds->eAccess = poOpenInfo->eAccess; ds->level = level; ds->zslice = zslice; // OpenOptions can override file name arguments ds->ProcessOpenOptions(poOpenInfo->papszOpenOptions); if (level != -1) { // Open the whole dataset, then pick one level ds->cds = new GDALMRFDataset(); ds->cds->fname = pszFileName; ds->cds->eAccess = ds->eAccess; ds->zslice = zslice; ret = ds->cds->Initialize(config); if (ret == CE_None) ret = ds->LevelInit(level); } else { ret = ds->Initialize(config); } CPLDestroyXMLNode(config); if (ret != CE_None) { delete ds; return nullptr; } // Open a single version if (version != 0) ret = ds->SetVersion(version); if (ret != CE_None) { delete ds; return nullptr; } // Tell PAM what our real file name is, to help it find the aux.xml ds->SetPhysicalFilename(pszFileName); // Don't mess with metadata after this, otherwise PAM will re-write the aux.xml ds->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Open external overviews. */ /* -------------------------------------------------------------------- */ ds->oOvManager.Initialize( ds, pszFileName ); return ds; } // Adjust the band images with the right offset, then adjust the sizes CPLErr GDALMRFDataset::SetVersion(int version) { if (!hasVersions || version > verCount) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Version number error!"); return CE_Failure; } // Size of one version index for (int bcount = 1; bcount <= nBands; bcount++) { GDALMRFRasterBand *srcband = reinterpret_cast<GDALMRFRasterBand *>(GetRasterBand(bcount)); srcband->img.idxoffset += idxSize*verCount; for (int l = 0; l < srcband->GetOverviewCount(); l++) { GDALMRFRasterBand *band = reinterpret_cast<GDALMRFRasterBand *>(srcband->GetOverview(l)); if( band != nullptr ) band->img.idxoffset += idxSize*verCount; } } hasVersions = 0; return CE_None; } CPLErr GDALMRFDataset::LevelInit(const int l) { // Test that this level does exist if (l < 0 || l >= cds->GetRasterBand(1)->GetOverviewCount()) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Overview not present!"); return CE_Failure; } GDALMRFRasterBand *srcband = reinterpret_cast<GDALMRFRasterBand *>(cds->GetRasterBand(1)->GetOverview(l)); // Copy the sizes from this level full = srcband->img; current = srcband->img; current.size.c = cds->current.size.c; scale = cds->scale; SetProjection(cds->GetProjectionRef()); SetMetadataItem("INTERLEAVE", OrderName(current.order), "IMAGE_STRUCTURE"); SetMetadataItem("COMPRESSION", CompName(current.comp), "IMAGE_STRUCTURE"); bGeoTransformValid = (CE_None == cds->GetGeoTransform(GeoTransform)); for (int i = 0; i < l + 1; i++) { GeoTransform[1] *= scale; GeoTransform[5] *= scale; } nRasterXSize = current.size.x; nRasterYSize = current.size.y; nBands = current.size.c; // Add the bands, copy constructor so they can be closed independently for (int i = 1; i <= nBands; i++) SetBand(i, new GDALMRFLRasterBand(reinterpret_cast<GDALMRFRasterBand *> (cds->GetRasterBand(i)->GetOverview(l)))); return CE_None; } // Is the string positive or not inline bool on(const char *pszValue) { if (!pszValue || pszValue[0] == 0) return false; return EQUAL(pszValue, "ON") || EQUAL(pszValue, "TRUE") || EQUAL(pszValue, "YES"); } /** *\brief Initialize the image structure and the dataset from the XML Raster node * * @param image the structure to be initialized * @param ds the parent dataset, some things get inherited * @param defimage defimage * * The structure should be initialized with the default values as much as possible * */ static CPLErr Init_Raster(ILImage &image, GDALMRFDataset *ds, CPLXMLNode *defimage) { CPLXMLNode *node; // temporary if (!defimage) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Can't find raster info"); return CE_Failure; } // Size is mandatory node = CPLGetXMLNode(defimage, "Size"); if (node) { image.size = ILSize( static_cast<int>(getXMLNum(node, "x", -1)), static_cast<int>(getXMLNum(node, "y", -1)), static_cast<int>(getXMLNum(node, "z", 1)), static_cast<int>(getXMLNum(node, "c", 1)), 0); } // Basic checks if (!node || image.size.x < 1 || image.size.y < 1 || image.size.z < 0 || image.size.c < 0 || !GDALCheckBandCount(image.size.c, FALSE)) { CPLError(CE_Failure, CPLE_AppDefined, "Raster size missing or invalid"); return CE_Failure; } // Pagesize, defaults to 512,512,1,c image.pagesize = ILSize( std::min(512, image.size.x), std::min(512, image.size.y), 1, image.size.c); node = CPLGetXMLNode(defimage, "PageSize"); if (node) { image.pagesize = ILSize( static_cast<int>(getXMLNum(node, "x", image.pagesize.x)), static_cast<int>(getXMLNum(node, "y", image.pagesize.y)), 1, // One z at a time, forced static_cast<int>(getXMLNum(node, "c", image.pagesize.c))); if( image.pagesize.x < 1 || image.pagesize.y < 1 || image.pagesize.c <= 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid PageSize"); return CE_Failure; } } // Orientation, some other systems might support something // if (!EQUAL(CPLGetXMLValue(defimage,"Orientation","TL"), "TL")) { //// GDAL only handles Top Left Images //CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Only Top-Left orientation is supported"); //return CE_Failure; // } // Page Encoding, defaults to PNG image.comp = CompToken(CPLGetXMLValue(defimage, "Compression", "PNG")); if (image.comp == IL_ERR_COMP) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Compression %s is unknown", CPLGetXMLValue(defimage, "Compression", nullptr)); return CE_Failure; } // Is there a palette? // // GDAL only supports RGB+A palette, the other modes don't work // // Format is // <Palette> // <Size>N</Size> : Optional // <Model>RGBA|RGB|CMYK|HSV|HLS|L</Model> :mandatory // <Entry idx=i c1=v1 c2=v2 c3=v3 c4=v4/> :Optional // <Entry .../> // </Palette> // the idx attribute is optional, it autoincrements // The entries are actually vertices, interpolation takes place inside // The palette starts initialized with zeros // HSV and HLS are the similar, with c2 and c3 swapped // RGB or RGBA are same // if ((image.pagesize.c == 1) && (nullptr != (node = CPLGetXMLNode(defimage, "Palette")))) { int entries = static_cast<int>(getXMLNum(node, "Size", 255)); GDALPaletteInterp eInterp = GPI_RGB; // A flag to convert from HLS to HSV CPLString pModel = CPLGetXMLValue(node, "Model", "RGB"); if ((entries > 0) && (entries < 257)) { GDALColorEntry ce_start = { 0, 0, 0, 255 }, ce_end = { 0, 0, 0, 255 }; // Create it and initialize it to nothing GDALColorTable *poColorTable = new GDALColorTable(eInterp); poColorTable->CreateColorRamp(0, &ce_start, entries - 1, &ce_end); // Read the values CPLXMLNode *p = CPLGetXMLNode(node, "Entry"); if (p) { // Initialize the first entry ce_start = GetXMLColorEntry(p); int start_idx = static_cast<int>(getXMLNum(p, "idx", 0)); if (start_idx < 0) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Palette index %d not allowed", start_idx); delete poColorTable; return CE_Failure; } poColorTable->SetColorEntry(start_idx, &ce_start); while (nullptr != (p = SearchXMLSiblings(p, "Entry"))) { // For every entry, create a ramp ce_end = GetXMLColorEntry(p); int end_idx = static_cast<int>(getXMLNum(p, "idx", start_idx + 1)); if ((end_idx <= start_idx) || (start_idx >= entries)) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Index Error at index %d", end_idx); delete poColorTable; return CE_Failure; } poColorTable->CreateColorRamp(start_idx, &ce_start, end_idx, &ce_end); ce_start = ce_end; start_idx = end_idx; } } ds->SetColorTable(poColorTable); } else { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Palette definition error"); return CE_Failure; } } // Order of increment if( image.pagesize.c != image.size.c && image.pagesize.c != 1 ) { // Fixes heap buffer overflow in GDALMRFRasterBand::ReadInterleavedBlock() // See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2884 CPLError(CE_Failure, CPLE_NotSupported, "GDAL MRF: image.pagesize.c = %d and image.size.c = %d", image.pagesize.c, image.size.c); return CE_Failure; } image.order = OrderToken(CPLGetXMLValue(defimage, "Order", (image.pagesize.c != image.size.c) ? "BAND" : "PIXEL")); if (image.order == IL_ERR_ORD) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Order %s is unknown", CPLGetXMLValue(defimage, "Order", nullptr)); return CE_Failure; } image.quality = atoi(CPLGetXMLValue(defimage, "Quality", "85")); const char * photo_val = CPLGetXMLValue(defimage, "Photometric", nullptr); if (photo_val) ds->SetPhotometricInterpretation(photo_val); if (image.quality < 0 || image.quality>99) { CPLError(CE_Warning, CPLE_AppDefined, "GDAL MRF: Quality setting error, using default of 85"); image.quality = 85; } // Data Type, use GDAL Names image.dt = GDALGetDataTypeByName( CPLGetXMLValue(defimage, "DataType", GDALGetDataTypeName(image.dt))); if (image.dt == GDT_Unknown || GDALGetDataTypeSize(image.dt) == 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Image has wrong type"); return CE_Failure; } // Check the endianness if needed, assume host order if (is_Endianess_Dependent(image.dt, image.comp)) image.nbo = on(CPLGetXMLValue(defimage, "NetByteOrder", "No")); CPLXMLNode *DataValues = CPLGetXMLNode(defimage, "DataValues"); if (nullptr != DataValues) { const char *pszValue = CPLGetXMLValue(DataValues, "NoData", nullptr); if (pszValue) ds->SetNoDataValue(pszValue); pszValue = CPLGetXMLValue(DataValues, "min", nullptr); if (pszValue) ds->SetMinValue(pszValue); pszValue = CPLGetXMLValue(DataValues, "max", nullptr); if (pszValue) ds->SetMaxValue(pszValue); } // Calculate the page size in bytes if( image.pagesize.z <= 0 || image.pagesize.x > INT_MAX / image.pagesize.y || image.pagesize.x * image.pagesize.y > INT_MAX / image.pagesize.z || image.pagesize.x * image.pagesize.y * image.pagesize.z > INT_MAX / image.pagesize.c || image.pagesize.x * image.pagesize.y * image.pagesize.z* image.pagesize.c > INT_MAX / GDALGetDataTypeSizeBytes(image.dt) ) { CPLError(CE_Failure, CPLE_AppDefined, "MRF page size too big"); return CE_Failure; } image.pageSizeBytes = GDALGetDataTypeSizeBytes(image.dt) * image.pagesize.x * image.pagesize.y * image.pagesize.z * image.pagesize.c; // Calculate the page count, including the total for the level image.pagecount = pcount(image.size, image.pagesize); if( image.pagecount.l < 0 ) { return CE_Failure; } // Data File Name and base offset image.datfname = getFname(defimage, "DataFile", ds->GetFname(), ILComp_Ext[image.comp]); image.dataoffset = static_cast<int>( getXMLNum(CPLGetXMLNode(defimage, "DataFile"), "offset", 0.0)); // Index File Name and base offset image.idxfname = getFname(defimage, "IndexFile", ds->GetFname(), ".idx"); image.idxoffset = static_cast<int>( getXMLNum(CPLGetXMLNode(defimage, "IndexFile"), "offset", 0.0)); return CE_None; } char **GDALMRFDataset::GetFileList() { char** papszFileList = nullptr; // Add the header file name if it is real VSIStatBufL sStat; if (VSIStatExL(fname, &sStat, VSI_STAT_EXISTS_FLAG) == 0) papszFileList = CSLAddString(papszFileList, fname); // These two should be real // We don't really want to add these files, since they will be erased when an mrf is overwritten // This collides with the concept that the data file never shrinks. Same goes with the index, in case // we just want to add things to it. // papszFileList = CSLAddString( papszFileList, full.datfname); // papszFileList = CSLAddString( papszFileList, full.idxfname); // if (!source.empty()) // papszFileList = CSLAddString( papszFileList, source); return papszFileList; } // Try to create all the folders in the path in sequence, ignore errors static void mkdir_r(string const &fname) { size_t loc = fname.find_first_of("\\/"); if( loc == string::npos ) return; while (true) { ++ loc; loc = fname.find_first_of("\\/", loc); if( loc == string::npos ) break; VSIMkdir(fname.substr(0, loc).c_str(), 0); } } // Returns the dataset index file or null VSILFILE *GDALMRFDataset::IdxFP() { if (ifp.FP != nullptr) return ifp.FP; // If missing is set, we already checked, there is no index if (missing) return nullptr; // If name starts with '(' it is not a real file name if (current.idxfname[0] == '(') return nullptr; const char *mode = "rb"; ifp.acc = GF_Read; if (eAccess == GA_Update || !source.empty()) { mode = "r+b"; ifp.acc = GF_Write; } ifp.FP = VSIFOpenL(current.idxfname, mode); // If file didn't open for reading and no_errors is set, just return null and make a note if (ifp.FP == nullptr && eAccess == GA_ReadOnly && no_errors) { missing = 1; return nullptr; } // need to create the index file if (ifp.FP == nullptr && !bCrystalized && (eAccess == GA_Update || !source.empty())) { mode = "w+b"; ifp.FP = VSIFOpenL(current.idxfname, mode); } if (nullptr == ifp.FP && !source.empty()) { // caching and cloning, try making the folder and attempt again mkdir_r(current.idxfname); ifp.FP = VSIFOpenL(current.idxfname, mode); } GIntBig expected_size = idxSize; if (clonedSource) expected_size *= 2; if (nullptr != ifp.FP) { if (!bCrystalized && !CheckFileSize(current.idxfname, expected_size, GA_Update)) { CPLError(CE_Failure, CPLE_AppDefined, "Can't extend the cache index file %s", current.idxfname.c_str()); return nullptr; } if (source.empty()) return ifp.FP; // Make sure the index is large enough before proceeding // Timeout in .1 seconds, can't really guarantee the accuracy // So this is about half second, should be sufficient int timeout = 5; do { if (CheckFileSize(current.idxfname, expected_size, GA_ReadOnly)) return ifp.FP; CPLSleep(0.100); /* 100 ms */ } while (--timeout); // If we get here it is a time-out CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Timeout on fetching cloned index file %s\n", current.idxfname.c_str()); return nullptr; } // If single tile, and no index file, let the caller figure it out if (IsSingleTile()) return nullptr; // Error if this is not a caching MRF if (source.empty()) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Can't open index file %s\n", current.idxfname.c_str()); return nullptr; } // Caching/Cloning MRF and index could be read only // Is this actually works, we should try again, maybe somebody else just created the file? mode = "rb"; ifp.acc = GF_Read; ifp.FP = VSIFOpenL(current.idxfname, mode); if (nullptr != ifp.FP) return ifp.FP; // Caching and index file absent, create it // Due to a race, multiple processes might do this at the same time, but that is fine ifp.FP = VSIFOpenL(current.idxfname, "wb"); if (nullptr == ifp.FP) { CPLError(CE_Failure, CPLE_AppDefined, "Can't create the MRF cache index file %s", current.idxfname.c_str()); return nullptr; } VSIFCloseL(ifp.FP); ifp.FP = nullptr; // Make it large enough for caching and for cloning if (!CheckFileSize(current.idxfname, expected_size, GA_Update)) { CPLError(CE_Failure, CPLE_AppDefined, "Can't extend the cache index file %s", current.idxfname.c_str()); return nullptr; } // Try opening it again in rw mode so we can read and write mode = "r+b"; ifp.acc = GF_Write; ifp.FP = VSIFOpenL(current.idxfname.c_str(), mode); if (nullptr == ifp.FP) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Can't reopen cache index file %s\n", full.idxfname.c_str()); return nullptr; } return ifp.FP; } // // Returns the dataset data file or null // Data file is opened either in Read or Append mode, never in straight write // VSILFILE *GDALMRFDataset::DataFP() { if (dfp.FP != nullptr) return dfp.FP; const char *mode = "rb"; dfp.acc = GF_Read; // Open it for writing if updating or if caching if (eAccess == GA_Update || !source.empty()) { mode = "a+b"; dfp.acc = GF_Write; } dfp.FP = VSIFOpenL(current.datfname, mode); if (dfp.FP) return dfp.FP; // It could be a caching MRF if (source.empty()) goto io_error; // May be there but read only, remember that it was open that way mode = "rb"; dfp.acc = GF_Read; dfp.FP = VSIFOpenL(current.datfname, mode); if (nullptr != dfp.FP) { CPLDebug("MRF_IO", "Opened %s RO mode %s\n", current.datfname.c_str(), mode); return dfp.FP; } if (source.empty()) goto io_error; // caching, maybe the folder didn't exist mkdir_r(current.datfname); mode = "a+b"; dfp.acc = GF_Write; dfp.FP = VSIFOpenL(current.datfname, mode); if (dfp.FP) return dfp.FP; io_error: dfp.FP = nullptr; CPLError(CE_Failure, CPLE_FileIO, "GDAL MRF: %s : %s", strerror(errno), current.datfname.c_str()); return nullptr; } // Builds an XML tree from the current MRF. If written to a file it becomes an MRF CPLXMLNode * GDALMRFDataset::BuildConfig() { CPLXMLNode *config = CPLCreateXMLNode(nullptr, CXT_Element, "MRF_META"); if (!source.empty()) { CPLXMLNode *psCachedSource = CPLCreateXMLNode(config, CXT_Element, "CachedSource"); // Should wrap the string in CDATA, in case it is XML CPLXMLNode *psSource = CPLCreateXMLElementAndValue(psCachedSource, "Source", source); if (clonedSource) CPLSetXMLValue(psSource, "#clone", "true"); } // Use the full size CPLXMLNode *raster = CPLCreateXMLNode(config, CXT_Element, "Raster"); // Preserve the file names if not the default ones if (full.datfname != getFname(GetFname(), ILComp_Ext[full.comp])) CPLCreateXMLElementAndValue(raster, "DataFile", full.datfname.c_str()); if (full.idxfname != getFname(GetFname(), ".idx")) CPLCreateXMLElementAndValue(raster, "IndexFile", full.idxfname.c_str()); if (spacing != 0) XMLSetAttributeVal(raster, "Spacing", static_cast<double>(spacing), "%.0f"); XMLSetAttributeVal(raster, "Size", full.size, "%.0f"); XMLSetAttributeVal(raster, "PageSize", full.pagesize, "%.0f"); if (full.comp != IL_PNG) CPLCreateXMLElementAndValue(raster, "Compression", CompName(full.comp)); if (full.dt != GDT_Byte) CPLCreateXMLElementAndValue(raster, "DataType", GDALGetDataTypeName(full.dt)); // special photometric interpretation if (!photometric.empty()) CPLCreateXMLElementAndValue(raster, "Photometric", photometric); if (!vNoData.empty() || !vMin.empty() || !vMax.empty() ) { CPLXMLNode *values = CPLCreateXMLNode(raster, CXT_Element, "DataValues"); XMLSetAttributeVal(values, "NoData", vNoData); XMLSetAttributeVal(values, "min", vMin); XMLSetAttributeVal(values, "max", vMax); } // palette, if we have one if (poColorTable != nullptr) { const char *pfrmt = "%.0f"; CPLXMLNode *pal = CPLCreateXMLNode(raster, CXT_Element, "Palette"); int sz = poColorTable->GetColorEntryCount(); if (sz != 256) XMLSetAttributeVal(pal, "Size", poColorTable->GetColorEntryCount()); // RGB or RGBA for now for (int i = 0; i < sz; i++) { CPLXMLNode *entry = CPLCreateXMLNode(pal, CXT_Element, "Entry"); const GDALColorEntry *ent = poColorTable->GetColorEntry(i); // No need to set the index, it is always from 0 no size-1 XMLSetAttributeVal(entry, "c1", ent->c1, pfrmt); XMLSetAttributeVal(entry, "c2", ent->c2, pfrmt); XMLSetAttributeVal(entry, "c3", ent->c3, pfrmt); if (ent->c4 != 255) XMLSetAttributeVal(entry, "c4", ent->c4, pfrmt); } } if (is_Endianess_Dependent(full.dt, full.comp)) // Need to set the order CPLCreateXMLElementAndValue(raster, "NetByteOrder", (full.nbo || NET_ORDER) ? "TRUE" : "FALSE"); if (full.quality > 0 && full.quality != 85) CPLCreateXMLElementAndValue(raster, "Quality", CPLString().Printf("%d", full.quality)); // Done with the raster node if (scale != 0.0) { CPLCreateXMLNode(config, CXT_Element, "Rsets"); CPLSetXMLValue(config, "Rsets.#model", "uniform"); CPLSetXMLValue(config, "Rsets.#scale", PrintDouble(scale)); } CPLXMLNode *gtags = CPLCreateXMLNode(config, CXT_Element, "GeoTags"); // Do we have an affine transform different from identity? double gt[6]; if ((GetGeoTransform(gt) == CE_None) && (gt[0] != 0 || gt[1] != 1 || gt[2] != 0 || gt[3] != 0 || gt[4] != 0 || gt[5] != 1)) { double minx = gt[0]; double maxx = gt[1] * full.size.x + minx; double maxy = gt[3]; double miny = gt[5] * full.size.y + maxy; CPLXMLNode *bbox = CPLCreateXMLNode(gtags, CXT_Element, "BoundingBox"); XMLSetAttributeVal(bbox, "minx", minx); XMLSetAttributeVal(bbox, "miny", miny); XMLSetAttributeVal(bbox, "maxx", maxx); XMLSetAttributeVal(bbox, "maxy", maxy); } const char *pszProj = GetProjectionRef(); if (pszProj && (!EQUAL(pszProj, ""))) CPLCreateXMLElementAndValue(gtags, "Projection", pszProj); if ( optlist.Count() != 0 ) { CPLString options; for (int i = 0; i < optlist.size(); i++) { options += optlist[i]; options += ' '; } options.resize(options.size() - 1); CPLCreateXMLElementAndValue(config, "Options", options); } return config; } /** * \brief Populates the dataset variables from the XML definition * * */ CPLErr GDALMRFDataset::Initialize(CPLXMLNode *config) { // We only need a basic initialization here, usually gets overwritten by the image params full.dt = GDT_Byte; full.hasNoData = false; full.NoDataValue = 0; Quality = 85; CPLErr ret = Init_Raster(full, this, CPLGetXMLNode(config, "Raster")); if (CE_None != ret) return ret; hasVersions = on(CPLGetXMLValue(config, "Raster.versioned", "no")); mp_safe = on(CPLGetXMLValue(config, "Raster.mp_safe", "no")); spacing = atoi(CPLGetXMLValue(config, "Raster.Spacing", "0")); // The zslice defined in the file wins over the oo or the file argument if (CPLGetXMLNode(config, "Raster.zslice")) zslice = atoi(CPLGetXMLValue(config, "Raster.zslice", "0")); Quality = full.quality; // Bounding box CPLXMLNode *bbox = CPLGetXMLNode(config, "GeoTags.BoundingBox"); if (nullptr != bbox) { double x0, x1, y0, y1; x0 = atof(CPLGetXMLValue(bbox, "minx", "0")); x1 = atof(CPLGetXMLValue(bbox, "maxx", "1")); y1 = atof(CPLGetXMLValue(bbox, "maxy", "1")); y0 = atof(CPLGetXMLValue(bbox, "miny", "0")); GeoTransform[0] = x0; GeoTransform[1] = (x1 - x0) / full.size.x; GeoTransform[2] = 0; GeoTransform[3] = y1; GeoTransform[4] = 0; GeoTransform[5] = (y0 - y1) / full.size.y; bGeoTransformValid = TRUE; } OGRSpatialReference oSRS; const char *pszRawProjFromXML = CPLGetXMLValue(config, "GeoTags.Projection", ""); if (strlen(pszRawProjFromXML) == 0 || oSRS.SetFromUserInput(pszRawProjFromXML) != OGRERR_NONE ) { SetProjection(""); } else { char* pszRawProj = nullptr; if( oSRS.exportToWkt(&pszRawProj) != OGRERR_NONE ) { CPLFree(pszRawProj); pszRawProj = CPLStrdup(""); } SetProjection(pszRawProj); CPLFree(pszRawProj); } // Copy the full size to current, data and index are not yet open current = full; if (current.size.z != 1) { SetMetadataItem("ZSIZE", CPLString().Printf("%d", current.size.z), "IMAGE_STRUCTURE"); SetMetadataItem("ZSLICE", CPLString().Printf("%d", zslice), "IMAGE_STRUCTURE"); // Capture the zslice in pagesize.l current.pagesize.l = zslice; // Adjust offset for base image if( full.size.z <= 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Invalid Raster.z value"); return CE_Failure; } if (zslice >= full.size.z) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Invalid z slice"); return CE_Failure; } current.idxoffset += (current.pagecount.l / full.size.z) * zslice * sizeof(ILIdx); } // Dataset metadata setup SetMetadataItem("INTERLEAVE", OrderName(current.order), "IMAGE_STRUCTURE"); SetMetadataItem("COMPRESSION", CompName(current.comp), "IMAGE_STRUCTURE"); if (is_Endianess_Dependent(current.dt, current.comp)) SetMetadataItem("NETBYTEORDER", current.nbo ? "TRUE" : "FALSE", "IMAGE_STRUCTURE"); // Open the files for the current image, either RW or RO nRasterXSize = current.size.x; nRasterYSize = current.size.y; nBands = current.size.c; if (!nBands || !nRasterXSize || !nRasterYSize) { CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Image size missing"); return CE_Failure; } // Pick up the source data image, if there is one source = CPLGetXMLValue(config, "CachedSource.Source", ""); // Is it a clone? clonedSource = on(CPLGetXMLValue(config, "CachedSource.Source.clone", "no")); // Pick up the options, if any optlist.Assign(CSLTokenizeString2(CPLGetXMLValue(config, "Options", nullptr), " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES)); // Load all the options in the IMAGE_STRUCTURE metadata for (int i = 0; i < optlist.Count(); i++) { CPLString s(optlist[i]); size_t nSepPos = s.find_first_of(":="); if( nSepPos != std::string::npos ) { s.resize(nSepPos); const char *key = s.c_str(); SetMetadataItem(key, optlist.FetchNameValue(key), "IMAGE_STRUCTURE"); } } // We have the options, so we can call rasterband for (int i = 1; i <= nBands; i++) { // The overviews are low resolution copies of the current one. GDALMRFRasterBand *band = newMRFRasterBand(this, current, i); if (!band) return CE_Failure; GDALColorInterp ci = GCI_Undefined; // Default color interpretation switch (nBands) { case 1: case 2: ci = (i == 1) ? GCI_GrayIndex : GCI_AlphaBand; break; case 3: case 4: if (i < 3) ci = (i == 1) ? GCI_RedBand : GCI_GreenBand; else ci = (i == 3) ? GCI_BlueBand : GCI_AlphaBand; } if (GetColorTable()) ci = GCI_PaletteIndex; // Legacy, deprecated if (optlist.FetchBoolean("MULTISPECTRAL", FALSE)) ci = GCI_Undefined; // New style if (!photometric.empty() ) { if ("MULTISPECTRAL" == photometric) ci = GCI_Undefined; } band->SetColorInterpretation(ci); SetBand(i, band); } CPLXMLNode *rsets = CPLGetXMLNode(config, "Rsets"); if (nullptr != rsets && nullptr != rsets->psChild) { // We have rsets // Regular spaced overlays, until everything fits in a single tile if (EQUAL("uniform", CPLGetXMLValue(rsets, "model", "uniform"))) { scale = getXMLNum(rsets, "scale", 2.0); if (scale <= 1) { CPLError(CE_Failure, CPLE_AppDefined, "MRF: zoom factor less than unit not allowed"); return CE_Failure; } // Looks like there are overlays AddOverviews(int(scale)); } else { CPLError(CE_Failure, CPLE_AppDefined, "Unknown Rset definition"); return CE_Failure; } } idxSize = IdxSize(full, int(scale)); if( idxSize == 0 ) { return CE_Failure; } // If not set by the bands, get a pageSizeBytes buffer if (GetPBufferSize() == 0) { if( !SetPBuffer(current.pageSizeBytes) ) { return CE_Failure; } } if (hasVersions) { // It has versions, but how many? verCount = 0; // Assume it only has one VSIStatBufL statb; // If the file exists, compute the last version number if (0 == VSIStatL(full.idxfname, &statb)) verCount = int(statb.st_size / idxSize - 1); } return CE_None; } static inline bool has_path(const CPLString &name) { return name.find_first_of("/\\") != string::npos; } // Does name look like an absolute gdal file name? static inline bool is_absolute(const CPLString &name) { return (name.find_first_of("/\\") == 0) // Starts with root || (name.size() > 1 && name[1] == ':' && isalpha(name[0])) // Starts with drive letter || (name[0] == '<'); // Maybe it is XML } // Add the dirname of path to the beginning of name, if it is relative // returns true if name was modified static inline bool make_absolute(CPLString &name, const CPLString &path) { if (!is_absolute(path) && (path.find_first_of("/\\") != string::npos)) { name = path.substr(0, path.find_last_of("/\\") + 1) + name; return true; } return false; } /** *\brief Get the source dataset, open it if necessary */ GDALDataset *GDALMRFDataset::GetSrcDS() { if (poSrcDS) return poSrcDS; if (source.empty()) return nullptr; // Try open the source dataset as is poSrcDS = GDALDataset::FromHandle(GDALOpenShared(source.c_str(), GA_ReadOnly)); // It the open fails, try again with the current dataset path prepended if (!poSrcDS && make_absolute(source, fname)) poSrcDS = GDALDataset::FromHandle(GDALOpenShared(source.c_str(), GA_ReadOnly)); if (0 == source.find("<MRF_META>") && has_path(fname)) { // MRF XML source, might need to patch the file names with the current one GDALMRFDataset *poMRFDS = dynamic_cast<GDALMRFDataset *>(poSrcDS); if( !poMRFDS ) { delete poSrcDS; poSrcDS = nullptr; return nullptr; } make_absolute(poMRFDS->current.datfname, fname); make_absolute(poMRFDS->current.idxfname, fname); } mp_safe = true; // Turn on MP safety return poSrcDS; } /** *\brief Add or verify that all overlays exits * * @return size of the index file */ GIntBig GDALMRFDataset::AddOverviews(int scaleIn) { // Fit the overlays ILImage img = current; while (1 != img.pagecount.x*img.pagecount.y) { // Adjust raster data for next level // Adjust the offsets for indices left at this level img.idxoffset += sizeof(ILIdx) * img.pagecount.l / img.size.z * (img.size.z - zslice); // Next overview size img.size.x = pcount(img.size.x, scaleIn); img.size.y = pcount(img.size.y, scaleIn); img.size.l++; // Increment the level img.pagecount = pcount(img.size, img.pagesize); // And adjust the offset again, within next level img.idxoffset += sizeof(ILIdx) * img.pagecount.l / img.size.z * zslice; // Create and register the the overviews for each band for (int i = 1; i <= nBands; i++) { GDALMRFRasterBand *b = reinterpret_cast<GDALMRFRasterBand *>(GetRasterBand(i)); if (!(b->GetOverview(static_cast<int>(img.size.l) - 1))) b->AddOverview(newMRFRasterBand(this, img, i, static_cast<int>(img.size.l))); } } // Last adjustment, should be a single set of c and leftover z tiles return img.idxoffset + sizeof(ILIdx) * img.pagecount.l / img.size.z * (img.size.z - zslice); } // CreateCopy implemented based on Create GDALDataset *GDALMRFDataset::CreateCopy(const char *pszFilename, GDALDataset *poSrcDS, int /*bStrict*/, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData) { ILImage img; int x = poSrcDS->GetRasterXSize(); int y = poSrcDS->GetRasterYSize(); int nBands = poSrcDS->GetRasterCount(); if( nBands == 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "nBands == 0 not supported"); return nullptr; } GDALRasterBand *poSrcBand1 = poSrcDS->GetRasterBand(1); GDALDataType dt = poSrcBand1->GetRasterDataType(); // Have our own options, to modify as we want char **options = CSLDuplicate(papszOptions); const char *pszValue = poSrcDS->GetMetadataItem("INTERLEAVE", "IMAGE_STRUCTURE"); options = CSLAddIfMissing(options, "INTERLEAVE", pszValue ? pszValue : "PIXEL"); int xb, yb; poSrcBand1->GetBlockSize(&xb, &yb); // Keep input block size if it exists and not explicitly set if (CSLFetchNameValue(options, "BLOCKSIZE") == nullptr && xb != x && yb != y) { options = CSLAddIfMissing(options, "BLOCKXSIZE", PrintDouble(xb, "%d").c_str()); options = CSLAddIfMissing(options, "BLOCKYSIZE", PrintDouble(yb, "%d").c_str()); } GDALMRFDataset *poDS = nullptr; try { poDS = reinterpret_cast<GDALMRFDataset *>( Create(pszFilename, x, y, nBands, dt, options)); if (poDS == nullptr || poDS->bCrystalized) throw CPLString().Printf("Can't create %s",pszFilename); img = poDS->current; // Deal with the current one here // Copy data values from source for (int i = 0; i < poDS->nBands; i++) { int bHas; double dfData; GDALRasterBand *srcBand = poSrcDS->GetRasterBand(i + 1); GDALRasterBand *mBand = poDS->GetRasterBand(i + 1); dfData = srcBand->GetNoDataValue(&bHas); if (bHas) { poDS->vNoData.push_back(dfData); mBand->SetNoDataValue(dfData); } dfData = srcBand->GetMinimum(&bHas); if (bHas) poDS->vMin.push_back(dfData); dfData = srcBand->GetMaximum(&bHas); if (bHas) poDS->vMax.push_back(dfData); // Copy the band metadata, PAM will handle it char **meta = srcBand->GetMetadata("IMAGE_STRUCTURE"); if (CSLCount(meta)) mBand->SetMetadata(meta,"IMAGE_STRUCTURE"); meta = srcBand->GetMetadata(); if (CSLCount(meta)) mBand->SetMetadata(meta); } // Geotags double gt[6]; if (CE_None == poSrcDS->GetGeoTransform(gt)) poDS->SetGeoTransform(gt); const char *pszProj = poSrcDS->GetProjectionRef(); if (pszProj && pszProj[0]) poDS->SetProjection(pszProj); // Color palette if we only have one band if (1 == nBands && GCI_PaletteIndex == poSrcBand1->GetColorInterpretation()) poDS->SetColorTable(poSrcBand1->GetColorTable()->Clone()); // Finally write the XML in the right file name poDS->Crystalize(); } catch (const CPLString& e) { if (poDS) delete poDS; CPLError(CE_Failure, CPLE_ObjectNull, "%s", e.c_str()); poDS = nullptr; } CSLDestroy(options); if (!poDS) return nullptr; char** papszFileList = poDS->GetFileList(); poDS->oOvManager.Initialize(poDS, poDS->GetPhysicalFilename(), papszFileList); CSLDestroy(papszFileList); CPLErr err = CE_None; // Have PAM copy all, but skip the mask int nCloneFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK; // If copy is disabled, we're done, we just created an empty MRF if (!on(CSLFetchNameValue(papszOptions, "NOCOPY"))) { // Use the GDAL copy call // Need to flag the dataset as compressed (COMPRESSED=TRUE) to force block writes // This might not be what we want, if the input and out order is truly separate nCloneFlags |= GCIF_MASK; // We do copy the data, so copy the mask too if necessary char **papszCWROptions = nullptr; papszCWROptions = CSLAddNameValue(papszCWROptions, "COMPRESSED", "TRUE"); // Use the Zen version of the CopyWholeRaster if input has a dataset mask and JPEGs are generated if (GMF_PER_DATASET == poSrcDS->GetRasterBand(1)->GetMaskFlags() && (poDS->current.comp == IL_JPEG || poDS->current.comp == IL_JPNG)) { err = poDS->ZenCopy(poSrcDS, pfnProgress, pProgressData); nCloneFlags ^= GCIF_MASK; // Turn the external mask off } else { err = GDALDatasetCopyWholeRaster((GDALDatasetH)poSrcDS, (GDALDatasetH)poDS, papszCWROptions, pfnProgress, pProgressData); } CSLDestroy(papszCWROptions); } if (CE_None == err) err = poDS->CloneInfo(poSrcDS, nCloneFlags); if (CE_Failure == err) { delete poDS; return nullptr; } return poDS; } // Prepares the data so it is suitable for Zen JPEG encoding, based on input mask // If bFBO is set, only the values of the first band are set non-zero when needed template<typename T> static void ZenFilter(T* buffer, GByte *mask, int nPixels, int nBands, bool bFBO) { for (int i = 0; i < nPixels; i++) { if (mask[i] == 0) { // enforce zero values for (int b = 0; b < nBands; b++) buffer[nBands * i + b] = 0; } else { // enforce non-zero if (bFBO) { // First band only bool f = true; for (int b = 0; b < nBands; b++) f = f && (0 == buffer[nBands * i + b]); if (f) buffer[nBands * i] = 1; } else { // Every band for (int b = 0; b < nBands; b++) if (0 == buffer[nBands * i + b]) buffer[nBands * i + b] = 1; } } } } // Custom CopyWholeRaster for Zen JPEG, called when the input has a PER_DATASET mask // Works like GDALDatasetCopyWholeRaster, but it does filter the input data based on the mask // CPLErr GDALMRFDataset::ZenCopy(GDALDataset *poSrc, GDALProgressFunc pfnProgress, void * pProgressData) { VALIDATE_POINTER1(poSrc, "MRF:ZenCopy", CE_Failure); if (!pfnProgress) pfnProgress = GDALDummyProgress; /* -------------------------------------------------------------------- */ /* Confirm the datasets match in size and band counts. */ /* -------------------------------------------------------------------- */ const int nXSize = GetRasterXSize(); const int nYSize = GetRasterYSize(); const int nBandCount = GetRasterCount(); if (poSrc->GetRasterXSize() != nXSize || poSrc->GetRasterYSize() != nYSize || poSrc->GetRasterCount() != nBandCount) { CPLError(CE_Failure, CPLE_AppDefined, "Input and output dataset sizes or band counts do not\n" "match in GDALDatasetCopyWholeRaster()"); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Get our prototype band, and assume the others are similarly */ /* configured. Also get the per_dataset mask */ /* -------------------------------------------------------------------- */ GDALRasterBand *poSrcPrototypeBand = poSrc->GetRasterBand(1); GDALRasterBand *poDstPrototypeBand = GetRasterBand(1); GDALRasterBand *poSrcMask = poSrcPrototypeBand->GetMaskBand(); const int nPageXSize = current.pagesize.x; const int nPageYSize = current.pagesize.y; const double nTotalBlocks = static_cast<double>(DIV_ROUND_UP(nYSize, nPageYSize)) * static_cast<double>(DIV_ROUND_UP(nXSize, nPageXSize)); const GDALDataType eDT = poDstPrototypeBand->GetRasterDataType(); // All the bands are done per block // this flag tells us to apply the Zen filter to the first band only const bool bFirstBandOnly = (current.order == IL_Interleaved); if (!pfnProgress(0.0, nullptr, pProgressData)) { CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()"); return CE_Failure; } const int nPixelCount = nPageXSize * nPageYSize; const int dts = GDALGetDataTypeSizeBytes(eDT); void *buffer = VSI_MALLOC3_VERBOSE(nPixelCount, nBandCount, dts); GByte *buffer_mask = nullptr; if (buffer) buffer_mask = reinterpret_cast<GByte *>(VSI_MALLOC_VERBOSE(nPixelCount)); if (!buffer || !buffer_mask) { // Just in case buffers did get allocated CPLFree(buffer); CPLFree(buffer_mask); CPLError(CE_Failure, CPLE_OutOfMemory, "Can't allocate copy buffer"); return CE_Failure; } int nBlocksDone = 0; CPLErr eErr = CE_None; // Advise the source that a complete read will be done poSrc->AdviseRead(0, 0, nXSize, nYSize, nXSize, nYSize, eDT, nBandCount, nullptr, nullptr); // For every block, break on error for (int row = 0; row < nYSize && eErr == CE_None; row += nPageYSize) { int nRows = std::min(nPageYSize, nYSize - row); for (int col = 0; col < nXSize && eErr == CE_None; col += nPageXSize) { int nCols = std::min(nPageXSize, nXSize - col); // Report if (eErr == CE_None && !pfnProgress(nBlocksDone++ / nTotalBlocks, nullptr, pProgressData)) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()"); break; } // Get the data mask as byte eErr = poSrcMask->RasterIO(GF_Read, col, row, nCols, nRows, buffer_mask, nCols, nRows, GDT_Byte, 0, 0, nullptr); if (eErr != CE_None) break; // If there is no data at all, skip this block if (MatchCount(buffer_mask, nPixelCount, static_cast<GByte>(0)) == nPixelCount) continue; // get the data in the buffer, interleaved eErr = poSrc->RasterIO(GF_Read, col, row, nCols, nRows, buffer, nCols, nRows, eDT, nBandCount, nullptr, nBands * dts, nBands * dts * nCols, dts, nullptr); if (eErr != CE_None) break; // This is JPEG, only 8 and 12(16) bits unsigned integer types are valid switch (eDT) { case GDT_Byte: ZenFilter(reinterpret_cast<GByte *>(buffer), buffer_mask, nPixelCount, nBandCount, bFirstBandOnly); break; case GDT_UInt16: ZenFilter(reinterpret_cast<GUInt16 *>(buffer), buffer_mask, nPixelCount, nBandCount, bFirstBandOnly); break; default: CPLError(CE_Failure, CPLE_AppDefined, "Unsupported data type for Zen filter"); eErr = CE_Failure; break; } // Write if( eErr == CE_None ) { eErr = RasterIO(GF_Write, col, row, nCols, nRows, buffer, nCols, nRows, eDT, nBandCount, nullptr, nBands * dts, nBands * dts * nCols, dts, nullptr); } } // Columns if (eErr != CE_None) break; } // Rows // Cleanup CPLFree(buffer); CPLFree(buffer_mask); // Final report if (eErr == CE_None && !pfnProgress(1.0, nullptr, pProgressData)) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()"); } return eErr; } // Apply open options to the current dataset // Called before the configuration is read void GDALMRFDataset::ProcessOpenOptions(char **papszOptions) { CPLStringList opt(papszOptions, FALSE); no_errors = opt.FetchBoolean("NOERRORS", FALSE); const char *val = opt.FetchNameValue("ZSLICE"); if (val) zslice = atoi(val); } // Apply create options to the current dataset, only valid during creation void GDALMRFDataset::ProcessCreateOptions(char **papszOptions) { assert(!bCrystalized); CPLStringList opt(papszOptions, FALSE); ILImage &img(full); const char *val = opt.FetchNameValue("COMPRESS"); if (val && IL_ERR_COMP == (img.comp = CompToken(val))) throw CPLString("GDAL MRF: Error setting compression"); val = opt.FetchNameValue("INTERLEAVE"); if (val && IL_ERR_ORD == (img.order = OrderToken(val))) throw CPLString("GDAL MRF: Error setting interleave"); val = opt.FetchNameValue("QUALITY"); if (val) img.quality = atoi(val); val = opt.FetchNameValue("ZSIZE"); if (val) img.size.z = atoi(val); val = opt.FetchNameValue("BLOCKXSIZE"); if (val) img.pagesize.x = atoi(val); val = opt.FetchNameValue("BLOCKYSIZE"); if (val) img.pagesize.y = atoi(val); val = opt.FetchNameValue("BLOCKSIZE"); if (val) img.pagesize.x = img.pagesize.y = atoi(val); img.nbo = opt.FetchBoolean("NETBYTEORDER", FALSE); val = opt.FetchNameValue("CACHEDSOURCE"); if (val) { source = val; nocopy = opt.FetchBoolean("NOCOPY", FALSE); } val = opt.FetchNameValue("UNIFORM_SCALE"); if (val) scale = atoi(val); val = opt.FetchNameValue("PHOTOMETRIC"); if (val) photometric = val; val = opt.FetchNameValue("DATANAME"); if (val) img.datfname = val; val = opt.FetchNameValue("INDEXNAME"); if (val) img.idxfname = val; val = opt.FetchNameValue("SPACING"); if (val) spacing = atoi(val); optlist.Assign(CSLTokenizeString2(opt.FetchNameValue("OPTIONS"), " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES)); // General Fixups if (img.order == IL_Interleaved) img.pagesize.c = img.size.c; // Compression dependent fixups #if defined(LERC) if (IL_LERC == img.comp) img.pagesize.c = 1; #endif } /** *\brief Create an MRF dataset, some settings can be changed later * papszOptions might be anything that an MRF might take * Still missing are the georeference ... * */ GDALDataset * GDALMRFDataset::Create(const char * pszName, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszOptions) { // Pending create if( nBands == 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "nBands == 0 not supported"); return nullptr; } GDALMRFDataset *poDS = new GDALMRFDataset(); CPLErr err = CE_None; poDS->fname = pszName; poDS->nBands = nBands; // Don't know what to do with these in this call //int level = -1; //int version = 0; size_t pos = poDS->fname.find(":MRF:"); if (string::npos != pos) { // Tokenize and pick known options vector<string> tokens; stringSplit(tokens, poDS->fname, pos + 5, ':'); //level = getnum(tokens, 'L', -1); //version = getnum(tokens, 'V', 0); poDS->zslice = getnum(tokens, 'Z', 0); poDS->fname.resize(pos); // Cut the ornamentations } // Use the full, set some initial parameters ILImage &img = poDS->full; img.size = ILSize(nXSize, nYSize, 1, nBands); img.comp = IL_PNG; img.order = (nBands < 5) ? IL_Interleaved : IL_Separate; img.pagesize = ILSize(512, 512, 1, 1); img.quality = 85; img.dt = eType; img.dataoffset = 0; img.idxoffset = 0; img.hasNoData = false; img.nbo = FALSE; // Set the guard that tells us it needs saving before IO can take place poDS->bCrystalized = FALSE; // Process the options, anything that an MRF might take try { // Adjust the dataset and the full image poDS->ProcessCreateOptions(papszOptions); // Set default file names if (img.datfname.empty()) img.datfname = getFname(poDS->GetFname(), ILComp_Ext[img.comp]); if (img.idxfname.empty()) img.idxfname = getFname(poDS->GetFname(), ".idx"); poDS->eAccess = GA_Update; } catch (const CPLString& e) { CPLError(CE_Failure, CPLE_OpenFailed, "%s", e.c_str()); delete poDS; return nullptr; } poDS->current = poDS->full; poDS->SetDescription(poDS->GetFname()); // Build a MRF XML and initialize from it, this creates the bands CPLXMLNode *config = poDS->BuildConfig(); err = poDS->Initialize(config); CPLDestroyXMLNode(config); if (CPLE_None != err) { delete poDS; return nullptr; } // If not set by the band, get a pageSizeBytes buffer if (poDS->GetPBufferSize() == 0) { if( !poDS->SetPBuffer(poDS->current.pageSizeBytes) ) { delete poDS; return nullptr; } } // Tell PAM what our real file name is, to help it find the aux.xml poDS->SetPhysicalFilename(poDS->GetFname()); return poDS; } void GDALMRFDataset::Crystalize() { if (bCrystalized || eAccess != GA_Update) return; // No need to write to disk if there is no filename. This is a // memory only dataset. if (strlen(GetDescription()) == 0 || EQUALN(GetDescription(), "<MRF_META>", 10)) return; CPLXMLNode *config = BuildConfig(); WriteConfig(config); CPLDestroyXMLNode(config); if (!nocopy && (!IdxFP() || !DataFP())) throw CPLString().Printf("MRF: %s", strerror(errno)); bCrystalized = TRUE; } // Copy the first index at the end of the file and bump the version count CPLErr GDALMRFDataset::AddVersion() { VSILFILE *l_ifp = IdxFP(); void *tbuff = CPLMalloc(static_cast<size_t>(idxSize)); VSIFSeekL(l_ifp, 0, SEEK_SET); VSIFReadL(tbuff, 1, static_cast<size_t>(idxSize), l_ifp); verCount++; // The one we write VSIFSeekL(l_ifp, idxSize * verCount, SEEK_SET); // At the end, this can mess things up royally VSIFWriteL(tbuff, 1, static_cast<size_t>(idxSize), l_ifp); CPLFree(tbuff); return CE_None; } // // Write a tile at the end of the data file // If buff and size are zero, it is equivalent to erasing the tile // If only size is zero, it is a special empty tile, // when used for caching, offset should be 1 // // To make it multi-processor safe, open the file in append mode // and verify after write // CPLErr GDALMRFDataset::WriteTile(void *buff, GUIntBig infooffset, GUIntBig size) { CPLErr ret = CE_None; ILIdx tinfo = { 0, 0 }; VSILFILE *l_dfp = DataFP(); VSILFILE *l_ifp = IdxFP(); // Pointer to verfiy buffer, if it doesn't exist everything worked fine void *tbuff = nullptr; if (l_ifp == nullptr || l_dfp == nullptr) return CE_Failure; // Flag that versioned access requires a write even if empty int new_tile = false; // If it has versions, might need to start a new one if (hasVersions) { int new_version = false; // Assume no need to build new version // Read the current tile info VSIFSeekL(l_ifp, infooffset, SEEK_SET); VSIFReadL(&tinfo, 1, sizeof(ILIdx), l_ifp); if (verCount != 0) { // We need at least two versions before we test buffers ILIdx prevtinfo = { 0, 0 }; // Read the previous one VSIFSeekL(l_ifp, infooffset + verCount * idxSize, SEEK_SET); VSIFReadL(&prevtinfo, 1, sizeof(ILIdx), l_ifp); // current and previous tiles are different, might create version if (tinfo.size != prevtinfo.size || tinfo.offset != prevtinfo.offset) new_version = true; } else new_version = true; // No previous, might create version // tinfo contains the current info or 0,0 if (tinfo.size == GIntBig(net64(size))) { // Might be the same, read and compare if (size != 0) { tbuff = CPLMalloc(static_cast<size_t>(size)); // Use the temporary buffer, we can't have a versioned cache !! VSIFSeekL(l_dfp, infooffset, SEEK_SET); VSIFReadL(tbuff, 1, static_cast<size_t>(size), l_dfp); // Need to write it if not the same new_tile = (0 != memcmp(buff, tbuff, static_cast<size_t>(size))); CPLFree(tbuff); tbuff = nullptr; } else { // Writing a null tile on top of a null tile, does it count? if (tinfo.offset != GIntBig(net64(GUIntBig(buff)))) new_tile = true; } } else { new_tile = true; // Need to write it because it is different if (verCount == 0 && tinfo.size == 0) new_version = false; // Don't create a version if current is empty and there is no previous } if (!new_tile) return CE_None; // No reason to write // Do we need to start a new version before writing the tile? if (new_version) AddVersion(); } // Convert to net format tinfo.size = net64(size); if (size) do { // These statements are the critical MP section for the data file VSIFSeekL(l_dfp, 0, SEEK_END); GUIntBig offset = VSIFTellL(l_dfp); if( spacing != 0 ) { // This should not be true in MP safe mode. // Use the same buffer, MRF doesn't care about the spacing content. // TODO(lplesea): Make sure size doesn't overflow. const int pad = static_cast<int>(size) >= spacing ? spacing : static_cast<int>(size); if( pad != spacing ) CPLError(CE_Warning, CPLE_FileIO, "MRF spacing failed, check the output"); offset += pad; VSIFWriteL(buff, 1, spacing, l_dfp); } if (static_cast<size_t>(size) != VSIFWriteL(buff, 1, static_cast<size_t>(size), l_dfp)) ret = CE_Failure; // End of critical section tinfo.offset = net64(offset); // // For MP ops, check that we can read it back properly, otherwise we're done // This makes the caching MRF MP safe, without using explicit locks // if (mp_safe) { // Allocate the temp buffer if we haven't done so already if (!tbuff) tbuff = CPLMalloc(static_cast<size_t>(size)); VSIFSeekL(l_dfp, offset, SEEK_SET); VSIFReadL(tbuff, 1, static_cast<size_t>(size), l_dfp); // If memcmp returns zero, verify passed if (!memcmp(buff, tbuff, static_cast<size_t>(size))) { CPLFree(tbuff); tbuff = nullptr; // Triggers the loop termination } // Otherwise the tbuf stays allocated and try to write again // This works only if the file is opened in append mode } } while (tbuff); // At this point, the data is in the datafile // Do nothing if the tile is empty and the file record is also empty if (!new_tile && 0 == size && nullptr == buff) { VSIFSeekL(l_ifp, infooffset, SEEK_SET); VSIFReadL(&tinfo, 1, sizeof(ILIdx), l_ifp); if (0 == tinfo.offset && 0 == tinfo.size) return ret; } // Special case // Any non-zero will do, use 1 to only consume one bit if (nullptr != buff && 0 == size) tinfo.offset = net64(GUIntBig(buff)); VSIFSeekL(l_ifp, infooffset, SEEK_SET); if (sizeof(tinfo) != VSIFWriteL(&tinfo, 1, sizeof(tinfo), l_ifp)) ret = CE_Failure; return ret; } CPLErr GDALMRFDataset::SetGeoTransform(double *gt) { if (GetAccess() == GA_Update) { memcpy(GeoTransform, gt, 6 * sizeof(double)); bGeoTransformValid = TRUE; return CE_None; } CPLError(CE_Failure, CPLE_NotSupported, "SetGeoTransform called on read only file"); return CE_Failure; } bool GDALMRFDataset::IsSingleTile() { if (current.pagecount.l != 1 || !source.empty() || nullptr == DataFP()) return FALSE; return 0 == reinterpret_cast<GDALMRFRasterBand *>(GetRasterBand(1))->GetOverviewCount(); } /* * Returns 0,1,0,0,0,1 even if it was not set */ CPLErr GDALMRFDataset::GetGeoTransform(double *gt) { memcpy(gt, GeoTransform, 6 * sizeof(double)); if (GetMetadata("RPC") || GetGCPCount()) bGeoTransformValid = FALSE; if (!bGeoTransformValid) return CE_Failure; return CE_None; } /** *\brief Read a tile index * * It handles the non-existent index case, for no compression * The bias is non-zero only when the cloned index is read */ CPLErr GDALMRFDataset::ReadTileIdx(ILIdx &tinfo, const ILSize &pos, const ILImage &img, const GIntBig bias) { VSILFILE *l_ifp = IdxFP(); // Initialize the tinfo structure, in case the files are missing if (missing) return CE_None; GIntBig offset = bias + IdxOffset(pos, img); if (l_ifp == nullptr && img.comp == IL_NONE ) { tinfo.size = current.pageSizeBytes; tinfo.offset = offset * tinfo.size; return CE_None; } if (l_ifp == nullptr && IsSingleTile()) { tinfo.offset = 0; VSILFILE *l_dfp = DataFP(); // IsSingleTile() checks that fp is valid VSIFSeekL(l_dfp, 0, SEEK_END); tinfo.size = VSIFTellL(l_dfp); // It should be less than the pagebuffer tinfo.size = std::min(tinfo.size, static_cast<GIntBig>(pbsize)); return CE_None; } if (l_ifp == nullptr) { CPLError(CE_Failure, CPLE_FileIO, "Can't open index file"); return CE_Failure; } VSIFSeekL(l_ifp, offset, SEEK_SET); if (1 != VSIFReadL(&tinfo, sizeof(ILIdx), 1, l_ifp)) return CE_Failure; // Convert them to native form tinfo.offset = net64(tinfo.offset); tinfo.size = net64(tinfo.size); if (0 == bias || 0 != tinfo.size || 0 != tinfo.offset) return CE_None; // zero size and zero offset in sourced index means that this portion is un-initialized // Should be cloned and the offset within the cloned index offset -= bias; assert(offset < bias); assert(clonedSource); // Read this block from the remote index, prepare it and store it in the right place // The block size in bytes, should be a multiple of 16, to have full index entries const int CPYSZ = 32768; // Adjust offset to the start of the block offset = (offset / CPYSZ) * CPYSZ; GIntBig size = std::min(size_t(CPYSZ), size_t(bias - offset)); size /= sizeof(ILIdx); // In records vector<ILIdx> buf(static_cast<size_t>(size)); ILIdx *buffer = &buf[0]; // Buffer to copy the source to the clone index // Fetch the data from the cloned index GDALMRFDataset *pSrc = static_cast<GDALMRFDataset *>(GetSrcDS()); if( pSrc == nullptr ) { CPLError(CE_Failure, CPLE_FileIO, "Can't open cloned source index"); return CE_Failure; // Source reported the error } VSILFILE *srcidx = pSrc->IdxFP(); if (!srcidx) { CPLError(CE_Failure, CPLE_FileIO, "Can't open cloned source index"); return CE_Failure; // Source reported the error } VSIFSeekL(srcidx, offset, SEEK_SET); size = VSIFReadL(buffer, sizeof(ILIdx), static_cast<size_t>(size), srcidx); if (size != GIntBig(buf.size())) { CPLError(CE_Failure, CPLE_FileIO, "Can't read cloned source index"); return CE_Failure; // Source reported the error } // Mark the empty records as checked, by making the offset non-zero for (vector<ILIdx>::iterator it = buf.begin(); it != buf.end(); ++it) { if (it->offset == 0 && it->size == 0) it->offset = net64(1); } // Write it in the right place in the local index file VSIFSeekL(l_ifp, bias + offset, SEEK_SET); size = VSIFWriteL(&buf[0], sizeof(ILIdx), static_cast<size_t>(size), l_ifp); if (size != GIntBig(buf.size())) { CPLError(CE_Failure, CPLE_FileIO, "Can't write to cloning MRF index"); return CE_Failure; // Source reported the error } // Cloned index updated, restart this function, it will work now return ReadTileIdx(tinfo, pos, img, bias); } NAMESPACE_MRF_END
#include "DQMOffline/Muon/interface/EfficiencyPlotter.h" // Framework #include <FWCore/Framework/interface/Event.h> #include "DataFormats/Common/interface/Handle.h" #include <FWCore/Framework/interface/ESHandle.h> #include <FWCore/Framework/interface/MakerMacros.h> #include <FWCore/Framework/interface/EventSetup.h> #include <FWCore/ParameterSet/interface/ParameterSet.h> #include "DQMServices/Core/interface/DQMStore.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Framework/interface/Run.h" #include <iostream> #include <cstdio> #include <string> #include <cmath> #include "TF1.h" #include "TH1F.h" using namespace edm; using namespace std; //#define DEBUG EfficiencyPlotter::EfficiencyPlotter(const edm::ParameterSet &ps) { #ifdef DEBUG cout << "EfficiencyPlotter(): Constructor " << endl; #endif parameters = ps; etaBin = parameters.getParameter<int>("etaBin"); etaMin = parameters.getParameter<double>("etaMin"); etaMax = parameters.getParameter<double>("etaMax"); phiBin = parameters.getParameter<int>("phiBin"); phiMin = parameters.getParameter<double>("phiMin"); phiMax = parameters.getParameter<double>("phiMax"); ptBin = parameters.getParameter<int>("ptBin"); ptMin = parameters.getParameter<double>("ptMin"); ptMax = parameters.getParameter<double>("ptMax"); vtxBin = parameters.getParameter<int>("vtxBin"); vtxMin = parameters.getParameter<double>("vtxMin"); vtxMax = parameters.getParameter<double>("vtxMax"); ID_ = parameters.getParameter<string>("MuonID"); theFolder = parameters.getParameter<string>("folder"); } EfficiencyPlotter::~EfficiencyPlotter() {} void EfficiencyPlotter::dqmEndJob(DQMStore::IBooker &ibooker, DQMStore::IGetter &igetter) { ibooker.setCurrentFolder(theFolder); // efficiency plot h_eff_eta_ID = ibooker.book1D("Eff_eta_" + ID_, ID_ + " Eff. vs #eta", etaBin, etaMin, etaMax); h_eff_inner_pt_ID = ibooker.book1D("Eff_inner_pt_" + ID_, ID_ + " Eff. vs pt", ptBin, ptMin, ptMax); h_eff_inner_eta_ID = ibooker.book1D("Eff_inner_eta_" + ID_, ID_ + " Eff. vs #eta", etaBin, etaMin, etaMax); h_eff_inner_phi_ID = ibooker.book1D("Eff_inner_phi_" + ID_, ID_ + " Eff. vs #phi", phiBin, phiMin, phiMax); h_eff_hp_eta_ID = ibooker.book1D("Eff_hp_eta_" + ID_, "High Pt " + ID_ + " Eff. vs #eta", etaBin, etaMin, etaMax); h_eff_phi_ID = ibooker.book1D("Eff_phi_" + ID_, ID_ + " Eff. vs #phi", phiBin, phiMin, phiMax); h_eff_pt_ID = ibooker.book1D("Eff_pt_" + ID_, ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EB_ID = ibooker.book1D("Eff_pt_EB_" + ID_, "Barrel: " + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EE_ID = ibooker.book1D("Eff_pt_EE_" + ID_, "Endcap: " + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_detIsoID = ibooker.book1D("Eff_pt_detIso" + ID_, "detIso" + ID_ + " Efficiency vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EB_detIsoID = ibooker.book1D("Eff_pt_EB_detIso" + ID_, "Barrel: detIso" + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EE_detIsoID = ibooker.book1D("Eff_pt_EE_detIso" + ID_, "Endcap: detIso" + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_pfIsoID = ibooker.book1D("Eff_pt_pfIso" + ID_, "pfIso" + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EB_pfIsoID = ibooker.book1D("Eff_pt_EB_pfIso" + ID_, "Barrel: pfIso" + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EE_pfIsoID = ibooker.book1D("Eff_pt_EE_pfIso" + ID_, "Endcap: pfIso" + ID_ + " Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_vtx_detIsoID = ibooker.book1D("Eff_vtx_detIso" + ID_, "detIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_pfIsoID = ibooker.book1D("Eff_vtx_pfIso" + ID_, "pfIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EB_detIsoID = ibooker.book1D("Eff_vtx_EB_detIso" + ID_, "Barrel: detIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EB_pfIsoID = ibooker.book1D("Eff_vtx_EB_pfIso" + ID_, "Barrel: pfIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EE_detIsoID = ibooker.book1D("Eff_vtx_EE_detIso" + ID_, "Endcap: detIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EE_pfIsoID = ibooker.book1D("Eff_vtx_EE_pfIso" + ID_, "Endcap: pfIso" + ID_ + " Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_pt_pfIsodBID = ibooker.book1D("Eff_pt_pfIsodB" + ID_, "pfIso" + ID_ + " (deltaBeta) Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EB_pfIsodBID = ibooker.book1D("Eff_pt_EB_pfIsodB" + ID_, "Barrel: pfIso" + ID_ + " (deltaBeta) Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_pt_EE_pfIsodBID = ibooker.book1D("Eff_pt_EE_pfIsodB" + ID_, "Endcap: pfIso" + ID_ + " (deltaBeta) Eff. vs Pt", ptBin, ptMin, ptMax); h_eff_vtx_pfIsodBID = ibooker.book1D("Eff_vtx_pfIsodB" + ID_, "pfIso" + ID_ + " (deltaBeta) Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EB_pfIsodBID = ibooker.book1D( "Eff_vtx_EB_pfIsodB" + ID_, "Barrel: pfIso" + ID_ + " (deltaBeta) Eff. vs nVtx", vtxBin, vtxMin, vtxMax); h_eff_vtx_EE_pfIsodBID = ibooker.book1D( "Eff_vtx_EE_pfIsodB" + ID_, "Endcap: pfIso" + ID_ + " (deltaBeta) Eff. vs nVtx", vtxBin, vtxMin, vtxMax); // This prevents this ME to be normalized when drawn into the GUI h_eff_eta_ID->setEfficiencyFlag(); h_eff_inner_eta_ID->setEfficiencyFlag(); h_eff_inner_pt_ID->setEfficiencyFlag(); h_eff_inner_phi_ID->setEfficiencyFlag(); h_eff_hp_eta_ID->setEfficiencyFlag(); h_eff_phi_ID->setEfficiencyFlag(); h_eff_pt_ID->setEfficiencyFlag(); h_eff_pt_EB_ID->setEfficiencyFlag(); h_eff_pt_EE_ID->setEfficiencyFlag(); h_eff_pt_detIsoID->setEfficiencyFlag(); h_eff_pt_EB_detIsoID->setEfficiencyFlag(); h_eff_pt_EE_detIsoID->setEfficiencyFlag(); h_eff_pt_pfIsoID->setEfficiencyFlag(); h_eff_pt_EB_pfIsoID->setEfficiencyFlag(); h_eff_pt_EE_pfIsoID->setEfficiencyFlag(); h_eff_vtx_detIsoID->setEfficiencyFlag(); h_eff_vtx_pfIsoID->setEfficiencyFlag(); h_eff_vtx_EB_detIsoID->setEfficiencyFlag(); h_eff_vtx_EB_pfIsoID->setEfficiencyFlag(); h_eff_vtx_EE_detIsoID->setEfficiencyFlag(); h_eff_vtx_EE_pfIsoID->setEfficiencyFlag(); h_eff_pt_pfIsodBID->setEfficiencyFlag(); h_eff_pt_EB_pfIsodBID->setEfficiencyFlag(); h_eff_pt_EE_pfIsodBID->setEfficiencyFlag(); h_eff_vtx_pfIsodBID->setEfficiencyFlag(); h_eff_vtx_EB_pfIsodBID->setEfficiencyFlag(); h_eff_vtx_EE_pfIsodBID->setEfficiencyFlag(); // AXIS TITLES.... h_eff_hp_eta_ID->setAxisTitle("#eta", 1); h_eff_inner_eta_ID->setAxisTitle("#eta", 1); h_eff_inner_pt_ID->setAxisTitle("#eta", 1); h_eff_inner_phi_ID->setAxisTitle("#eta", 1); h_eff_eta_ID->setAxisTitle("#eta", 1); h_eff_phi_ID->setAxisTitle("#phi", 1); h_eff_pt_ID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EB_ID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EE_ID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_detIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EB_detIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EE_detIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_pfIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EB_pfIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EE_pfIsoID->setAxisTitle("p_{T} (GeV)", 1); h_eff_vtx_detIsoID->setAxisTitle("Number of PV", 1); h_eff_vtx_pfIsoID->setAxisTitle("Number of PV", 1); h_eff_vtx_EB_detIsoID->setAxisTitle("Number of PV", 1); h_eff_vtx_EB_pfIsoID->setAxisTitle("Number of PV", 1); h_eff_vtx_EE_detIsoID->setAxisTitle("Number of PV", 1); h_eff_vtx_EE_pfIsoID->setAxisTitle("Number of PV", 1); h_eff_pt_pfIsodBID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EB_pfIsodBID->setAxisTitle("p_{T} (GeV)", 1); h_eff_pt_EE_pfIsodBID->setAxisTitle("p_{T} (GeV)", 1); h_eff_vtx_pfIsodBID->setAxisTitle("Number of PV", 1); h_eff_vtx_EB_pfIsodBID->setAxisTitle("Number of PV", 1); h_eff_vtx_EE_pfIsodBID->setAxisTitle("Number of PV", 1); /// --- Tight Muon efficiency vs muon Pt string inputdir = "Muons/EfficiencyAnalyzer/" + ID_; string numpath_pt = inputdir + "/passProbes_ID_pt"; string denpath_pt = inputdir + "/allProbes_pt"; MonitorElement *Numerator_pt = igetter.get(numpath_pt); MonitorElement *Denominator_pt = igetter.get(denpath_pt); if (Numerator_pt && Denominator_pt) { TH1F *h_numerator_pt = Numerator_pt->getTH1F(); TH1F *h_denominator_pt = Denominator_pt->getTH1F(); TH1F *h_eff_pt = h_eff_pt_ID->getTH1F(); if (h_eff_pt->GetSumw2N() == 0) h_eff_pt->Sumw2(); h_eff_pt->Divide(h_numerator_pt, h_denominator_pt, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon inner Pt string numpath_inner_pt = inputdir + "/passProbes_ID_inner_pt"; string denpath_inner_pt = inputdir + "/allProbes_inner_pt"; MonitorElement *Numerator_inner_pt = igetter.get(numpath_inner_pt); MonitorElement *Denominator_inner_pt = igetter.get(denpath_inner_pt); if (Numerator_inner_pt && Denominator_inner_pt) { TH1F *h_numerator_inner_pt = Numerator_inner_pt->getTH1F(); TH1F *h_denominator_inner_pt = Denominator_inner_pt->getTH1F(); TH1F *h_eff_inner_pt = h_eff_inner_pt_ID->getTH1F(); if (h_eff_inner_pt->GetSumw2N() == 0) h_eff_inner_pt->Sumw2(); h_eff_inner_pt->Divide(h_numerator_inner_pt, h_denominator_inner_pt, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon inner eta string numpath_inner_eta = inputdir + "/passProbes_ID_inner_eta"; string denpath_inner_eta = inputdir + "/allProbes_inner_eta"; MonitorElement *Numerator_inner_eta = igetter.get(numpath_inner_eta); MonitorElement *Denominator_inner_eta = igetter.get(denpath_inner_eta); if (Numerator_inner_eta && Denominator_inner_eta) { TH1F *h_numerator_inner_eta = Numerator_inner_eta->getTH1F(); TH1F *h_denominator_inner_eta = Denominator_inner_eta->getTH1F(); TH1F *h_eff_inner_eta = h_eff_inner_eta_ID->getTH1F(); if (h_eff_inner_eta->GetSumw2N() == 0) h_eff_inner_eta->Sumw2(); h_eff_inner_eta->Divide(h_numerator_inner_eta, h_denominator_inner_eta, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon inner phi string numpath_inner_phi = inputdir + "/passProbes_ID_inner_phi"; string denpath_inner_phi = inputdir + "/allProbes_inner_phi"; MonitorElement *Numerator_inner_phi = igetter.get(numpath_inner_phi); MonitorElement *Denominator_inner_phi = igetter.get(denpath_inner_phi); if (Numerator_inner_phi && Denominator_inner_phi) { TH1F *h_numerator_inner_phi = Numerator_inner_phi->getTH1F(); TH1F *h_denominator_inner_phi = Denominator_inner_phi->getTH1F(); TH1F *h_eff_inner_phi = h_eff_inner_phi_ID->getTH1F(); if (h_eff_inner_phi->GetSumw2N() == 0) h_eff_inner_phi->Sumw2(); h_eff_inner_phi->Divide(h_numerator_inner_phi, h_denominator_inner_phi, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon Pt [EB] string numpath_EB_pt = inputdir + "/passProbes_ID_EB_pt"; string denpath_EB_pt = inputdir + "/allProbes_EB_pt"; MonitorElement *Numerator_EB_pt = igetter.get(numpath_EB_pt); MonitorElement *Denominator_EB_pt = igetter.get(denpath_EB_pt); if (Numerator_EB_pt && Denominator_EB_pt) { TH1F *h_numerator_EB_pt = Numerator_EB_pt->getTH1F(); TH1F *h_denominator_EB_pt = Denominator_EB_pt->getTH1F(); TH1F *h_eff_EB_pt = h_eff_pt_EB_ID->getTH1F(); if (h_eff_EB_pt->GetSumw2N() == 0) h_eff_EB_pt->Sumw2(); h_eff_EB_pt->Divide(h_numerator_EB_pt, h_denominator_EB_pt, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon Pt [EE] string numpath_EE_pt = inputdir + "/passProbes_ID_EE_pt"; string denpath_EE_pt = inputdir + "/allProbes_EE_pt"; MonitorElement *Numerator_EE_pt = igetter.get(numpath_EE_pt); MonitorElement *Denominator_EE_pt = igetter.get(denpath_EE_pt); if (Numerator_EE_pt && Denominator_EE_pt) { TH1F *h_numerator_EE_pt = Numerator_EE_pt->getTH1F(); TH1F *h_denominator_EE_pt = Denominator_EE_pt->getTH1F(); TH1F *h_eff_EE_pt = h_eff_pt_EE_ID->getTH1F(); if (h_eff_EE_pt->GetSumw2N() == 0) h_eff_EE_pt->Sumw2(); h_eff_EE_pt->Divide(h_numerator_EE_pt, h_denominator_EE_pt, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon Eta string numpath_eta = inputdir + "/passProbes_ID_eta"; string denpath_eta = inputdir + "/allProbes_eta"; MonitorElement *Numerator_eta = igetter.get(numpath_eta); MonitorElement *Denominator_eta = igetter.get(denpath_eta); if (Numerator_eta && Denominator_eta) { TH1F *h_numerator_eta = Numerator_eta->getTH1F(); TH1F *h_denominator_eta = Denominator_eta->getTH1F(); TH1F *h_eff_eta = h_eff_eta_ID->getTH1F(); if (h_eff_eta->GetSumw2N() == 0) h_eff_eta->Sumw2(); h_eff_eta->Divide(h_numerator_eta, h_denominator_eta, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon Eta [ pt > 20 ] string numpath_hp_eta = inputdir + "/passProbes_ID_hp_eta"; string denpath_hp_eta = inputdir + "/allProbes_hp_eta"; MonitorElement *Numerator_hp_eta = igetter.get(numpath_hp_eta); MonitorElement *Denominator_hp_eta = igetter.get(denpath_hp_eta); if (Numerator_hp_eta && Denominator_hp_eta) { TH1F *h_numerator_hp_eta = Numerator_hp_eta->getTH1F(); TH1F *h_denominator_hp_eta = Denominator_hp_eta->getTH1F(); TH1F *h_eff_hp_eta = h_eff_hp_eta_ID->getTH1F(); if (h_eff_hp_eta->GetSumw2N() == 0) h_eff_hp_eta->Sumw2(); h_eff_hp_eta->Divide(h_numerator_hp_eta, h_denominator_hp_eta, 1., 1., "B"); } /// --- Tight Muon efficiency vs muon Phi string numpath_phi = inputdir + "/passProbes_ID_phi"; string denpath_phi = inputdir + "/allProbes_phi"; MonitorElement *Numerator_phi = igetter.get(numpath_phi); MonitorElement *Denominator_phi = igetter.get(denpath_phi); if (Numerator_phi && Denominator_phi) { TH1F *h_numerator_phi = Numerator_phi->getTH1F(); TH1F *h_denominator_phi = Denominator_phi->getTH1F(); TH1F *h_eff_phi = h_eff_phi_ID->getTH1F(); if (h_eff_phi->GetSumw2N() == 0) h_eff_phi->Sumw2(); h_eff_phi->Divide(h_numerator_phi, h_denominator_phi, 1., 1., "B"); } /// --- Tight Muon + Detector Isolation efficiency vs muon Pt string numpath_detIso_pt = inputdir + "/passProbes_detIsoID_pt"; string denpath_detIso_pt = inputdir + "/allProbes_ID_pt"; MonitorElement *Numerator_detIso_pt = igetter.get(numpath_detIso_pt); MonitorElement *Denominator_detIso_pt = igetter.get(denpath_detIso_pt); if (Numerator_detIso_pt && Denominator_detIso_pt) { TH1F *h_numerator_detIso_pt = Numerator_detIso_pt->getTH1F(); TH1F *h_denominator_detIso_pt = Denominator_detIso_pt->getTH1F(); TH1F *h_eff_detIso_pt = h_eff_pt_detIsoID->getTH1F(); if (h_eff_detIso_pt->GetSumw2N() == 0) h_eff_detIso_pt->Sumw2(); h_eff_detIso_pt->Divide(h_numerator_detIso_pt, h_denominator_detIso_pt, 1., 1., "B"); } /// --- Tight Muon + Detector Isolation efficiency vs muon Pt [EB] string numpath_detIso_EB_pt = inputdir + "/passProbes_EB_detIsoID_pt"; string denpath_detIso_EB_pt = inputdir + "/allProbes_EB_ID_pt"; MonitorElement *Numerator_detIso_EB_pt = igetter.get(numpath_detIso_EB_pt); MonitorElement *Denominator_detIso_EB_pt = igetter.get(denpath_detIso_EB_pt); if (Numerator_detIso_EB_pt && Denominator_detIso_EB_pt) { TH1F *h_numerator_detIso_EB_pt = Numerator_detIso_EB_pt->getTH1F(); TH1F *h_denominator_detIso_EB_pt = Denominator_detIso_EB_pt->getTH1F(); TH1F *h_eff_detIso_EB_pt = h_eff_pt_EB_detIsoID->getTH1F(); if (h_eff_detIso_EB_pt->GetSumw2N() == 0) h_eff_detIso_EB_pt->Sumw2(); h_eff_detIso_EB_pt->Divide(h_numerator_detIso_EB_pt, h_denominator_detIso_EB_pt, 1., 1., "B"); } /// --- Tight Muon + Detector Isolation efficiency vs muon Pt [EE] string numpath_detIso_EE_pt = inputdir + "/passProbes_EE_detIsoID_pt"; string denpath_detIso_EE_pt = inputdir + "/allProbes_EE_ID_pt"; MonitorElement *Numerator_detIso_EE_pt = igetter.get(numpath_detIso_EE_pt); MonitorElement *Denominator_detIso_EE_pt = igetter.get(denpath_detIso_EE_pt); if (Numerator_detIso_EE_pt && Denominator_detIso_EE_pt) { TH1F *h_numerator_detIso_EE_pt = Numerator_detIso_EE_pt->getTH1F(); TH1F *h_denominator_detIso_EE_pt = Denominator_detIso_EE_pt->getTH1F(); TH1F *h_eff_detIso_EE_pt = h_eff_pt_EE_detIsoID->getTH1F(); if (h_eff_detIso_EE_pt->GetSumw2N() == 0) h_eff_detIso_EE_pt->Sumw2(); h_eff_detIso_EE_pt->Divide(h_numerator_detIso_EE_pt, h_denominator_detIso_EE_pt, 1., 1., "B"); } /// --- Tight Muon + PF Isolation efficiency vs muon Pt string numpath_pfIso_pt = inputdir + "/passProbes_pfIsoID_pt"; string denpath_pfIso_pt = inputdir + "/allProbes_ID_pt"; MonitorElement *Numerator_pfIso_pt = igetter.get(numpath_pfIso_pt); MonitorElement *Denominator_pfIso_pt = igetter.get(denpath_pfIso_pt); if (Numerator_pfIso_pt && Denominator_pfIso_pt) { TH1F *h_numerator_pfIso_pt = Numerator_pfIso_pt->getTH1F(); TH1F *h_denominator_pfIso_pt = Denominator_pfIso_pt->getTH1F(); TH1F *h_eff_pfIso_pt = h_eff_pt_pfIsoID->getTH1F(); if (h_eff_pfIso_pt->GetSumw2N() == 0) h_eff_pfIso_pt->Sumw2(); h_eff_pfIso_pt->Divide(h_numerator_pfIso_pt, h_denominator_pfIso_pt, 1., 1., "B"); } /// --- Tight Muon + PF Isolation efficiency vs muon Pt [EB] string numpath_pfIso_EB_pt = inputdir + "/passProbes_EB_pfIsoID_pt"; string denpath_pfIso_EB_pt = inputdir + "/allProbes_EB_ID_pt"; MonitorElement *Numerator_pfIso_EB_pt = igetter.get(numpath_pfIso_EB_pt); MonitorElement *Denominator_pfIso_EB_pt = igetter.get(denpath_pfIso_EB_pt); if (Numerator_pfIso_EB_pt && Denominator_pfIso_EB_pt) { TH1F *h_numerator_pfIso_EB_pt = Numerator_pfIso_EB_pt->getTH1F(); TH1F *h_denominator_pfIso_EB_pt = Denominator_pfIso_EB_pt->getTH1F(); TH1F *h_eff_pfIso_EB_pt = h_eff_pt_EB_pfIsoID->getTH1F(); if (h_eff_pfIso_EB_pt->GetSumw2N() == 0) h_eff_pfIso_EB_pt->Sumw2(); h_eff_pfIso_EB_pt->Divide(h_numerator_pfIso_EB_pt, h_denominator_pfIso_EB_pt, 1., 1., "B"); } /// --- Tight Muon + PF Isolation efficiency vs muon Pt [EE] string numpath_pfIso_EE_pt = inputdir + "/passProbes_EE_pfIsoID_pt"; string denpath_pfIso_EE_pt = inputdir + "/allProbes_EE_ID_pt"; MonitorElement *Numerator_pfIso_EE_pt = igetter.get(numpath_pfIso_EE_pt); MonitorElement *Denominator_pfIso_EE_pt = igetter.get(denpath_pfIso_EE_pt); if (Numerator_pfIso_EE_pt && Denominator_pfIso_EE_pt) { TH1F *h_numerator_pfIso_EE_pt = Numerator_pfIso_EE_pt->getTH1F(); TH1F *h_denominator_pfIso_EE_pt = Denominator_pfIso_EE_pt->getTH1F(); TH1F *h_eff_pfIso_EE_pt = h_eff_pt_EE_pfIsoID->getTH1F(); if (h_eff_pfIso_EE_pt->GetSumw2N() == 0) h_eff_pfIso_EE_pt->Sumw2(); h_eff_pfIso_EE_pt->Divide(h_numerator_pfIso_EE_pt, h_denominator_pfIso_EE_pt, 1., 1., "B"); } /// --- Tight Muon + PF Isolation efficiency vs muon number of reco Vertex string numpath_pfIso_nvtx = inputdir + "/passProbes_pfIsoID_nVtx"; string denpath_pfIso_nvtx = inputdir + "/allProbes_ID_nVtx"; MonitorElement *Numerator_pfIso_nvtx = igetter.get(numpath_pfIso_nvtx); MonitorElement *Denominator_pfIso_nvtx = igetter.get(denpath_pfIso_nvtx); if (Numerator_pfIso_nvtx && Denominator_pfIso_nvtx) { TH1F *h_numerator_pfIso_nvtx = Numerator_pfIso_nvtx->getTH1F(); TH1F *h_denominator_pfIso_nvtx = Denominator_pfIso_nvtx->getTH1F(); TH1F *h_eff_pfIso_nvtx = h_eff_vtx_pfIsoID->getTH1F(); if (h_eff_pfIso_nvtx->GetSumw2N() == 0) h_eff_pfIso_nvtx->Sumw2(); h_eff_pfIso_nvtx->Divide(h_numerator_pfIso_nvtx, h_denominator_pfIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + detector-Based Isolation efficiency vs muon number of reco Vertex string numpath_detIso_nvtx = inputdir + "/passProbes_detIsoID_nVtx"; string denpath_detIso_nvtx = inputdir + "/allProbes_ID_nVtx"; MonitorElement *Numerator_detIso_nvtx = igetter.get(numpath_detIso_nvtx); MonitorElement *Denominator_detIso_nvtx = igetter.get(denpath_detIso_nvtx); if (Numerator_detIso_nvtx && Denominator_detIso_nvtx) { TH1F *h_numerator_detIso_nvtx = Numerator_detIso_nvtx->getTH1F(); TH1F *h_denominator_detIso_nvtx = Denominator_detIso_nvtx->getTH1F(); TH1F *h_eff_detIso_nvtx = h_eff_vtx_detIsoID->getTH1F(); if (h_eff_detIso_nvtx->GetSumw2N() == 0) h_eff_detIso_nvtx->Sumw2(); h_eff_detIso_nvtx->Divide(h_numerator_detIso_nvtx, h_denominator_detIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + detector-Based Isolation efficiency vs muon number of reco Vertex [EB] numpath_detIso_nvtx = inputdir + "/passProbes_EB_detIsoID_nVtx"; denpath_detIso_nvtx = inputdir + "/allProbes_EB_ID_nVtx"; Numerator_detIso_nvtx = igetter.get(numpath_detIso_nvtx); Denominator_detIso_nvtx = igetter.get(denpath_detIso_nvtx); if (Numerator_detIso_nvtx && Denominator_detIso_nvtx) { TH1F *h_numerator_detIso_nvtx = Numerator_detIso_nvtx->getTH1F(); TH1F *h_denominator_detIso_nvtx = Denominator_detIso_nvtx->getTH1F(); TH1F *h_eff_detIso_nvtx = h_eff_vtx_EB_detIsoID->getTH1F(); if (h_eff_detIso_nvtx->GetSumw2N() == 0) h_eff_detIso_nvtx->Sumw2(); h_eff_detIso_nvtx->Divide(h_numerator_detIso_nvtx, h_denominator_detIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + detector-Based Isolation efficiency vs muon number of reco Vertex [EE] numpath_detIso_nvtx = inputdir + "/passProbes_EE_detIsoID_nVtx"; denpath_detIso_nvtx = inputdir + "/allProbes_EE_ID_nVtx"; Numerator_detIso_nvtx = igetter.get(numpath_detIso_nvtx); Denominator_detIso_nvtx = igetter.get(denpath_detIso_nvtx); if (Numerator_detIso_nvtx && Denominator_detIso_nvtx) { TH1F *h_numerator_detIso_nvtx = Numerator_detIso_nvtx->getTH1F(); TH1F *h_denominator_detIso_nvtx = Denominator_detIso_nvtx->getTH1F(); TH1F *h_eff_detIso_nvtx = h_eff_vtx_EE_detIsoID->getTH1F(); if (h_eff_detIso_nvtx->GetSumw2N() == 0) h_eff_detIso_nvtx->Sumw2(); h_eff_detIso_nvtx->Divide(h_numerator_detIso_nvtx, h_denominator_detIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + PF-Based Isolation efficiency vs muon number of reco Vertex [EB] numpath_pfIso_nvtx = inputdir + "/passProbes_EB_pfIsoID_nVtx"; denpath_pfIso_nvtx = inputdir + "/allProbes_EB_ID_nVtx"; Numerator_pfIso_nvtx = igetter.get(numpath_pfIso_nvtx); Denominator_pfIso_nvtx = igetter.get(denpath_pfIso_nvtx); if (Numerator_pfIso_nvtx && Denominator_pfIso_nvtx) { TH1F *h_numerator_pfIso_nvtx = Numerator_pfIso_nvtx->getTH1F(); TH1F *h_denominator_pfIso_nvtx = Denominator_pfIso_nvtx->getTH1F(); TH1F *h_eff_pfIso_nvtx = h_eff_vtx_EB_pfIsoID->getTH1F(); if (h_eff_pfIso_nvtx->GetSumw2N() == 0) h_eff_pfIso_nvtx->Sumw2(); h_eff_pfIso_nvtx->Divide(h_numerator_pfIso_nvtx, h_denominator_pfIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + PF-Based Isolation efficiency vs muon number of reco Vertex [EE] numpath_pfIso_nvtx = inputdir + "/passProbes_EE_pfIsoID_nVtx"; denpath_pfIso_nvtx = inputdir + "/allProbes_EE_ID_nVtx"; Numerator_pfIso_nvtx = igetter.get(numpath_pfIso_nvtx); Denominator_pfIso_nvtx = igetter.get(denpath_pfIso_nvtx); if (Numerator_pfIso_nvtx && Denominator_pfIso_nvtx) { TH1F *h_numerator_pfIso_nvtx = Numerator_pfIso_nvtx->getTH1F(); TH1F *h_denominator_pfIso_nvtx = Denominator_pfIso_nvtx->getTH1F(); TH1F *h_eff_pfIso_nvtx = h_eff_vtx_EE_pfIsoID->getTH1F(); if (h_eff_pfIso_nvtx->GetSumw2N() == 0) h_eff_pfIso_nvtx->Sumw2(); h_eff_pfIso_nvtx->Divide(h_numerator_pfIso_nvtx, h_denominator_pfIso_nvtx, 1., 1., "B"); } /// --- Tight Muon + PF IsodBlation corrected by deltaBeta efficiency vs muon Pt string numpath_pfIsodB_pt = inputdir + "/passProbes_pfIsodBID_pt"; string denpath_pfIsodB_pt = inputdir + "/allProbes_ID_pt"; MonitorElement *Numerator_pfIsodB_pt = igetter.get(numpath_pfIsodB_pt); MonitorElement *Denominator_pfIsodB_pt = igetter.get(denpath_pfIsodB_pt); if (Numerator_pfIsodB_pt && Denominator_pfIsodB_pt) { TH1F *h_numerator_pfIsodB_pt = Numerator_pfIsodB_pt->getTH1F(); TH1F *h_denominator_pfIsodB_pt = Denominator_pfIsodB_pt->getTH1F(); TH1F *h_eff_pfIsodB_pt = h_eff_pt_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_pt->GetSumw2N() == 0) h_eff_pfIsodB_pt->Sumw2(); h_eff_pfIsodB_pt->Divide(h_numerator_pfIsodB_pt, h_denominator_pfIsodB_pt, 1., 1., "B"); } /// --- Tight Muon + PF IsodBlation corrected by deltaBeta efficiency vs muon Pt [EB] string numpath_pfIsodB_EB_pt = inputdir + "/passProbes_EB_pfIsodBID_pt"; string denpath_pfIsodB_EB_pt = inputdir + "/allProbes_EB_ID_pt"; MonitorElement *Numerator_pfIsodB_EB_pt = igetter.get(numpath_pfIsodB_EB_pt); MonitorElement *Denominator_pfIsodB_EB_pt = igetter.get(denpath_pfIsodB_EB_pt); if (Numerator_pfIsodB_EB_pt && Denominator_pfIsodB_EB_pt) { TH1F *h_numerator_pfIsodB_EB_pt = Numerator_pfIsodB_EB_pt->getTH1F(); TH1F *h_denominator_pfIsodB_EB_pt = Denominator_pfIsodB_EB_pt->getTH1F(); TH1F *h_eff_pfIsodB_EB_pt = h_eff_pt_EB_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_EB_pt->GetSumw2N() == 0) h_eff_pfIsodB_EB_pt->Sumw2(); h_eff_pfIsodB_EB_pt->Divide(h_numerator_pfIsodB_EB_pt, h_denominator_pfIsodB_EB_pt, 1., 1., "B"); } /// --- Tight Muon + PF IsodBlation corrected by deltaBeta efficiency vs muon Pt [EE] string numpath_pfIsodB_EE_pt = inputdir + "/passProbes_EE_pfIsodBID_pt"; string denpath_pfIsodB_EE_pt = inputdir + "/allProbes_EE_ID_pt"; MonitorElement *Numerator_pfIsodB_EE_pt = igetter.get(numpath_pfIsodB_EE_pt); MonitorElement *Denominator_pfIsodB_EE_pt = igetter.get(denpath_pfIsodB_EE_pt); if (Numerator_pfIsodB_EE_pt && Denominator_pfIsodB_EE_pt) { TH1F *h_numerator_pfIsodB_EE_pt = Numerator_pfIsodB_EE_pt->getTH1F(); TH1F *h_denominator_pfIsodB_EE_pt = Denominator_pfIsodB_EE_pt->getTH1F(); TH1F *h_eff_pfIsodB_EE_pt = h_eff_pt_EE_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_EE_pt->GetSumw2N() == 0) h_eff_pfIsodB_EE_pt->Sumw2(); h_eff_pfIsodB_EE_pt->Divide(h_numerator_pfIsodB_EE_pt, h_denominator_pfIsodB_EE_pt, 1., 1., "B"); } /// --- Tight Muon + PF Isolation corrected by deltaBeta efficiency vs muon number of reco Vertex string numpath_pfIsodB_nvtx = inputdir + "/passProbes_pfIsodBID_nVtx"; string denpath_pfIsodB_nvtx = inputdir + "/allProbes_ID_nVtx"; MonitorElement *Numerator_pfIsodB_nvtx = igetter.get(numpath_pfIsodB_nvtx); MonitorElement *Denominator_pfIsodB_nvtx = igetter.get(denpath_pfIsodB_nvtx); if (Numerator_pfIsodB_nvtx && Denominator_pfIsodB_nvtx) { TH1F *h_numerator_pfIsodB_nvtx = Numerator_pfIsodB_nvtx->getTH1F(); TH1F *h_denominator_pfIsodB_nvtx = Denominator_pfIsodB_nvtx->getTH1F(); TH1F *h_eff_pfIsodB_nvtx = h_eff_vtx_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_nvtx->GetSumw2N() == 0) h_eff_pfIsodB_nvtx->Sumw2(); h_eff_pfIsodB_nvtx->Divide(h_numerator_pfIsodB_nvtx, h_denominator_pfIsodB_nvtx, 1., 1., "B"); } /// --- Tight Muon + PF-Based Isolation corrected by deltaBeta efficiency vs muon number of reco Vertex [EB] numpath_pfIsodB_nvtx = inputdir + "/passProbes_EB_pfIsodBID_nVtx"; denpath_pfIsodB_nvtx = inputdir + "/allProbes_EB_ID_nVtx"; Numerator_pfIsodB_nvtx = igetter.get(numpath_pfIsodB_nvtx); Denominator_pfIsodB_nvtx = igetter.get(denpath_pfIsodB_nvtx); if (Numerator_pfIsodB_nvtx && Denominator_pfIsodB_nvtx) { TH1F *h_numerator_pfIsodB_nvtx = Numerator_pfIsodB_nvtx->getTH1F(); TH1F *h_denominator_pfIsodB_nvtx = Denominator_pfIsodB_nvtx->getTH1F(); TH1F *h_eff_pfIsodB_nvtx = h_eff_vtx_EB_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_nvtx->GetSumw2N() == 0) h_eff_pfIsodB_nvtx->Sumw2(); h_eff_pfIsodB_nvtx->Divide(h_numerator_pfIsodB_nvtx, h_denominator_pfIsodB_nvtx, 1., 1., "B"); } /// --- Tight Muon + PF-Based Isolation corrected by deltaBeta efficiency vs muon number of reco Vertex [EE] numpath_pfIsodB_nvtx = inputdir + "/passProbes_EE_pfIsodBID_nVtx"; denpath_pfIsodB_nvtx = inputdir + "/allProbes_EE_ID_nVtx"; Numerator_pfIsodB_nvtx = igetter.get(numpath_pfIsodB_nvtx); Denominator_pfIsodB_nvtx = igetter.get(denpath_pfIsodB_nvtx); if (Numerator_pfIsodB_nvtx && Denominator_pfIsodB_nvtx) { TH1F *h_numerator_pfIsodB_nvtx = Numerator_pfIsodB_nvtx->getTH1F(); TH1F *h_denominator_pfIsodB_nvtx = Denominator_pfIsodB_nvtx->getTH1F(); TH1F *h_eff_pfIsodB_nvtx = h_eff_vtx_EE_pfIsodBID->getTH1F(); if (h_eff_pfIsodB_nvtx->GetSumw2N() == 0) h_eff_pfIsodB_nvtx->Sumw2(); h_eff_pfIsodB_nvtx->Divide(h_numerator_pfIsodB_nvtx, h_denominator_pfIsodB_nvtx, 1., 1., "B"); } }
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 "v8.h" #include "api.h" #include "arguments.h" #include "ast.h" #include "code-stubs.h" #include "cpu-profiler.h" #include "gdb-jit.h" #include "ic-inl.h" #include "stub-cache.h" #include "type-info.h" #include "vm-state-inl.h" namespace v8 { namespace internal { // ----------------------------------------------------------------------- // StubCache implementation. StubCache::StubCache(Isolate* isolate) : isolate_(isolate) { } void StubCache::Initialize() { ASSERT(IsPowerOf2(kPrimaryTableSize)); ASSERT(IsPowerOf2(kSecondaryTableSize)); Clear(); } Code* StubCache::Set(Name* name, Map* map, Code* code) { // Get the flags from the code. Code::Flags flags = Code::RemoveTypeFromFlags(code->flags()); // Validate that the name does not move on scavenge, and that we // can use identity checks instead of structural equality checks. ASSERT(!heap()->InNewSpace(name)); ASSERT(name->IsUniqueName()); // The state bits are not important to the hash function because // the stub cache only contains monomorphic stubs. Make sure that // the bits are the least significant so they will be the ones // masked out. ASSERT(Code::ExtractICStateFromFlags(flags) == MONOMORPHIC); STATIC_ASSERT((Code::ICStateField::kMask & 1) == 1); // Make sure that the code type is not included in the hash. ASSERT(Code::ExtractTypeFromFlags(flags) == 0); // Compute the primary entry. int primary_offset = PrimaryOffset(name, flags, map); Entry* primary = entry(primary_, primary_offset); Code* old_code = primary->value; // If the primary entry has useful data in it, we retire it to the // secondary cache before overwriting it. if (old_code != isolate_->builtins()->builtin(Builtins::kIllegal)) { Map* old_map = primary->map; Code::Flags old_flags = Code::RemoveTypeFromFlags(old_code->flags()); int seed = PrimaryOffset(primary->key, old_flags, old_map); int secondary_offset = SecondaryOffset(primary->key, old_flags, seed); Entry* secondary = entry(secondary_, secondary_offset); *secondary = *primary; } // Update primary cache. primary->key = name; primary->value = code; primary->map = map; isolate()->counters()->megamorphic_stub_cache_updates()->Increment(); return code; } Handle<Code> StubCache::FindIC(Handle<Name> name, Handle<Map> stub_holder, Code::Kind kind, ExtraICState extra_state, InlineCacheHolderFlag cache_holder) { Code::Flags flags = Code::ComputeMonomorphicFlags( kind, extra_state, cache_holder); Handle<Object> probe(stub_holder->FindInCodeCache(*name, flags), isolate_); if (probe->IsCode()) return Handle<Code>::cast(probe); return Handle<Code>::null(); } Handle<Code> StubCache::FindHandler(Handle<Name> name, Handle<Map> stub_holder, Code::Kind kind, InlineCacheHolderFlag cache_holder, Code::StubType type) { Code::Flags flags = Code::ComputeHandlerFlags(kind, type, cache_holder); Handle<Object> probe(stub_holder->FindInCodeCache(*name, flags), isolate_); if (probe->IsCode()) return Handle<Code>::cast(probe); return Handle<Code>::null(); } Handle<Code> StubCache::ComputeMonomorphicIC( Code::Kind kind, Handle<Name> name, Handle<HeapType> type, Handle<Code> handler, ExtraICState extra_ic_state) { InlineCacheHolderFlag flag = IC::GetCodeCacheFlag(*type); Handle<Map> stub_holder; Handle<Code> ic; // There are multiple string maps that all use the same prototype. That // prototype cannot hold multiple handlers, one for each of the string maps, // for a single name. Hence, turn off caching of the IC. bool can_be_cached = !type->Is(HeapType::String()); if (can_be_cached) { stub_holder = IC::GetCodeCacheHolder(flag, *type, isolate()); ic = FindIC(name, stub_holder, kind, extra_ic_state, flag); if (!ic.is_null()) return ic; } if (kind == Code::LOAD_IC) { LoadStubCompiler ic_compiler(isolate(), extra_ic_state, flag); ic = ic_compiler.CompileMonomorphicIC(type, handler, name); } else if (kind == Code::KEYED_LOAD_IC) { KeyedLoadStubCompiler ic_compiler(isolate(), extra_ic_state, flag); ic = ic_compiler.CompileMonomorphicIC(type, handler, name); } else if (kind == Code::STORE_IC) { StoreStubCompiler ic_compiler(isolate(), extra_ic_state); ic = ic_compiler.CompileMonomorphicIC(type, handler, name); } else { ASSERT(kind == Code::KEYED_STORE_IC); ASSERT(STANDARD_STORE == KeyedStoreIC::GetKeyedAccessStoreMode(extra_ic_state)); KeyedStoreStubCompiler ic_compiler(isolate(), extra_ic_state); ic = ic_compiler.CompileMonomorphicIC(type, handler, name); } if (can_be_cached) Map::UpdateCodeCache(stub_holder, name, ic); return ic; } Handle<Code> StubCache::ComputeLoadNonexistent(Handle<Name> name, Handle<HeapType> type) { InlineCacheHolderFlag flag = IC::GetCodeCacheFlag(*type); Handle<Map> stub_holder = IC::GetCodeCacheHolder(flag, *type, isolate()); // If no dictionary mode objects are present in the prototype chain, the load // nonexistent IC stub can be shared for all names for a given map and we use // the empty string for the map cache in that case. If there are dictionary // mode objects involved, we need to do negative lookups in the stub and // therefore the stub will be specific to the name. Handle<Map> current_map = stub_holder; Handle<Name> cache_name = current_map->is_dictionary_map() ? name : Handle<Name>::cast(isolate()->factory()->nonexistent_symbol()); Handle<Object> next(current_map->prototype(), isolate()); Handle<JSObject> last = Handle<JSObject>::null(); while (!next->IsNull()) { last = Handle<JSObject>::cast(next); next = handle(current_map->prototype(), isolate()); current_map = handle(Handle<HeapObject>::cast(next)->map()); if (current_map->is_dictionary_map()) cache_name = name; } // Compile the stub that is either shared for all names or // name specific if there are global objects involved. Handle<Code> handler = FindHandler( cache_name, stub_holder, Code::LOAD_IC, flag, Code::FAST); if (!handler.is_null()) { return handler; } LoadStubCompiler compiler(isolate_, kNoExtraICState, flag); handler = compiler.CompileLoadNonexistent(type, last, cache_name); Map::UpdateCodeCache(stub_holder, cache_name, handler); return handler; } Handle<Code> StubCache::ComputeKeyedLoadElement(Handle<Map> receiver_map) { Code::Flags flags = Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC); Handle<Name> name = isolate()->factory()->KeyedLoadElementMonomorphic_string(); Handle<Object> probe(receiver_map->FindInCodeCache(*name, flags), isolate_); if (probe->IsCode()) return Handle<Code>::cast(probe); KeyedLoadStubCompiler compiler(isolate()); Handle<Code> code = compiler.CompileLoadElement(receiver_map); Map::UpdateCodeCache(receiver_map, name, code); return code; } Handle<Code> StubCache::ComputeKeyedStoreElement( Handle<Map> receiver_map, StrictMode strict_mode, KeyedAccessStoreMode store_mode) { ExtraICState extra_state = KeyedStoreIC::ComputeExtraICState(strict_mode, store_mode); Code::Flags flags = Code::ComputeMonomorphicFlags( Code::KEYED_STORE_IC, extra_state); ASSERT(store_mode == STANDARD_STORE || store_mode == STORE_AND_GROW_NO_TRANSITION || store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS || store_mode == STORE_NO_TRANSITION_HANDLE_COW); Handle<String> name = isolate()->factory()->KeyedStoreElementMonomorphic_string(); Handle<Object> probe(receiver_map->FindInCodeCache(*name, flags), isolate_); if (probe->IsCode()) return Handle<Code>::cast(probe); KeyedStoreStubCompiler compiler(isolate(), extra_state); Handle<Code> code = compiler.CompileStoreElement(receiver_map); Map::UpdateCodeCache(receiver_map, name, code); ASSERT(KeyedStoreIC::GetKeyedAccessStoreMode(code->extra_ic_state()) == store_mode); return code; } #define CALL_LOGGER_TAG(kind, type) (Logger::KEYED_##type) static void FillCache(Isolate* isolate, Handle<Code> code) { Handle<UnseededNumberDictionary> dictionary = UnseededNumberDictionary::Set(isolate->factory()->non_monomorphic_cache(), code->flags(), code); isolate->heap()->public_set_non_monomorphic_cache(*dictionary); } Code* StubCache::FindPreMonomorphicIC(Code::Kind kind, ExtraICState state) { Code::Flags flags = Code::ComputeFlags(kind, PREMONOMORPHIC, state); UnseededNumberDictionary* dictionary = isolate()->heap()->non_monomorphic_cache(); int entry = dictionary->FindEntry(isolate(), flags); ASSERT(entry != -1); Object* code = dictionary->ValueAt(entry); // This might be called during the marking phase of the collector // hence the unchecked cast. return reinterpret_cast<Code*>(code); } Handle<Code> StubCache::ComputeLoad(InlineCacheState ic_state, ExtraICState extra_state) { Code::Flags flags = Code::ComputeFlags(Code::LOAD_IC, ic_state, extra_state); Handle<UnseededNumberDictionary> cache = isolate_->factory()->non_monomorphic_cache(); int entry = cache->FindEntry(isolate_, flags); if (entry != -1) return Handle<Code>(Code::cast(cache->ValueAt(entry))); StubCompiler compiler(isolate_); Handle<Code> code; if (ic_state == UNINITIALIZED) { code = compiler.CompileLoadInitialize(flags); } else if (ic_state == PREMONOMORPHIC) { code = compiler.CompileLoadPreMonomorphic(flags); } else if (ic_state == MEGAMORPHIC) { code = compiler.CompileLoadMegamorphic(flags); } else { UNREACHABLE(); } FillCache(isolate_, code); return code; } Handle<Code> StubCache::ComputeStore(InlineCacheState ic_state, ExtraICState extra_state) { Code::Flags flags = Code::ComputeFlags(Code::STORE_IC, ic_state, extra_state); Handle<UnseededNumberDictionary> cache = isolate_->factory()->non_monomorphic_cache(); int entry = cache->FindEntry(isolate_, flags); if (entry != -1) return Handle<Code>(Code::cast(cache->ValueAt(entry))); StubCompiler compiler(isolate_); Handle<Code> code; if (ic_state == UNINITIALIZED) { code = compiler.CompileStoreInitialize(flags); } else if (ic_state == PREMONOMORPHIC) { code = compiler.CompileStorePreMonomorphic(flags); } else if (ic_state == GENERIC) { code = compiler.CompileStoreGeneric(flags); } else if (ic_state == MEGAMORPHIC) { code = compiler.CompileStoreMegamorphic(flags); } else { UNREACHABLE(); } FillCache(isolate_, code); return code; } Handle<Code> StubCache::ComputeCompareNil(Handle<Map> receiver_map, CompareNilICStub& stub) { Handle<String> name(isolate_->heap()->empty_string()); if (!receiver_map->is_shared()) { Handle<Code> cached_ic = FindIC(name, receiver_map, Code::COMPARE_NIL_IC, stub.GetExtraICState()); if (!cached_ic.is_null()) return cached_ic; } Code::FindAndReplacePattern pattern; pattern.Add(isolate_->factory()->meta_map(), receiver_map); Handle<Code> ic = stub.GetCodeCopy(isolate_, pattern); if (!receiver_map->is_shared()) { Map::UpdateCodeCache(receiver_map, name, ic); } return ic; } // TODO(verwaest): Change this method so it takes in a TypeHandleList. Handle<Code> StubCache::ComputeLoadElementPolymorphic( MapHandleList* receiver_maps) { Code::Flags flags = Code::ComputeFlags(Code::KEYED_LOAD_IC, POLYMORPHIC); Handle<PolymorphicCodeCache> cache = isolate_->factory()->polymorphic_code_cache(); Handle<Object> probe = cache->Lookup(receiver_maps, flags); if (probe->IsCode()) return Handle<Code>::cast(probe); TypeHandleList types(receiver_maps->length()); for (int i = 0; i < receiver_maps->length(); i++) { types.Add(HeapType::Class(receiver_maps->at(i), isolate())); } CodeHandleList handlers(receiver_maps->length()); KeyedLoadStubCompiler compiler(isolate_); compiler.CompileElementHandlers(receiver_maps, &handlers); Handle<Code> code = compiler.CompilePolymorphicIC( &types, &handlers, factory()->empty_string(), Code::NORMAL, ELEMENT); isolate()->counters()->keyed_load_polymorphic_stubs()->Increment(); PolymorphicCodeCache::Update(cache, receiver_maps, flags, code); return code; } Handle<Code> StubCache::ComputePolymorphicIC( Code::Kind kind, TypeHandleList* types, CodeHandleList* handlers, int number_of_valid_types, Handle<Name> name, ExtraICState extra_ic_state) { Handle<Code> handler = handlers->at(0); Code::StubType type = number_of_valid_types == 1 ? handler->type() : Code::NORMAL; if (kind == Code::LOAD_IC) { LoadStubCompiler ic_compiler(isolate_, extra_ic_state); return ic_compiler.CompilePolymorphicIC( types, handlers, name, type, PROPERTY); } else { ASSERT(kind == Code::STORE_IC); StoreStubCompiler ic_compiler(isolate_, extra_ic_state); return ic_compiler.CompilePolymorphicIC( types, handlers, name, type, PROPERTY); } } Handle<Code> StubCache::ComputeStoreElementPolymorphic( MapHandleList* receiver_maps, KeyedAccessStoreMode store_mode, StrictMode strict_mode) { ASSERT(store_mode == STANDARD_STORE || store_mode == STORE_AND_GROW_NO_TRANSITION || store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS || store_mode == STORE_NO_TRANSITION_HANDLE_COW); Handle<PolymorphicCodeCache> cache = isolate_->factory()->polymorphic_code_cache(); ExtraICState extra_state = KeyedStoreIC::ComputeExtraICState( strict_mode, store_mode); Code::Flags flags = Code::ComputeFlags(Code::KEYED_STORE_IC, POLYMORPHIC, extra_state); Handle<Object> probe = cache->Lookup(receiver_maps, flags); if (probe->IsCode()) return Handle<Code>::cast(probe); KeyedStoreStubCompiler compiler(isolate_, extra_state); Handle<Code> code = compiler.CompileStoreElementPolymorphic(receiver_maps); PolymorphicCodeCache::Update(cache, receiver_maps, flags, code); return code; } void StubCache::Clear() { Code* empty = isolate_->builtins()->builtin(Builtins::kIllegal); for (int i = 0; i < kPrimaryTableSize; i++) { primary_[i].key = heap()->empty_string(); primary_[i].map = NULL; primary_[i].value = empty; } for (int j = 0; j < kSecondaryTableSize; j++) { secondary_[j].key = heap()->empty_string(); secondary_[j].map = NULL; secondary_[j].value = empty; } } void StubCache::CollectMatchingMaps(SmallMapList* types, Handle<Name> name, Code::Flags flags, Handle<Context> native_context, Zone* zone) { for (int i = 0; i < kPrimaryTableSize; i++) { if (primary_[i].key == *name) { Map* map = primary_[i].map; // Map can be NULL, if the stub is constant function call // with a primitive receiver. if (map == NULL) continue; int offset = PrimaryOffset(*name, flags, map); if (entry(primary_, offset) == &primary_[i] && !TypeFeedbackOracle::CanRetainOtherContext(map, *native_context)) { types->AddMapIfMissing(Handle<Map>(map), zone); } } } for (int i = 0; i < kSecondaryTableSize; i++) { if (secondary_[i].key == *name) { Map* map = secondary_[i].map; // Map can be NULL, if the stub is constant function call // with a primitive receiver. if (map == NULL) continue; // Lookup in primary table and skip duplicates. int primary_offset = PrimaryOffset(*name, flags, map); // Lookup in secondary table and add matches. int offset = SecondaryOffset(*name, flags, primary_offset); if (entry(secondary_, offset) == &secondary_[i] && !TypeFeedbackOracle::CanRetainOtherContext(map, *native_context)) { types->AddMapIfMissing(Handle<Map>(map), zone); } } } } // ------------------------------------------------------------------------ // StubCompiler implementation. RUNTIME_FUNCTION(MaybeObject*, StoreCallbackProperty) { JSObject* receiver = JSObject::cast(args[0]); JSObject* holder = JSObject::cast(args[1]); ExecutableAccessorInfo* callback = ExecutableAccessorInfo::cast(args[2]); Address setter_address = v8::ToCData<Address>(callback->setter()); v8::AccessorSetterCallback fun = FUNCTION_CAST<v8::AccessorSetterCallback>(setter_address); ASSERT(fun != NULL); ASSERT(callback->IsCompatibleReceiver(receiver)); Handle<Name> name = args.at<Name>(3); Handle<Object> value = args.at<Object>(4); HandleScope scope(isolate); // TODO(rossberg): Support symbols in the API. if (name->IsSymbol()) return *value; Handle<String> str = Handle<String>::cast(name); LOG(isolate, ApiNamedPropertyAccess("store", receiver, *name)); PropertyCallbackArguments custom_args(isolate, callback->data(), receiver, holder); custom_args.Call(fun, v8::Utils::ToLocal(str), v8::Utils::ToLocal(value)); RETURN_IF_SCHEDULED_EXCEPTION(isolate); return *value; } /** * Attempts to load a property with an interceptor (which must be present), * but doesn't search the prototype chain. * * Returns |Heap::no_interceptor_result_sentinel()| if interceptor doesn't * provide any value for the given name. */ RUNTIME_FUNCTION(MaybeObject*, LoadPropertyWithInterceptorOnly) { ASSERT(args.length() == StubCache::kInterceptorArgsLength); Handle<Name> name_handle = args.at<Name>(StubCache::kInterceptorArgsNameIndex); Handle<InterceptorInfo> interceptor_info = args.at<InterceptorInfo>(StubCache::kInterceptorArgsInfoIndex); // TODO(rossberg): Support symbols in the API. if (name_handle->IsSymbol()) return isolate->heap()->no_interceptor_result_sentinel(); Handle<String> name = Handle<String>::cast(name_handle); Address getter_address = v8::ToCData<Address>(interceptor_info->getter()); v8::NamedPropertyGetterCallback getter = FUNCTION_CAST<v8::NamedPropertyGetterCallback>(getter_address); ASSERT(getter != NULL); Handle<JSObject> receiver = args.at<JSObject>(StubCache::kInterceptorArgsThisIndex); Handle<JSObject> holder = args.at<JSObject>(StubCache::kInterceptorArgsHolderIndex); PropertyCallbackArguments callback_args( isolate, interceptor_info->data(), *receiver, *holder); { // Use the interceptor getter. HandleScope scope(isolate); v8::Handle<v8::Value> r = callback_args.Call(getter, v8::Utils::ToLocal(name)); RETURN_IF_SCHEDULED_EXCEPTION(isolate); if (!r.IsEmpty()) { Handle<Object> result = v8::Utils::OpenHandle(*r); result->VerifyApiCallResultType(); return *v8::Utils::OpenHandle(*r); } } return isolate->heap()->no_interceptor_result_sentinel(); } static MaybeObject* ThrowReferenceError(Isolate* isolate, Name* name) { // If the load is non-contextual, just return the undefined result. // Note that both keyed and non-keyed loads may end up here. HandleScope scope(isolate); LoadIC ic(IC::NO_EXTRA_FRAME, isolate); if (ic.contextual_mode() != CONTEXTUAL) { return isolate->heap()->undefined_value(); } // Throw a reference error. Handle<Name> name_handle(name); Handle<Object> error = isolate->factory()->NewReferenceError("not_defined", HandleVector(&name_handle, 1)); return isolate->Throw(*error); } static Handle<Object> LoadWithInterceptor(Arguments* args, PropertyAttributes* attrs) { ASSERT(args->length() == StubCache::kInterceptorArgsLength); Handle<Name> name_handle = args->at<Name>(StubCache::kInterceptorArgsNameIndex); Handle<InterceptorInfo> interceptor_info = args->at<InterceptorInfo>(StubCache::kInterceptorArgsInfoIndex); Handle<JSObject> receiver_handle = args->at<JSObject>(StubCache::kInterceptorArgsThisIndex); Handle<JSObject> holder_handle = args->at<JSObject>(StubCache::kInterceptorArgsHolderIndex); Isolate* isolate = receiver_handle->GetIsolate(); // TODO(rossberg): Support symbols in the API. if (name_handle->IsSymbol()) { return JSObject::GetPropertyPostInterceptor( holder_handle, receiver_handle, name_handle, attrs); } Handle<String> name = Handle<String>::cast(name_handle); Address getter_address = v8::ToCData<Address>(interceptor_info->getter()); v8::NamedPropertyGetterCallback getter = FUNCTION_CAST<v8::NamedPropertyGetterCallback>(getter_address); ASSERT(getter != NULL); PropertyCallbackArguments callback_args(isolate, interceptor_info->data(), *receiver_handle, *holder_handle); { HandleScope scope(isolate); // Use the interceptor getter. v8::Handle<v8::Value> r = callback_args.Call(getter, v8::Utils::ToLocal(name)); RETURN_HANDLE_IF_SCHEDULED_EXCEPTION(isolate, Object); if (!r.IsEmpty()) { *attrs = NONE; Handle<Object> result = v8::Utils::OpenHandle(*r); result->VerifyApiCallResultType(); return scope.CloseAndEscape(result); } } Handle<Object> result = JSObject::GetPropertyPostInterceptor( holder_handle, receiver_handle, name_handle, attrs); return result; } /** * Loads a property with an interceptor performing post interceptor * lookup if interceptor failed. */ RUNTIME_FUNCTION(MaybeObject*, LoadPropertyWithInterceptorForLoad) { PropertyAttributes attr = NONE; HandleScope scope(isolate); Handle<Object> result = LoadWithInterceptor(&args, &attr); RETURN_IF_EMPTY_HANDLE(isolate, result); // If the property is present, return it. if (attr != ABSENT) return *result; return ThrowReferenceError(isolate, Name::cast(args[0])); } RUNTIME_FUNCTION(MaybeObject*, LoadPropertyWithInterceptorForCall) { PropertyAttributes attr; HandleScope scope(isolate); Handle<Object> result = LoadWithInterceptor(&args, &attr); RETURN_IF_EMPTY_HANDLE(isolate, result); // This is call IC. In this case, we simply return the undefined result which // will lead to an exception when trying to invoke the result as a // function. return *result; } RUNTIME_FUNCTION(MaybeObject*, StoreInterceptorProperty) { HandleScope scope(isolate); ASSERT(args.length() == 3); StoreIC ic(IC::NO_EXTRA_FRAME, isolate); Handle<JSObject> receiver = args.at<JSObject>(0); Handle<Name> name = args.at<Name>(1); Handle<Object> value = args.at<Object>(2); ASSERT(receiver->HasNamedInterceptor()); PropertyAttributes attr = NONE; Handle<Object> result = JSObject::SetPropertyWithInterceptor( receiver, name, value, attr, ic.strict_mode()); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } RUNTIME_FUNCTION(MaybeObject*, KeyedLoadPropertyWithInterceptor) { HandleScope scope(isolate); Handle<JSObject> receiver = args.at<JSObject>(0); ASSERT(args.smi_at(1) >= 0); uint32_t index = args.smi_at(1); Handle<Object> result = JSObject::GetElementWithInterceptor(receiver, receiver, index); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } Handle<Code> StubCompiler::CompileLoadInitialize(Code::Flags flags) { LoadIC::GenerateInitialize(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileLoadInitialize"); PROFILE(isolate(), CodeCreateEvent(Logger::LOAD_INITIALIZE_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::LOAD_IC, *code)); return code; } Handle<Code> StubCompiler::CompileLoadPreMonomorphic(Code::Flags flags) { LoadIC::GeneratePreMonomorphic(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileLoadPreMonomorphic"); PROFILE(isolate(), CodeCreateEvent(Logger::LOAD_PREMONOMORPHIC_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::LOAD_IC, *code)); return code; } Handle<Code> StubCompiler::CompileLoadMegamorphic(Code::Flags flags) { LoadIC::GenerateMegamorphic(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileLoadMegamorphic"); PROFILE(isolate(), CodeCreateEvent(Logger::LOAD_MEGAMORPHIC_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::LOAD_IC, *code)); return code; } Handle<Code> StubCompiler::CompileStoreInitialize(Code::Flags flags) { StoreIC::GenerateInitialize(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileStoreInitialize"); PROFILE(isolate(), CodeCreateEvent(Logger::STORE_INITIALIZE_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::STORE_IC, *code)); return code; } Handle<Code> StubCompiler::CompileStorePreMonomorphic(Code::Flags flags) { StoreIC::GeneratePreMonomorphic(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileStorePreMonomorphic"); PROFILE(isolate(), CodeCreateEvent(Logger::STORE_PREMONOMORPHIC_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::STORE_IC, *code)); return code; } Handle<Code> StubCompiler::CompileStoreGeneric(Code::Flags flags) { ExtraICState extra_state = Code::ExtractExtraICStateFromFlags(flags); StrictMode strict_mode = StoreIC::GetStrictMode(extra_state); StoreIC::GenerateRuntimeSetProperty(masm(), strict_mode); Handle<Code> code = GetCodeWithFlags(flags, "CompileStoreGeneric"); PROFILE(isolate(), CodeCreateEvent(Logger::STORE_GENERIC_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::STORE_IC, *code)); return code; } Handle<Code> StubCompiler::CompileStoreMegamorphic(Code::Flags flags) { StoreIC::GenerateMegamorphic(masm()); Handle<Code> code = GetCodeWithFlags(flags, "CompileStoreMegamorphic"); PROFILE(isolate(), CodeCreateEvent(Logger::STORE_MEGAMORPHIC_TAG, *code, 0)); GDBJIT(AddCode(GDBJITInterface::STORE_IC, *code)); return code; } #undef CALL_LOGGER_TAG Handle<Code> StubCompiler::GetCodeWithFlags(Code::Flags flags, const char* name) { // Create code object in the heap. CodeDesc desc; masm_.GetCode(&desc); Handle<Code> code = factory()->NewCode(desc, flags, masm_.CodeObject()); if (code->has_major_key()) { code->set_major_key(CodeStub::NoCache); } #ifdef ENABLE_DISASSEMBLER if (FLAG_print_code_stubs) code->Disassemble(name); #endif return code; } Handle<Code> StubCompiler::GetCodeWithFlags(Code::Flags flags, Handle<Name> name) { return (FLAG_print_code_stubs && !name.is_null() && name->IsString()) ? GetCodeWithFlags(flags, Handle<String>::cast(name)->ToCString().get()) : GetCodeWithFlags(flags, NULL); } void StubCompiler::LookupPostInterceptor(Handle<JSObject> holder, Handle<Name> name, LookupResult* lookup) { holder->LocalLookupRealNamedProperty(*name, lookup); if (lookup->IsFound()) return; if (holder->GetPrototype()->IsNull()) return; holder->GetPrototype()->Lookup(*name, lookup); } #define __ ACCESS_MASM(masm()) Register LoadStubCompiler::HandlerFrontendHeader( Handle<HeapType> type, Register object_reg, Handle<JSObject> holder, Handle<Name> name, Label* miss) { PrototypeCheckType check_type = CHECK_ALL_MAPS; int function_index = -1; if (type->Is(HeapType::String())) { function_index = Context::STRING_FUNCTION_INDEX; } else if (type->Is(HeapType::Symbol())) { function_index = Context::SYMBOL_FUNCTION_INDEX; } else if (type->Is(HeapType::Number())) { function_index = Context::NUMBER_FUNCTION_INDEX; } else if (type->Is(HeapType::Boolean())) { // Booleans use the generic oddball map, so an additional check is needed to // ensure the receiver is really a boolean. GenerateBooleanCheck(object_reg, miss); function_index = Context::BOOLEAN_FUNCTION_INDEX; } else { check_type = SKIP_RECEIVER; } if (check_type == CHECK_ALL_MAPS) { GenerateDirectLoadGlobalFunctionPrototype( masm(), function_index, scratch1(), miss); Object* function = isolate()->native_context()->get(function_index); Object* prototype = JSFunction::cast(function)->instance_prototype(); type = IC::CurrentTypeOf(handle(prototype, isolate()), isolate()); object_reg = scratch1(); } // Check that the maps starting from the prototype haven't changed. return CheckPrototypes( type, object_reg, holder, scratch1(), scratch2(), scratch3(), name, miss, check_type); } // HandlerFrontend for store uses the name register. It has to be restored // before a miss. Register StoreStubCompiler::HandlerFrontendHeader( Handle<HeapType> type, Register object_reg, Handle<JSObject> holder, Handle<Name> name, Label* miss) { return CheckPrototypes(type, object_reg, holder, this->name(), scratch1(), scratch2(), name, miss, SKIP_RECEIVER); } bool BaseLoadStoreStubCompiler::IncludesNumberType(TypeHandleList* types) { for (int i = 0; i < types->length(); ++i) { if (types->at(i)->Is(HeapType::Number())) return true; } return false; } Register BaseLoadStoreStubCompiler::HandlerFrontend(Handle<HeapType> type, Register object_reg, Handle<JSObject> holder, Handle<Name> name) { Label miss; Register reg = HandlerFrontendHeader(type, object_reg, holder, name, &miss); HandlerFrontendFooter(name, &miss); return reg; } void LoadStubCompiler::NonexistentHandlerFrontend(Handle<HeapType> type, Handle<JSObject> last, Handle<Name> name) { Label miss; Register holder; Handle<Map> last_map; if (last.is_null()) { holder = receiver(); last_map = IC::TypeToMap(*type, isolate()); // If |type| has null as its prototype, |last| is Handle<JSObject>::null(). ASSERT(last_map->prototype() == isolate()->heap()->null_value()); } else { holder = HandlerFrontendHeader(type, receiver(), last, name, &miss); last_map = handle(last->map()); } if (last_map->is_dictionary_map() && !last_map->IsJSGlobalObjectMap() && !last_map->IsJSGlobalProxyMap()) { if (!name->IsUniqueName()) { ASSERT(name->IsString()); name = factory()->InternalizeString(Handle<String>::cast(name)); } ASSERT(last.is_null() || last->property_dictionary()->FindEntry(*name) == NameDictionary::kNotFound); GenerateDictionaryNegativeLookup(masm(), &miss, holder, name, scratch2(), scratch3()); } // If the last object in the prototype chain is a global object, // check that the global property cell is empty. if (last_map->IsJSGlobalObjectMap()) { Handle<JSGlobalObject> global = last.is_null() ? Handle<JSGlobalObject>::cast(type->AsConstant()) : Handle<JSGlobalObject>::cast(last); GenerateCheckPropertyCell(masm(), global, name, scratch2(), &miss); } HandlerFrontendFooter(name, &miss); } Handle<Code> LoadStubCompiler::CompileLoadField( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name, PropertyIndex field, Representation representation) { Register reg = HandlerFrontend(type, receiver(), holder, name); GenerateLoadField(reg, holder, field, representation); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> LoadStubCompiler::CompileLoadConstant( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name, Handle<Object> value) { HandlerFrontend(type, receiver(), holder, name); GenerateLoadConstant(value); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> LoadStubCompiler::CompileLoadCallback( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name, Handle<ExecutableAccessorInfo> callback) { Register reg = CallbackHandlerFrontend( type, receiver(), holder, name, callback); GenerateLoadCallback(reg, callback); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> LoadStubCompiler::CompileLoadCallback( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name, const CallOptimization& call_optimization) { ASSERT(call_optimization.is_simple_api_call()); Handle<JSFunction> callback = call_optimization.constant_function(); CallbackHandlerFrontend(type, receiver(), holder, name, callback); Handle<Map>receiver_map = IC::TypeToMap(*type, isolate()); GenerateFastApiCall( masm(), call_optimization, receiver_map, receiver(), scratch1(), false, 0, NULL); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> LoadStubCompiler::CompileLoadInterceptor( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name) { LookupResult lookup(isolate()); LookupPostInterceptor(holder, name, &lookup); Register reg = HandlerFrontend(type, receiver(), holder, name); // TODO(368): Compile in the whole chain: all the interceptors in // prototypes and ultimate answer. GenerateLoadInterceptor(reg, type, holder, &lookup, name); // Return the generated code. return GetCode(kind(), Code::FAST, name); } void LoadStubCompiler::GenerateLoadPostInterceptor( Register interceptor_reg, Handle<JSObject> interceptor_holder, Handle<Name> name, LookupResult* lookup) { Handle<JSObject> holder(lookup->holder()); if (lookup->IsField()) { PropertyIndex field = lookup->GetFieldIndex(); if (interceptor_holder.is_identical_to(holder)) { GenerateLoadField( interceptor_reg, holder, field, lookup->representation()); } else { // We found FIELD property in prototype chain of interceptor's holder. // Retrieve a field from field's holder. Register reg = HandlerFrontend( IC::CurrentTypeOf(interceptor_holder, isolate()), interceptor_reg, holder, name); GenerateLoadField( reg, holder, field, lookup->representation()); } } else { // We found CALLBACKS property in prototype chain of interceptor's // holder. ASSERT(lookup->type() == CALLBACKS); Handle<ExecutableAccessorInfo> callback( ExecutableAccessorInfo::cast(lookup->GetCallbackObject())); ASSERT(callback->getter() != NULL); Register reg = CallbackHandlerFrontend( IC::CurrentTypeOf(interceptor_holder, isolate()), interceptor_reg, holder, name, callback); GenerateLoadCallback(reg, callback); } } Handle<Code> BaseLoadStoreStubCompiler::CompileMonomorphicIC( Handle<HeapType> type, Handle<Code> handler, Handle<Name> name) { TypeHandleList types(1); CodeHandleList handlers(1); types.Add(type); handlers.Add(handler); Code::StubType stub_type = handler->type(); return CompilePolymorphicIC(&types, &handlers, name, stub_type, PROPERTY); } Handle<Code> LoadStubCompiler::CompileLoadViaGetter( Handle<HeapType> type, Handle<JSObject> holder, Handle<Name> name, Handle<JSFunction> getter) { HandlerFrontend(type, receiver(), holder, name); GenerateLoadViaGetter(masm(), type, receiver(), getter); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> StoreStubCompiler::CompileStoreTransition( Handle<JSObject> object, LookupResult* lookup, Handle<Map> transition, Handle<Name> name) { Label miss, slow; // Ensure no transitions to deprecated maps are followed. __ CheckMapDeprecated(transition, scratch1(), &miss); // Check that we are allowed to write this. if (object->GetPrototype()->IsJSObject()) { Handle<JSObject> holder; // holder == object indicates that no property was found. if (lookup->holder() != *object) { holder = Handle<JSObject>(lookup->holder()); } else { // Find the top object. holder = object; do { holder = Handle<JSObject>(JSObject::cast(holder->GetPrototype())); } while (holder->GetPrototype()->IsJSObject()); } Register holder_reg = HandlerFrontendHeader( IC::CurrentTypeOf(object, isolate()), receiver(), holder, name, &miss); // If no property was found, and the holder (the last object in the // prototype chain) is in slow mode, we need to do a negative lookup on the // holder. if (lookup->holder() == *object) { GenerateNegativeHolderLookup(masm(), holder, holder_reg, name, &miss); } } GenerateStoreTransition(masm(), object, lookup, transition, name, receiver(), this->name(), value(), scratch1(), scratch2(), scratch3(), &miss, &slow); // Handle store cache miss. GenerateRestoreName(masm(), &miss, name); TailCallBuiltin(masm(), MissBuiltin(kind())); GenerateRestoreName(masm(), &slow, name); TailCallBuiltin(masm(), SlowBuiltin(kind())); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> StoreStubCompiler::CompileStoreField(Handle<JSObject> object, LookupResult* lookup, Handle<Name> name) { Label miss; HandlerFrontendHeader(IC::CurrentTypeOf(object, isolate()), receiver(), object, name, &miss); // Generate store field code. GenerateStoreField(masm(), object, lookup, receiver(), this->name(), value(), scratch1(), scratch2(), &miss); // Handle store cache miss. __ bind(&miss); TailCallBuiltin(masm(), MissBuiltin(kind())); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> StoreStubCompiler::CompileStoreArrayLength(Handle<JSObject> object, LookupResult* lookup, Handle<Name> name) { // This accepts as a receiver anything JSArray::SetElementsLength accepts // (currently anything except for external arrays which means anything with // elements of FixedArray type). Value must be a number, but only smis are // accepted as the most common case. Label miss; // Check that value is a smi. __ JumpIfNotSmi(value(), &miss); // Generate tail call to StoreIC_ArrayLength. GenerateStoreArrayLength(); // Handle miss case. __ bind(&miss); TailCallBuiltin(masm(), MissBuiltin(kind())); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> StoreStubCompiler::CompileStoreViaSetter( Handle<JSObject> object, Handle<JSObject> holder, Handle<Name> name, Handle<JSFunction> setter) { Handle<HeapType> type = IC::CurrentTypeOf(object, isolate()); HandlerFrontend(type, receiver(), holder, name); GenerateStoreViaSetter(masm(), type, receiver(), setter); return GetCode(kind(), Code::FAST, name); } Handle<Code> StoreStubCompiler::CompileStoreCallback( Handle<JSObject> object, Handle<JSObject> holder, Handle<Name> name, const CallOptimization& call_optimization) { HandlerFrontend(IC::CurrentTypeOf(object, isolate()), receiver(), holder, name); Register values[] = { value() }; GenerateFastApiCall( masm(), call_optimization, handle(object->map()), receiver(), scratch1(), true, 1, values); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> KeyedLoadStubCompiler::CompileLoadElement( Handle<Map> receiver_map) { ElementsKind elements_kind = receiver_map->elements_kind(); if (receiver_map->has_fast_elements() || receiver_map->has_external_array_elements() || receiver_map->has_fixed_typed_array_elements()) { Handle<Code> stub = KeyedLoadFastElementStub( receiver_map->instance_type() == JS_ARRAY_TYPE, elements_kind).GetCode(isolate()); __ DispatchMap(receiver(), scratch1(), receiver_map, stub, DO_SMI_CHECK); } else { Handle<Code> stub = FLAG_compiled_keyed_dictionary_loads ? KeyedLoadDictionaryElementStub().GetCode(isolate()) : KeyedLoadDictionaryElementPlatformStub().GetCode(isolate()); __ DispatchMap(receiver(), scratch1(), receiver_map, stub, DO_SMI_CHECK); } TailCallBuiltin(masm(), Builtins::kKeyedLoadIC_Miss); // Return the generated code. return GetICCode(kind(), Code::NORMAL, factory()->empty_string()); } Handle<Code> KeyedStoreStubCompiler::CompileStoreElement( Handle<Map> receiver_map) { ElementsKind elements_kind = receiver_map->elements_kind(); bool is_jsarray = receiver_map->instance_type() == JS_ARRAY_TYPE; Handle<Code> stub; if (receiver_map->has_fast_elements() || receiver_map->has_external_array_elements() || receiver_map->has_fixed_typed_array_elements()) { stub = KeyedStoreFastElementStub( is_jsarray, elements_kind, store_mode()).GetCode(isolate()); } else { stub = KeyedStoreElementStub(is_jsarray, elements_kind, store_mode()).GetCode(isolate()); } __ DispatchMap(receiver(), scratch1(), receiver_map, stub, DO_SMI_CHECK); TailCallBuiltin(masm(), Builtins::kKeyedStoreIC_Miss); // Return the generated code. return GetICCode(kind(), Code::NORMAL, factory()->empty_string()); } #undef __ void StubCompiler::TailCallBuiltin(MacroAssembler* masm, Builtins::Name name) { Handle<Code> code(masm->isolate()->builtins()->builtin(name)); GenerateTailCall(masm, code); } void BaseLoadStoreStubCompiler::JitEvent(Handle<Name> name, Handle<Code> code) { #ifdef ENABLE_GDB_JIT_INTERFACE GDBJITInterface::CodeTag tag; if (kind_ == Code::LOAD_IC) { tag = GDBJITInterface::LOAD_IC; } else if (kind_ == Code::KEYED_LOAD_IC) { tag = GDBJITInterface::KEYED_LOAD_IC; } else if (kind_ == Code::STORE_IC) { tag = GDBJITInterface::STORE_IC; } else { tag = GDBJITInterface::KEYED_STORE_IC; } GDBJIT(AddCode(tag, *name, *code)); #endif } void BaseLoadStoreStubCompiler::InitializeRegisters() { if (kind_ == Code::LOAD_IC) { registers_ = LoadStubCompiler::registers(); } else if (kind_ == Code::KEYED_LOAD_IC) { registers_ = KeyedLoadStubCompiler::registers(); } else if (kind_ == Code::STORE_IC) { registers_ = StoreStubCompiler::registers(); } else { registers_ = KeyedStoreStubCompiler::registers(); } } Handle<Code> BaseLoadStoreStubCompiler::GetICCode(Code::Kind kind, Code::StubType type, Handle<Name> name, InlineCacheState state) { Code::Flags flags = Code::ComputeFlags(kind, state, extra_state(), type); Handle<Code> code = GetCodeWithFlags(flags, name); PROFILE(isolate(), CodeCreateEvent(log_kind(code), *code, *name)); JitEvent(name, code); return code; } Handle<Code> BaseLoadStoreStubCompiler::GetCode(Code::Kind kind, Code::StubType type, Handle<Name> name) { ASSERT_EQ(kNoExtraICState, extra_state()); Code::Flags flags = Code::ComputeHandlerFlags(kind, type, cache_holder_); Handle<Code> code = GetCodeWithFlags(flags, name); PROFILE(isolate(), CodeCreateEvent(log_kind(code), *code, *name)); JitEvent(name, code); return code; } void KeyedLoadStubCompiler::CompileElementHandlers(MapHandleList* receiver_maps, CodeHandleList* handlers) { for (int i = 0; i < receiver_maps->length(); ++i) { Handle<Map> receiver_map = receiver_maps->at(i); Handle<Code> cached_stub; if ((receiver_map->instance_type() & kNotStringTag) == 0) { cached_stub = isolate()->builtins()->KeyedLoadIC_String(); } else if (receiver_map->instance_type() < FIRST_JS_RECEIVER_TYPE) { cached_stub = isolate()->builtins()->KeyedLoadIC_Slow(); } else { bool is_js_array = receiver_map->instance_type() == JS_ARRAY_TYPE; ElementsKind elements_kind = receiver_map->elements_kind(); if (IsFastElementsKind(elements_kind) || IsExternalArrayElementsKind(elements_kind) || IsFixedTypedArrayElementsKind(elements_kind)) { cached_stub = KeyedLoadFastElementStub(is_js_array, elements_kind).GetCode(isolate()); } else if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) { cached_stub = isolate()->builtins()->KeyedLoadIC_SloppyArguments(); } else { ASSERT(elements_kind == DICTIONARY_ELEMENTS); cached_stub = KeyedLoadDictionaryElementStub().GetCode(isolate()); } } handlers->Add(cached_stub); } } Handle<Code> KeyedStoreStubCompiler::CompileStoreElementPolymorphic( MapHandleList* receiver_maps) { // Collect MONOMORPHIC stubs for all |receiver_maps|. CodeHandleList handlers(receiver_maps->length()); MapHandleList transitioned_maps(receiver_maps->length()); for (int i = 0; i < receiver_maps->length(); ++i) { Handle<Map> receiver_map(receiver_maps->at(i)); Handle<Code> cached_stub; Handle<Map> transitioned_map = receiver_map->FindTransitionedMap(receiver_maps); // TODO(mvstanton): The code below is doing pessimistic elements // transitions. I would like to stop doing that and rely on Allocation Site // Tracking to do a better job of ensuring the data types are what they need // to be. Not all the elements are in place yet, pessimistic elements // transitions are still important for performance. bool is_js_array = receiver_map->instance_type() == JS_ARRAY_TYPE; ElementsKind elements_kind = receiver_map->elements_kind(); if (!transitioned_map.is_null()) { cached_stub = ElementsTransitionAndStoreStub( elements_kind, transitioned_map->elements_kind(), is_js_array, store_mode()).GetCode(isolate()); } else if (receiver_map->instance_type() < FIRST_JS_RECEIVER_TYPE) { cached_stub = isolate()->builtins()->KeyedStoreIC_Slow(); } else { if (receiver_map->has_fast_elements() || receiver_map->has_external_array_elements() || receiver_map->has_fixed_typed_array_elements()) { cached_stub = KeyedStoreFastElementStub( is_js_array, elements_kind, store_mode()).GetCode(isolate()); } else { cached_stub = KeyedStoreElementStub( is_js_array, elements_kind, store_mode()).GetCode(isolate()); } } ASSERT(!cached_stub.is_null()); handlers.Add(cached_stub); transitioned_maps.Add(transitioned_map); } Handle<Code> code = CompileStorePolymorphic(receiver_maps, &handlers, &transitioned_maps); isolate()->counters()->keyed_store_polymorphic_stubs()->Increment(); PROFILE(isolate(), CodeCreateEvent(Logger::KEYED_STORE_POLYMORPHIC_IC_TAG, *code, 0)); return code; } void KeyedStoreStubCompiler::GenerateStoreDictionaryElement( MacroAssembler* masm) { KeyedStoreIC::GenerateSlow(masm); } CallOptimization::CallOptimization(LookupResult* lookup) { if (lookup->IsFound() && lookup->IsCacheable() && lookup->IsConstantFunction()) { // We only optimize constant function calls. Initialize(Handle<JSFunction>(lookup->GetConstantFunction())); } else { Initialize(Handle<JSFunction>::null()); } } CallOptimization::CallOptimization(Handle<JSFunction> function) { Initialize(function); } Handle<JSObject> CallOptimization::LookupHolderOfExpectedType( Handle<Map> object_map, HolderLookup* holder_lookup) const { ASSERT(is_simple_api_call()); if (!object_map->IsJSObjectMap()) { *holder_lookup = kHolderNotFound; return Handle<JSObject>::null(); } if (expected_receiver_type_.is_null() || expected_receiver_type_->IsTemplateFor(*object_map)) { *holder_lookup = kHolderIsReceiver; return Handle<JSObject>::null(); } while (true) { if (!object_map->prototype()->IsJSObject()) break; Handle<JSObject> prototype(JSObject::cast(object_map->prototype())); if (!prototype->map()->is_hidden_prototype()) break; object_map = handle(prototype->map()); if (expected_receiver_type_->IsTemplateFor(*object_map)) { *holder_lookup = kHolderFound; return prototype; } } *holder_lookup = kHolderNotFound; return Handle<JSObject>::null(); } bool CallOptimization::IsCompatibleReceiver(Handle<Object> receiver, Handle<JSObject> holder) const { ASSERT(is_simple_api_call()); if (!receiver->IsJSObject()) return false; Handle<Map> map(JSObject::cast(*receiver)->map()); HolderLookup holder_lookup; Handle<JSObject> api_holder = LookupHolderOfExpectedType(map, &holder_lookup); switch (holder_lookup) { case kHolderNotFound: return false; case kHolderIsReceiver: return true; case kHolderFound: if (api_holder.is_identical_to(holder)) return true; // Check if holder is in prototype chain of api_holder. { JSObject* object = *api_holder; while (true) { Object* prototype = object->map()->prototype(); if (!prototype->IsJSObject()) return false; if (prototype == *holder) return true; object = JSObject::cast(prototype); } } break; } UNREACHABLE(); return false; } void CallOptimization::Initialize(Handle<JSFunction> function) { constant_function_ = Handle<JSFunction>::null(); is_simple_api_call_ = false; expected_receiver_type_ = Handle<FunctionTemplateInfo>::null(); api_call_info_ = Handle<CallHandlerInfo>::null(); if (function.is_null() || !function->is_compiled()) return; constant_function_ = function; AnalyzePossibleApiFunction(function); } void CallOptimization::AnalyzePossibleApiFunction(Handle<JSFunction> function) { if (!function->shared()->IsApiFunction()) return; Handle<FunctionTemplateInfo> info(function->shared()->get_api_func_data()); // Require a C++ callback. if (info->call_code()->IsUndefined()) return; api_call_info_ = Handle<CallHandlerInfo>(CallHandlerInfo::cast(info->call_code())); // Accept signatures that either have no restrictions at all or // only have restrictions on the receiver. if (!info->signature()->IsUndefined()) { Handle<SignatureInfo> signature = Handle<SignatureInfo>(SignatureInfo::cast(info->signature())); if (!signature->args()->IsUndefined()) return; if (!signature->receiver()->IsUndefined()) { expected_receiver_type_ = Handle<FunctionTemplateInfo>( FunctionTemplateInfo::cast(signature->receiver())); } } is_simple_api_call_ = true; } } } // namespace v8::internal
// Copyright 2019 The Fuchsia 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 <gtest/gtest.h> #include "tools/fidlcat/interception_tests/interception_workflow_test.h" namespace fidlcat { // zx_thread_exit tests. std::unique_ptr<SystemCallTest> ZxThreadExit() { return std::make_unique<SystemCallTest>("zx_thread_exit", 0, ""); } #define THREAD_EXIT_DISPLAY_TEST_CONTENT(expected) \ PerformNoReturnDisplayTest("$plt(zx_thread_exit)", ZxThreadExit(), expected) #define THREAD_EXIT_DISPLAY_TEST(name, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { THREAD_EXIT_DISPLAY_TEST_CONTENT(expected); } \ TEST_F(InterceptionWorkflowTestArm, name) { THREAD_EXIT_DISPLAY_TEST_CONTENT(expected); } THREAD_EXIT_DISPLAY_TEST(ZxThreadExit, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_exit()\n") // zx_thread_create tests. std::unique_ptr<SystemCallTest> ZxThreadCreate(int64_t result, std::string_view result_name, zx_handle_t process, const char* name, size_t name_size, uint32_t options, zx_handle_t* out) { auto value = std::make_unique<SystemCallTest>("zx_thread_create", result, result_name); value->AddInput(process); value->AddInput(reinterpret_cast<uint64_t>(name)); value->AddInput(name_size); value->AddInput(options); value->AddInput(reinterpret_cast<uint64_t>(out)); return value; } #define THREAD_CREATE_DISPLAY_TEST_CONTENT(result, expected) \ const char* name = "my_thread"; \ zx_handle_t out = kHandleOut; \ PerformDisplayTest("$plt(zx_thread_create)", \ ZxThreadCreate(result, #result, kHandle, name, strlen(name), 0, &out), \ expected) #define THREAD_CREATE_DISPLAY_TEST(name, errno, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { \ THREAD_CREATE_DISPLAY_TEST_CONTENT(errno, expected); \ } \ TEST_F(InterceptionWorkflowTestArm, name) { THREAD_CREATE_DISPLAY_TEST_CONTENT(errno, expected); } THREAD_CREATE_DISPLAY_TEST(ZxThreadCreate, ZX_OK, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_create(" "process: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "name: \x1B[32mstring\x1B[0m = \x1B[31m\"my_thread\"\x1B[0m, " "options: \x1B[32muint32\x1B[0m = \x1B[34m0\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m (" "out: \x1B[32mhandle\x1B[0m = \x1B[31mbde90caf\x1B[0m)\n") CREATE_AUTOMATION_TEST(ZxThreadCreateAutomation, "zx_thread_create", ZX_OK, "Invoked bp instructions:\n" " load_memory rsi, rdx\n" " stored_value(0) = r8\n" "Exit bp instructions:\n" " load_memory stored_value(0), 4\n" " clear_stored_values\n", "Invoked bp instructions:\n" " load_memory x1, x2\n" " stored_value(0) = x4\n" "Exit bp instructions:\n" " load_memory stored_value(0), 4\n" " clear_stored_values\n") // zx_thread_start tests. std::unique_ptr<SystemCallTest> ZxThreadStart(int64_t result, std::string_view result_name, zx_handle_t handle, zx_vaddr_t thread_entry, zx_vaddr_t stack, uintptr_t arg1, uintptr_t arg2) { auto value = std::make_unique<SystemCallTest>("zx_thread_start", result, result_name); value->AddInput(handle); value->AddInput(thread_entry); value->AddInput(stack); value->AddInput(arg1); value->AddInput(arg2); return value; } #define THREAD_START_DISPLAY_TEST_CONTENT(result, expected) \ zx_vaddr_t thread_entry = 0xeeee; \ zx_vaddr_t stack = 0xaaaa; \ uintptr_t arg1 = 0x1111; \ uintptr_t arg2 = 0x2222; \ PerformDisplayTest("$plt(zx_thread_start)", \ ZxThreadStart(result, #result, kHandle, thread_entry, stack, arg1, arg2), \ expected) #define THREAD_START_DISPLAY_TEST(name, errno, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { \ THREAD_START_DISPLAY_TEST_CONTENT(errno, expected); \ } \ TEST_F(InterceptionWorkflowTestArm, name) { THREAD_START_DISPLAY_TEST_CONTENT(errno, expected); } THREAD_START_DISPLAY_TEST( ZxThreadStart, ZX_OK, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_start(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "thread_entry: \x1B[32mzx.vaddr\x1B[0m = \x1B[34m000000000000eeee\x1B[0m, " "stack: \x1B[32mzx.vaddr\x1B[0m = \x1B[34m000000000000aaaa\x1B[0m, " "arg1: \x1B[32muintptr\x1B[0m = \x1B[34m0000000000001111\x1B[0m, " "arg2: \x1B[32muintptr\x1B[0m = \x1B[34m0000000000002222\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n") // zx_thread_read_state tests. std::unique_ptr<SystemCallTest> ZxThreadReadState(int64_t result, std::string_view result_name, zx_handle_t handle, uint32_t kind, void* buffer, size_t buffer_size) { auto value = std::make_unique<SystemCallTest>("zx_thread_read_state", result, result_name); value->AddInput(handle); value->AddInput(kind); value->AddInput(reinterpret_cast<uint64_t>(buffer)); value->AddInput(buffer_size); return value; } #define THREAD_READ_STATE_DISPLAY_TEST_CONTENT(result, kind, buffer, expected) \ PerformDisplayTest("$plt(zx_thread_read_state)", \ ZxThreadReadState(result, #result, kHandle, kind, &buffer, sizeof(buffer)), \ expected) TEST_F(InterceptionWorkflowTestArm, ZxThreadReadStateGeneralRegsAArch64) { zx_thread_state_general_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.r) / sizeof(buffer.r[0]); ++i) { buffer.r[i] = value; value += kIncrement; } buffer.lr = 0x11111111; buffer.sp = 0x22222222; buffer.pc = 0xcccccccc; buffer.cpsr = 0xdddddddd; buffer.tpidr = 0xeeeeeeee; THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_GENERAL_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_GENERAL_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m280\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_general_regs_aarch64_t\x1B[0m = {\n" " r: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m, " "\x1B[34m0000000400000004\x1B[0m, \x1B[34m0000000500000005\x1B[0m\n" " \x1B[34m0000000600000006\x1B[0m, \x1B[34m0000000700000007\x1B[0m, " "\x1B[34m0000000800000008\x1B[0m, \x1B[34m0000000900000009\x1B[0m, " "\x1B[34m0000000a0000000a\x1B[0m, \x1B[34m0000000b0000000b\x1B[0m\n" " \x1B[34m0000000c0000000c\x1B[0m, \x1B[34m0000000d0000000d\x1B[0m, " "\x1B[34m0000000e0000000e\x1B[0m, \x1B[34m0000000f0000000f\x1B[0m, " "\x1B[34m0000001000000010\x1B[0m, \x1B[34m0000001100000011\x1B[0m\n" " \x1B[34m0000001200000012\x1B[0m, \x1B[34m0000001300000013\x1B[0m, " "\x1B[34m0000001400000014\x1B[0m, \x1B[34m0000001500000015\x1B[0m, " "\x1B[34m0000001600000016\x1B[0m, \x1B[34m0000001700000017\x1B[0m\n" " \x1B[34m0000001800000018\x1B[0m, \x1B[34m0000001900000019\x1B[0m, " "\x1B[34m0000001a0000001a\x1B[0m, \x1B[34m0000001b0000001b\x1B[0m, " "\x1B[34m0000001c0000001c\x1B[0m, \x1B[34m0000001d0000001d\x1B[0m\n" " ]\n" " lr: \x1B[32muint64\x1B[0m = \x1B[34m0000000011111111\x1B[0m\n" " sp: \x1B[32muint64\x1B[0m = \x1B[34m0000000022222222\x1B[0m\n" " pc: \x1B[32muint64\x1B[0m = \x1B[34m00000000cccccccc\x1B[0m\n" " cpsr: \x1B[32muint64\x1B[0m = \x1B[34m00000000dddddddd\x1B[0m\n" " tpidr: \x1B[32muint64\x1B[0m = \x1B[34m00000000eeeeeeee\x1B[0m\n" " }\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadReadStateGeneralRegsX64) { zx_thread_state_general_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.rax = 0xaaaa; buffer.rbx = 0xbbbb; buffer.rcx = 0xcccc; buffer.rdx = 0xdddd; buffer.rsi = 0x1234; buffer.rbp = 0x2345; buffer.rsp = 0x3456; buffer.r8 = 0x0808; buffer.r9 = 0x0909; buffer.r10 = 0x1010; buffer.r11 = 0x1111; buffer.r12 = 0x1212; buffer.r13 = 0x1313; buffer.r14 = 0x1414; buffer.r15 = 0x1515; buffer.rip = 0x1111; buffer.rflags = 0; buffer.fs_base = 0x100000000UL; buffer.gs_base = 0x200000000UL; THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_GENERAL_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_GENERAL_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m160\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_general_regs_x86_t\x1B[0m = {\n" " rax: \x1B[32muint64\x1B[0m = \x1B[34m000000000000aaaa\x1B[0m\n" " rbx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000bbbb\x1B[0m\n" " rcx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000cccc\x1B[0m\n" " rdx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000dddd\x1B[0m\n" " rsi: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001234\x1B[0m\n" " rdi: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m\n" " rbp: \x1B[32muint64\x1B[0m = \x1B[34m0000000000002345\x1B[0m\n" " rsp: \x1B[32muint64\x1B[0m = \x1B[34m0000000000003456\x1B[0m\n" " r8: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000808\x1B[0m\n" " r9: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000909\x1B[0m\n" " r10: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001010\x1B[0m\n" " r11: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001111\x1B[0m\n" " r12: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001212\x1B[0m\n" " r13: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001313\x1B[0m\n" " r14: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001414\x1B[0m\n" " r15: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001515\x1B[0m\n" " rip: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001111\x1B[0m\n" " rflags: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m\n" " fs_base: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m\n" " gs_base: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m\n" " }\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadReadStateFpRegsX64) { zx_thread_state_fp_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.fcw = 0xcccc; buffer.fsw = 0xdddd; buffer.ftw = 0xee; buffer.fop = 0xffff; buffer.fip = 0x100000001UL; buffer.fdp = 0xd0000000dUL; constexpr uint64_t kLowIncrement = 0x100000001UL; constexpr uint64_t kHighIncrement = 0x100000000UL; uint64_t low = 0; uint64_t high = 0; for (size_t i = 0; i < sizeof(buffer.st) / sizeof(buffer.st[0]); ++i) { buffer.st[i].low = low; buffer.st[i].high = high; low += kLowIncrement; high += kHighIncrement; } THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_FP_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_FP_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m160\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_fp_regs_x86_t\x1B[0m = {\n" " fcw: \x1B[32muint16\x1B[0m = \x1B[34mcccc\x1B[0m\n" " fsw: \x1B[32muint16\x1B[0m = \x1B[34mdddd\x1B[0m\n" " ftw: \x1B[32muint8\x1B[0m = \x1B[34mee\x1B[0m\n" " fop: \x1B[32muint16\x1B[0m = \x1B[34mffff\x1B[0m\n" " fip: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m\n" " fdp: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m\n" " st: vector<\x1B[32mzx.uint128\x1B[0m> = [\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000000\x1B[0m }\n" " ]\n" " }\n"); } TEST_F(InterceptionWorkflowTestArm, ZxThreadReadStateVectorRegsAArch64) { zx_thread_state_vector_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.fpcr = 0x12345678U; buffer.fpsr = 0x87654321U; constexpr uint64_t kLowIncrement = 0x100000001UL; constexpr uint64_t kHighIncrement = 0x100000000UL; uint64_t low = 0; uint64_t high = 0; for (size_t i = 0; i < sizeof(buffer.v) / sizeof(buffer.v[0]); ++i) { buffer.v[i].low = low; buffer.v[i].high = high; low += kLowIncrement; high += kHighIncrement; } THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_VECTOR_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_VECTOR_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m520\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_vector_regs_aarch64_t\x1B[0m = {\n" " fpcr: \x1B[32muint32\x1B[0m = \x1B[34m12345678\x1B[0m\n" " fpsr: \x1B[32muint32\x1B[0m = \x1B[34m87654321\x1B[0m\n" " v: vector<\x1B[32mzx.uint128\x1B[0m> = [\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000008\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000009\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000a0000000a\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000a00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000b0000000b\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000b00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000c0000000c\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000c00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000d00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000e0000000e\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000e00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000f0000000f\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000f00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000010\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000011\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000012\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000013\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000014\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000015\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000016\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000017\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000018\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000019\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001a0000001a\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001a00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001b0000001b\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001b00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001c0000001c\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001c00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001d0000001d\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001d00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001e0000001e\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001e00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001f0000001f\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001f00000000\x1B[0m }\n" " ]\n" " }\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadReadStateVectorRegsX64) { zx_thread_state_vector_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.zmm) / sizeof(buffer.zmm[0]); ++i) { for (size_t j = 0; j < sizeof(buffer.zmm[0].v) / sizeof(buffer.zmm[0].v[0]); ++j) { buffer.zmm[i].v[j] = value; value += kIncrement; } } for (size_t i = 0; i < sizeof(buffer.opmask) / sizeof(buffer.opmask[0]); ++i) { buffer.opmask[i] = value; value += kIncrement; } buffer.mxcsr = 0x12345678; THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_VECTOR_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_VECTOR_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m2120\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_vector_regs_x86_t\x1B[0m = {\n" " zmm: array<\x1B[32mzx_thread_state_vector_regs_x86_zmm_t\x1B[0m> = [\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m, " "\x1B[34m0000000400000004\x1B[0m, \x1B[34m0000000500000005\x1B[0m\n" " \x1B[34m0000000600000006\x1B[0m, \x1B[34m0000000700000007\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000800000008\x1B[0m, \x1B[34m0000000900000009\x1B[0m, " "\x1B[34m0000000a0000000a\x1B[0m, \x1B[34m0000000b0000000b\x1B[0m, " "\x1B[34m0000000c0000000c\x1B[0m, \x1B[34m0000000d0000000d\x1B[0m\n" " \x1B[34m0000000e0000000e\x1B[0m, \x1B[34m0000000f0000000f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000001000000010\x1B[0m, \x1B[34m0000001100000011\x1B[0m, " "\x1B[34m0000001200000012\x1B[0m, \x1B[34m0000001300000013\x1B[0m, " "\x1B[34m0000001400000014\x1B[0m, \x1B[34m0000001500000015\x1B[0m\n" " \x1B[34m0000001600000016\x1B[0m, \x1B[34m0000001700000017\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000001800000018\x1B[0m, \x1B[34m0000001900000019\x1B[0m, " "\x1B[34m0000001a0000001a\x1B[0m, \x1B[34m0000001b0000001b\x1B[0m, " "\x1B[34m0000001c0000001c\x1B[0m, \x1B[34m0000001d0000001d\x1B[0m\n" " \x1B[34m0000001e0000001e\x1B[0m, \x1B[34m0000001f0000001f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000002000000020\x1B[0m, \x1B[34m0000002100000021\x1B[0m, " "\x1B[34m0000002200000022\x1B[0m, \x1B[34m0000002300000023\x1B[0m, " "\x1B[34m0000002400000024\x1B[0m, \x1B[34m0000002500000025\x1B[0m\n" " \x1B[34m0000002600000026\x1B[0m, \x1B[34m0000002700000027\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000002800000028\x1B[0m, \x1B[34m0000002900000029\x1B[0m, " "\x1B[34m0000002a0000002a\x1B[0m, \x1B[34m0000002b0000002b\x1B[0m, " "\x1B[34m0000002c0000002c\x1B[0m, \x1B[34m0000002d0000002d\x1B[0m\n" " \x1B[34m0000002e0000002e\x1B[0m, \x1B[34m0000002f0000002f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000003000000030\x1B[0m, \x1B[34m0000003100000031\x1B[0m, " "\x1B[34m0000003200000032\x1B[0m, \x1B[34m0000003300000033\x1B[0m, " "\x1B[34m0000003400000034\x1B[0m, \x1B[34m0000003500000035\x1B[0m\n" " \x1B[34m0000003600000036\x1B[0m, \x1B[34m0000003700000037\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000003800000038\x1B[0m, \x1B[34m0000003900000039\x1B[0m, " "\x1B[34m0000003a0000003a\x1B[0m, \x1B[34m0000003b0000003b\x1B[0m, " "\x1B[34m0000003c0000003c\x1B[0m, \x1B[34m0000003d0000003d\x1B[0m\n" " \x1B[34m0000003e0000003e\x1B[0m, \x1B[34m0000003f0000003f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000004000000040\x1B[0m, \x1B[34m0000004100000041\x1B[0m, " "\x1B[34m0000004200000042\x1B[0m, \x1B[34m0000004300000043\x1B[0m, " "\x1B[34m0000004400000044\x1B[0m, \x1B[34m0000004500000045\x1B[0m\n" " \x1B[34m0000004600000046\x1B[0m, \x1B[34m0000004700000047\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000004800000048\x1B[0m, \x1B[34m0000004900000049\x1B[0m, " "\x1B[34m0000004a0000004a\x1B[0m, \x1B[34m0000004b0000004b\x1B[0m, " "\x1B[34m0000004c0000004c\x1B[0m, \x1B[34m0000004d0000004d\x1B[0m\n" " \x1B[34m0000004e0000004e\x1B[0m, \x1B[34m0000004f0000004f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000005000000050\x1B[0m, \x1B[34m0000005100000051\x1B[0m, " "\x1B[34m0000005200000052\x1B[0m, \x1B[34m0000005300000053\x1B[0m, " "\x1B[34m0000005400000054\x1B[0m, \x1B[34m0000005500000055\x1B[0m\n" " \x1B[34m0000005600000056\x1B[0m, \x1B[34m0000005700000057\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000005800000058\x1B[0m, \x1B[34m0000005900000059\x1B[0m, " "\x1B[34m0000005a0000005a\x1B[0m, \x1B[34m0000005b0000005b\x1B[0m, " "\x1B[34m0000005c0000005c\x1B[0m, \x1B[34m0000005d0000005d\x1B[0m\n" " \x1B[34m0000005e0000005e\x1B[0m, \x1B[34m0000005f0000005f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000006000000060\x1B[0m, \x1B[34m0000006100000061\x1B[0m, " "\x1B[34m0000006200000062\x1B[0m, \x1B[34m0000006300000063\x1B[0m, " "\x1B[34m0000006400000064\x1B[0m, \x1B[34m0000006500000065\x1B[0m\n" " \x1B[34m0000006600000066\x1B[0m, \x1B[34m0000006700000067\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000006800000068\x1B[0m, \x1B[34m0000006900000069\x1B[0m, " "\x1B[34m0000006a0000006a\x1B[0m, \x1B[34m0000006b0000006b\x1B[0m, " "\x1B[34m0000006c0000006c\x1B[0m, \x1B[34m0000006d0000006d\x1B[0m\n" " \x1B[34m0000006e0000006e\x1B[0m, \x1B[34m0000006f0000006f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000007000000070\x1B[0m, \x1B[34m0000007100000071\x1B[0m, " "\x1B[34m0000007200000072\x1B[0m, \x1B[34m0000007300000073\x1B[0m, " "\x1B[34m0000007400000074\x1B[0m, \x1B[34m0000007500000075\x1B[0m\n" " \x1B[34m0000007600000076\x1B[0m, \x1B[34m0000007700000077\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000007800000078\x1B[0m, \x1B[34m0000007900000079\x1B[0m, " "\x1B[34m0000007a0000007a\x1B[0m, \x1B[34m0000007b0000007b\x1B[0m, " "\x1B[34m0000007c0000007c\x1B[0m, \x1B[34m0000007d0000007d\x1B[0m\n" " \x1B[34m0000007e0000007e\x1B[0m, \x1B[34m0000007f0000007f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000008000000080\x1B[0m, \x1B[34m0000008100000081\x1B[0m, " "\x1B[34m0000008200000082\x1B[0m, \x1B[34m0000008300000083\x1B[0m, " "\x1B[34m0000008400000084\x1B[0m, \x1B[34m0000008500000085\x1B[0m\n" " \x1B[34m0000008600000086\x1B[0m, \x1B[34m0000008700000087\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000008800000088\x1B[0m, \x1B[34m0000008900000089\x1B[0m, " "\x1B[34m0000008a0000008a\x1B[0m, \x1B[34m0000008b0000008b\x1B[0m, " "\x1B[34m0000008c0000008c\x1B[0m, \x1B[34m0000008d0000008d\x1B[0m\n" " \x1B[34m0000008e0000008e\x1B[0m, \x1B[34m0000008f0000008f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000009000000090\x1B[0m, \x1B[34m0000009100000091\x1B[0m, " "\x1B[34m0000009200000092\x1B[0m, \x1B[34m0000009300000093\x1B[0m, " "\x1B[34m0000009400000094\x1B[0m, \x1B[34m0000009500000095\x1B[0m\n" " \x1B[34m0000009600000096\x1B[0m, \x1B[34m0000009700000097\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000009800000098\x1B[0m, \x1B[34m0000009900000099\x1B[0m, " "\x1B[34m0000009a0000009a\x1B[0m, \x1B[34m0000009b0000009b\x1B[0m, " "\x1B[34m0000009c0000009c\x1B[0m, \x1B[34m0000009d0000009d\x1B[0m\n" " \x1B[34m0000009e0000009e\x1B[0m, \x1B[34m0000009f0000009f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000a0000000a0\x1B[0m, \x1B[34m000000a1000000a1\x1B[0m, " "\x1B[34m000000a2000000a2\x1B[0m, \x1B[34m000000a3000000a3\x1B[0m, " "\x1B[34m000000a4000000a4\x1B[0m, \x1B[34m000000a5000000a5\x1B[0m\n" " \x1B[34m000000a6000000a6\x1B[0m, \x1B[34m000000a7000000a7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000a8000000a8\x1B[0m, \x1B[34m000000a9000000a9\x1B[0m, " "\x1B[34m000000aa000000aa\x1B[0m, \x1B[34m000000ab000000ab\x1B[0m, " "\x1B[34m000000ac000000ac\x1B[0m, \x1B[34m000000ad000000ad\x1B[0m\n" " \x1B[34m000000ae000000ae\x1B[0m, \x1B[34m000000af000000af\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000b0000000b0\x1B[0m, \x1B[34m000000b1000000b1\x1B[0m, " "\x1B[34m000000b2000000b2\x1B[0m, \x1B[34m000000b3000000b3\x1B[0m, " "\x1B[34m000000b4000000b4\x1B[0m, \x1B[34m000000b5000000b5\x1B[0m\n" " \x1B[34m000000b6000000b6\x1B[0m, \x1B[34m000000b7000000b7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000b8000000b8\x1B[0m, \x1B[34m000000b9000000b9\x1B[0m, " "\x1B[34m000000ba000000ba\x1B[0m, \x1B[34m000000bb000000bb\x1B[0m, " "\x1B[34m000000bc000000bc\x1B[0m, \x1B[34m000000bd000000bd\x1B[0m\n" " \x1B[34m000000be000000be\x1B[0m, \x1B[34m000000bf000000bf\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000c0000000c0\x1B[0m, \x1B[34m000000c1000000c1\x1B[0m, " "\x1B[34m000000c2000000c2\x1B[0m, \x1B[34m000000c3000000c3\x1B[0m, " "\x1B[34m000000c4000000c4\x1B[0m, \x1B[34m000000c5000000c5\x1B[0m\n" " \x1B[34m000000c6000000c6\x1B[0m, \x1B[34m000000c7000000c7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000c8000000c8\x1B[0m, \x1B[34m000000c9000000c9\x1B[0m, " "\x1B[34m000000ca000000ca\x1B[0m, \x1B[34m000000cb000000cb\x1B[0m, " "\x1B[34m000000cc000000cc\x1B[0m, \x1B[34m000000cd000000cd\x1B[0m\n" " \x1B[34m000000ce000000ce\x1B[0m, \x1B[34m000000cf000000cf\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000d0000000d0\x1B[0m, \x1B[34m000000d1000000d1\x1B[0m, " "\x1B[34m000000d2000000d2\x1B[0m, \x1B[34m000000d3000000d3\x1B[0m, " "\x1B[34m000000d4000000d4\x1B[0m, \x1B[34m000000d5000000d5\x1B[0m\n" " \x1B[34m000000d6000000d6\x1B[0m, \x1B[34m000000d7000000d7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000d8000000d8\x1B[0m, \x1B[34m000000d9000000d9\x1B[0m, " "\x1B[34m000000da000000da\x1B[0m, \x1B[34m000000db000000db\x1B[0m, " "\x1B[34m000000dc000000dc\x1B[0m, \x1B[34m000000dd000000dd\x1B[0m\n" " \x1B[34m000000de000000de\x1B[0m, \x1B[34m000000df000000df\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000e0000000e0\x1B[0m, \x1B[34m000000e1000000e1\x1B[0m, " "\x1B[34m000000e2000000e2\x1B[0m, \x1B[34m000000e3000000e3\x1B[0m, " "\x1B[34m000000e4000000e4\x1B[0m, \x1B[34m000000e5000000e5\x1B[0m\n" " \x1B[34m000000e6000000e6\x1B[0m, \x1B[34m000000e7000000e7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000e8000000e8\x1B[0m, \x1B[34m000000e9000000e9\x1B[0m, " "\x1B[34m000000ea000000ea\x1B[0m, \x1B[34m000000eb000000eb\x1B[0m, " "\x1B[34m000000ec000000ec\x1B[0m, \x1B[34m000000ed000000ed\x1B[0m\n" " \x1B[34m000000ee000000ee\x1B[0m, \x1B[34m000000ef000000ef\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000f0000000f0\x1B[0m, \x1B[34m000000f1000000f1\x1B[0m, " "\x1B[34m000000f2000000f2\x1B[0m, \x1B[34m000000f3000000f3\x1B[0m, " "\x1B[34m000000f4000000f4\x1B[0m, \x1B[34m000000f5000000f5\x1B[0m\n" " \x1B[34m000000f6000000f6\x1B[0m, \x1B[34m000000f7000000f7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000f8000000f8\x1B[0m, \x1B[34m000000f9000000f9\x1B[0m, " "\x1B[34m000000fa000000fa\x1B[0m, \x1B[34m000000fb000000fb\x1B[0m, " "\x1B[34m000000fc000000fc\x1B[0m, \x1B[34m000000fd000000fd\x1B[0m\n" " \x1B[34m000000fe000000fe\x1B[0m, \x1B[34m000000ff000000ff\x1B[0m\n" " ]\n" " }\n" " ]\n" " opmask: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000010000000100\x1B[0m, \x1B[34m0000010100000101\x1B[0m, " "\x1B[34m0000010200000102\x1B[0m, \x1B[34m0000010300000103\x1B[0m, " "\x1B[34m0000010400000104\x1B[0m, \x1B[34m0000010500000105\x1B[0m\n" " \x1B[34m0000010600000106\x1B[0m, \x1B[34m0000010700000107\x1B[0m\n" " ]\n" " mxcsr: \x1B[32muint32\x1B[0m = \x1B[34m12345678\x1B[0m\n" " }\n"); } TEST_F(InterceptionWorkflowTestArm, ZxThreadReadStateDebugRegsAArch64) { zx_thread_state_debug_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint32_t kCrIncrement = 0x00010001U; constexpr uint64_t kVrIncrement = 0x100000001UL; uint32_t cr = 0; uint64_t vr = 0; for (size_t i = 0; i < sizeof(buffer.hw_bps) / sizeof(buffer.hw_bps[0]); ++i) { buffer.hw_bps[i].dbgbcr = cr; buffer.hw_bps[i].dbgbvr = vr; cr += kCrIncrement; vr += kVrIncrement; } buffer.hw_bps_count = 3; for (size_t i = 0; i < sizeof(buffer.hw_wps) / sizeof(buffer.hw_wps[0]); ++i) { buffer.hw_wps[i].dbgwcr = cr; buffer.hw_wps[i].dbgwvr = vr; cr += kCrIncrement; vr += kVrIncrement; } buffer.hw_wps_count = 2; buffer.esr = 0xeeeeffff; THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_DEBUG_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_DEBUG_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m528\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_debug_regs_aarch64_t\x1B[0m = {\n" " hw_bps: array<\x1B[32mzx_thread_state_debug_regs_aarch64_bp_t\x1B[0m> = [\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00000000\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00010001\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00020002\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00030003\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00040004\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00050005\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00060006\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00070007\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00080008\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000008\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00090009\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000009\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000a000a\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000a0000000a\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000b000b\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000b0000000b\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000c000c\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000c0000000c\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000d000d\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000e000e\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000e0000000e\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000f000f\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000f0000000f\x1B[0m }\n" " ]\n" " hw_bps_count: \x1B[32muint8\x1B[0m = \x1B[34m03\x1B[0m\n" " hw_wps: array<\x1B[32mzx_thread_state_debug_regs_aarch64_wp_t\x1B[0m> = [\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00100010\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000010\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00110011\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000011\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00120012\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000012\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00130013\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000013\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00140014\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000014\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00150015\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000015\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00160016\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000016\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00170017\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000017\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00180018\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000018\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00190019\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000019\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001a001a\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001a0000001a\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001b001b\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001b0000001b\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001c001c\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001c0000001c\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001d001d\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001d0000001d\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001e001e\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001e0000001e\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001f001f\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001f0000001f\x1B[0m }\n" " ]\n" " hw_wps_count: \x1B[32muint8\x1B[0m = \x1B[34m02\x1B[0m\n" " esr: \x1B[32muint32\x1B[0m = \x1B[34meeeeffff\x1B[0m\n" " }\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadReadStateDebugRegsX64) { zx_thread_state_debug_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.dr) / sizeof(buffer.dr[0]); ++i) { buffer.dr[i] = value; value += kIncrement; } buffer.dr6 = 0x66666666; buffer.dr7 = 0x77777777; THREAD_READ_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_DEBUG_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_DEBUG_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m48\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n" " regs: \x1B[32mzx_thread_state_debug_regs_x86_t\x1B[0m = {\n" " dr: vector<\x1B[32muint64\x1B[0m> = [ " "\x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m ]\n" " dr6: \x1B[32muint64\x1B[0m = \x1B[34m0000000066666666\x1B[0m\n" " dr7: \x1B[32muint64\x1B[0m = \x1B[34m0000000077777777\x1B[0m\n" " }\n"); } #define THREAD_READ_STATE_SINGLE_STEP_DISPLAY_TEST(name, errno, value, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { \ uint32_t single_step = value; \ THREAD_READ_STATE_DISPLAY_TEST_CONTENT(errno, ZX_THREAD_STATE_SINGLE_STEP, single_step, \ expected); \ } \ TEST_F(InterceptionWorkflowTestArm, name) { \ uint32_t single_step = value; \ THREAD_READ_STATE_DISPLAY_TEST_CONTENT(errno, ZX_THREAD_STATE_SINGLE_STEP, single_step, \ expected); \ } THREAD_READ_STATE_SINGLE_STEP_DISPLAY_TEST( ZxThreadReadStateSingleStep0, ZX_OK, 0, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_SINGLE_STEP\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m4\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m (single_step: \x1B[32muint32\x1B[0m = \x1B[34m0\x1B[0m)\n") THREAD_READ_STATE_SINGLE_STEP_DISPLAY_TEST( ZxThreadReadStateSingleStep1, ZX_OK, 1, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_read_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_SINGLE_STEP\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m4\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m (single_step: \x1B[32muint32\x1B[0m = \x1B[34m1\x1B[0m)\n") // zx_thread_write_state tests. std::unique_ptr<SystemCallTest> ZxThreadWriteState(int64_t result, std::string_view result_name, zx_handle_t handle, uint32_t kind, void* buffer, size_t buffer_size) { auto value = std::make_unique<SystemCallTest>("zx_thread_write_state", result, result_name); value->AddInput(handle); value->AddInput(kind); value->AddInput(reinterpret_cast<uint64_t>(buffer)); value->AddInput(buffer_size); return value; } #define THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT(result, kind, buffer, expected) \ PerformDisplayTest("$plt(zx_thread_write_state)", \ ZxThreadWriteState(result, #result, kHandle, kind, &buffer, sizeof(buffer)), \ expected) TEST_F(InterceptionWorkflowTestArm, ZxThreadWriteStateGeneralRegsAArch64) { zx_thread_state_general_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.r) / sizeof(buffer.r[0]); ++i) { buffer.r[i] = value; value += kIncrement; } buffer.lr = 0x11111111; buffer.sp = 0x22222222; buffer.pc = 0xcccccccc; buffer.cpsr = 0xdddddddd; buffer.tpidr = 0xeeeeeeee; THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_GENERAL_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_GENERAL_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m280\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_general_regs_aarch64_t\x1B[0m = {\n" " r: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m, " "\x1B[34m0000000400000004\x1B[0m, \x1B[34m0000000500000005\x1B[0m, " "\x1B[34m0000000600000006\x1B[0m\n" " \x1B[34m0000000700000007\x1B[0m, \x1B[34m0000000800000008\x1B[0m, " "\x1B[34m0000000900000009\x1B[0m, \x1B[34m0000000a0000000a\x1B[0m, " "\x1B[34m0000000b0000000b\x1B[0m, \x1B[34m0000000c0000000c\x1B[0m, " "\x1B[34m0000000d0000000d\x1B[0m\n" " \x1B[34m0000000e0000000e\x1B[0m, \x1B[34m0000000f0000000f\x1B[0m, " "\x1B[34m0000001000000010\x1B[0m, \x1B[34m0000001100000011\x1B[0m, " "\x1B[34m0000001200000012\x1B[0m, \x1B[34m0000001300000013\x1B[0m, " "\x1B[34m0000001400000014\x1B[0m\n" " \x1B[34m0000001500000015\x1B[0m, \x1B[34m0000001600000016\x1B[0m, " "\x1B[34m0000001700000017\x1B[0m, \x1B[34m0000001800000018\x1B[0m, " "\x1B[34m0000001900000019\x1B[0m, \x1B[34m0000001a0000001a\x1B[0m, " "\x1B[34m0000001b0000001b\x1B[0m\n" " \x1B[34m0000001c0000001c\x1B[0m, \x1B[34m0000001d0000001d\x1B[0m\n" " ]\n" " lr: \x1B[32muint64\x1B[0m = \x1B[34m0000000011111111\x1B[0m\n" " sp: \x1B[32muint64\x1B[0m = \x1B[34m0000000022222222\x1B[0m\n" " pc: \x1B[32muint64\x1B[0m = \x1B[34m00000000cccccccc\x1B[0m\n" " cpsr: \x1B[32muint64\x1B[0m = \x1B[34m00000000dddddddd\x1B[0m\n" " tpidr: \x1B[32muint64\x1B[0m = \x1B[34m00000000eeeeeeee\x1B[0m\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadWriteStateGeneralRegsX64) { zx_thread_state_general_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.rax = 0xaaaa; buffer.rbx = 0xbbbb; buffer.rcx = 0xcccc; buffer.rdx = 0xdddd; buffer.rsi = 0x1234; buffer.rbp = 0x2345; buffer.rsp = 0x3456; buffer.r8 = 0x0808; buffer.r9 = 0x0909; buffer.r10 = 0x1010; buffer.r11 = 0x1111; buffer.r12 = 0x1212; buffer.r13 = 0x1313; buffer.r14 = 0x1414; buffer.r15 = 0x1515; buffer.rip = 0x1111; buffer.rflags = 0; buffer.fs_base = 0x100000000UL; buffer.gs_base = 0x200000000UL; THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_GENERAL_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_GENERAL_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m160\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_general_regs_x86_t\x1B[0m = {\n" " rax: \x1B[32muint64\x1B[0m = \x1B[34m000000000000aaaa\x1B[0m\n" " rbx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000bbbb\x1B[0m\n" " rcx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000cccc\x1B[0m\n" " rdx: \x1B[32muint64\x1B[0m = \x1B[34m000000000000dddd\x1B[0m\n" " rsi: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001234\x1B[0m\n" " rdi: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m\n" " rbp: \x1B[32muint64\x1B[0m = \x1B[34m0000000000002345\x1B[0m\n" " rsp: \x1B[32muint64\x1B[0m = \x1B[34m0000000000003456\x1B[0m\n" " r8: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000808\x1B[0m\n" " r9: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000909\x1B[0m\n" " r10: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001010\x1B[0m\n" " r11: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001111\x1B[0m\n" " r12: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001212\x1B[0m\n" " r13: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001313\x1B[0m\n" " r14: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001414\x1B[0m\n" " r15: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001515\x1B[0m\n" " rip: \x1B[32muint64\x1B[0m = \x1B[34m0000000000001111\x1B[0m\n" " rflags: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m\n" " fs_base: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m\n" " gs_base: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadWriteStateFpRegsX64) { zx_thread_state_fp_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.fcw = 0xcccc; buffer.fsw = 0xdddd; buffer.ftw = 0xee; buffer.fop = 0xffff; buffer.fip = 0x100000001UL; buffer.fdp = 0xd0000000dUL; constexpr uint64_t kLowIncrement = 0x100000001UL; constexpr uint64_t kHighIncrement = 0x100000000UL; uint64_t low = 0; uint64_t high = 0; for (size_t i = 0; i < sizeof(buffer.st) / sizeof(buffer.st[0]); ++i) { buffer.st[i].low = low; buffer.st[i].high = high; low += kLowIncrement; high += kHighIncrement; } THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_FP_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_FP_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m160\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_fp_regs_x86_t\x1B[0m = {\n" " fcw: \x1B[32muint16\x1B[0m = \x1B[34mcccc\x1B[0m\n" " fsw: \x1B[32muint16\x1B[0m = \x1B[34mdddd\x1B[0m\n" " ftw: \x1B[32muint8\x1B[0m = \x1B[34mee\x1B[0m\n" " fop: \x1B[32muint16\x1B[0m = \x1B[34mffff\x1B[0m\n" " fip: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m\n" " fdp: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m\n" " st: vector<\x1B[32mzx.uint128\x1B[0m> = [\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000000\x1B[0m }\n" " ]\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestArm, ZxThreadWriteStateVectorRegsAArch64) { zx_thread_state_vector_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); buffer.fpcr = 0x12345678U; buffer.fpsr = 0x87654321U; constexpr uint64_t kLowIncrement = 0x100000001UL; constexpr uint64_t kHighIncrement = 0x100000000UL; uint64_t low = 0; uint64_t high = 0; for (size_t i = 0; i < sizeof(buffer.v) / sizeof(buffer.v[0]); ++i) { buffer.v[i].low = low; buffer.v[i].high = high; low += kLowIncrement; high += kHighIncrement; } THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_VECTOR_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_VECTOR_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m520\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_vector_regs_aarch64_t\x1B[0m = {\n" " fpcr: \x1B[32muint32\x1B[0m = \x1B[34m12345678\x1B[0m\n" " fpsr: \x1B[32muint32\x1B[0m = \x1B[34m87654321\x1B[0m\n" " v: vector<\x1B[32mzx.uint128\x1B[0m> = [\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000008\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000009\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000a0000000a\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000a00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000b0000000b\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000b00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000c0000000c\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000c00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000d00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000e0000000e\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000e00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000000f0000000f\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000000f00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000010\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000011\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000012\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000013\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000014\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000015\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000016\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000017\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000018\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000019\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001a0000001a\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001a00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001b0000001b\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001b00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001c0000001c\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001c00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001d0000001d\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001d00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001e0000001e\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001e00000000\x1B[0m }\n" " { low: \x1B[32muint64\x1B[0m = \x1B[34m0000001f0000001f\x1B[0m, " "high: \x1B[32muint64\x1B[0m = \x1B[34m0000001f00000000\x1B[0m }\n" " ]\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadWriteStateVectorRegsX64) { zx_thread_state_vector_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.zmm) / sizeof(buffer.zmm[0]); ++i) { for (size_t j = 0; j < sizeof(buffer.zmm[0].v) / sizeof(buffer.zmm[0].v[0]); ++j) { buffer.zmm[i].v[j] = value; value += kIncrement; } } for (size_t i = 0; i < sizeof(buffer.opmask) / sizeof(buffer.opmask[0]); ++i) { buffer.opmask[i] = value; value += kIncrement; } buffer.mxcsr = 0x12345678; THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_VECTOR_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_VECTOR_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m2120\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_vector_regs_x86_t\x1B[0m = {\n" " zmm: array<\x1B[32mzx_thread_state_vector_regs_x86_zmm_t\x1B[0m> = [\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m, " "\x1B[34m0000000400000004\x1B[0m, \x1B[34m0000000500000005\x1B[0m\n" " \x1B[34m0000000600000006\x1B[0m, \x1B[34m0000000700000007\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000000800000008\x1B[0m, \x1B[34m0000000900000009\x1B[0m, " "\x1B[34m0000000a0000000a\x1B[0m, \x1B[34m0000000b0000000b\x1B[0m, " "\x1B[34m0000000c0000000c\x1B[0m, \x1B[34m0000000d0000000d\x1B[0m\n" " \x1B[34m0000000e0000000e\x1B[0m, \x1B[34m0000000f0000000f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000001000000010\x1B[0m, \x1B[34m0000001100000011\x1B[0m, " "\x1B[34m0000001200000012\x1B[0m, \x1B[34m0000001300000013\x1B[0m, " "\x1B[34m0000001400000014\x1B[0m, \x1B[34m0000001500000015\x1B[0m\n" " \x1B[34m0000001600000016\x1B[0m, \x1B[34m0000001700000017\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000001800000018\x1B[0m, \x1B[34m0000001900000019\x1B[0m, " "\x1B[34m0000001a0000001a\x1B[0m, \x1B[34m0000001b0000001b\x1B[0m, " "\x1B[34m0000001c0000001c\x1B[0m, \x1B[34m0000001d0000001d\x1B[0m\n" " \x1B[34m0000001e0000001e\x1B[0m, \x1B[34m0000001f0000001f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000002000000020\x1B[0m, \x1B[34m0000002100000021\x1B[0m, " "\x1B[34m0000002200000022\x1B[0m, \x1B[34m0000002300000023\x1B[0m, " "\x1B[34m0000002400000024\x1B[0m, \x1B[34m0000002500000025\x1B[0m\n" " \x1B[34m0000002600000026\x1B[0m, \x1B[34m0000002700000027\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000002800000028\x1B[0m, \x1B[34m0000002900000029\x1B[0m, " "\x1B[34m0000002a0000002a\x1B[0m, \x1B[34m0000002b0000002b\x1B[0m, " "\x1B[34m0000002c0000002c\x1B[0m, \x1B[34m0000002d0000002d\x1B[0m\n" " \x1B[34m0000002e0000002e\x1B[0m, \x1B[34m0000002f0000002f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000003000000030\x1B[0m, \x1B[34m0000003100000031\x1B[0m, " "\x1B[34m0000003200000032\x1B[0m, \x1B[34m0000003300000033\x1B[0m, " "\x1B[34m0000003400000034\x1B[0m, \x1B[34m0000003500000035\x1B[0m\n" " \x1B[34m0000003600000036\x1B[0m, \x1B[34m0000003700000037\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000003800000038\x1B[0m, \x1B[34m0000003900000039\x1B[0m, " "\x1B[34m0000003a0000003a\x1B[0m, \x1B[34m0000003b0000003b\x1B[0m, " "\x1B[34m0000003c0000003c\x1B[0m, \x1B[34m0000003d0000003d\x1B[0m\n" " \x1B[34m0000003e0000003e\x1B[0m, \x1B[34m0000003f0000003f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000004000000040\x1B[0m, \x1B[34m0000004100000041\x1B[0m, " "\x1B[34m0000004200000042\x1B[0m, \x1B[34m0000004300000043\x1B[0m, " "\x1B[34m0000004400000044\x1B[0m, \x1B[34m0000004500000045\x1B[0m\n" " \x1B[34m0000004600000046\x1B[0m, \x1B[34m0000004700000047\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000004800000048\x1B[0m, \x1B[34m0000004900000049\x1B[0m, " "\x1B[34m0000004a0000004a\x1B[0m, \x1B[34m0000004b0000004b\x1B[0m, " "\x1B[34m0000004c0000004c\x1B[0m, \x1B[34m0000004d0000004d\x1B[0m\n" " \x1B[34m0000004e0000004e\x1B[0m, \x1B[34m0000004f0000004f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000005000000050\x1B[0m, \x1B[34m0000005100000051\x1B[0m, " "\x1B[34m0000005200000052\x1B[0m, \x1B[34m0000005300000053\x1B[0m, " "\x1B[34m0000005400000054\x1B[0m, \x1B[34m0000005500000055\x1B[0m\n" " \x1B[34m0000005600000056\x1B[0m, \x1B[34m0000005700000057\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000005800000058\x1B[0m, \x1B[34m0000005900000059\x1B[0m, " "\x1B[34m0000005a0000005a\x1B[0m, \x1B[34m0000005b0000005b\x1B[0m, " "\x1B[34m0000005c0000005c\x1B[0m, \x1B[34m0000005d0000005d\x1B[0m\n" " \x1B[34m0000005e0000005e\x1B[0m, \x1B[34m0000005f0000005f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000006000000060\x1B[0m, \x1B[34m0000006100000061\x1B[0m, " "\x1B[34m0000006200000062\x1B[0m, \x1B[34m0000006300000063\x1B[0m, " "\x1B[34m0000006400000064\x1B[0m, \x1B[34m0000006500000065\x1B[0m\n" " \x1B[34m0000006600000066\x1B[0m, \x1B[34m0000006700000067\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000006800000068\x1B[0m, \x1B[34m0000006900000069\x1B[0m, " "\x1B[34m0000006a0000006a\x1B[0m, \x1B[34m0000006b0000006b\x1B[0m, " "\x1B[34m0000006c0000006c\x1B[0m, \x1B[34m0000006d0000006d\x1B[0m\n" " \x1B[34m0000006e0000006e\x1B[0m, \x1B[34m0000006f0000006f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000007000000070\x1B[0m, \x1B[34m0000007100000071\x1B[0m, " "\x1B[34m0000007200000072\x1B[0m, \x1B[34m0000007300000073\x1B[0m, " "\x1B[34m0000007400000074\x1B[0m, \x1B[34m0000007500000075\x1B[0m\n" " \x1B[34m0000007600000076\x1B[0m, \x1B[34m0000007700000077\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000007800000078\x1B[0m, \x1B[34m0000007900000079\x1B[0m, " "\x1B[34m0000007a0000007a\x1B[0m, \x1B[34m0000007b0000007b\x1B[0m, " "\x1B[34m0000007c0000007c\x1B[0m, \x1B[34m0000007d0000007d\x1B[0m\n" " \x1B[34m0000007e0000007e\x1B[0m, \x1B[34m0000007f0000007f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000008000000080\x1B[0m, \x1B[34m0000008100000081\x1B[0m, " "\x1B[34m0000008200000082\x1B[0m, \x1B[34m0000008300000083\x1B[0m, " "\x1B[34m0000008400000084\x1B[0m, \x1B[34m0000008500000085\x1B[0m\n" " \x1B[34m0000008600000086\x1B[0m, \x1B[34m0000008700000087\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000008800000088\x1B[0m, \x1B[34m0000008900000089\x1B[0m, " "\x1B[34m0000008a0000008a\x1B[0m, \x1B[34m0000008b0000008b\x1B[0m, " "\x1B[34m0000008c0000008c\x1B[0m, \x1B[34m0000008d0000008d\x1B[0m\n" " \x1B[34m0000008e0000008e\x1B[0m, \x1B[34m0000008f0000008f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000009000000090\x1B[0m, \x1B[34m0000009100000091\x1B[0m, " "\x1B[34m0000009200000092\x1B[0m, \x1B[34m0000009300000093\x1B[0m, " "\x1B[34m0000009400000094\x1B[0m, \x1B[34m0000009500000095\x1B[0m\n" " \x1B[34m0000009600000096\x1B[0m, \x1B[34m0000009700000097\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000009800000098\x1B[0m, \x1B[34m0000009900000099\x1B[0m, " "\x1B[34m0000009a0000009a\x1B[0m, \x1B[34m0000009b0000009b\x1B[0m, " "\x1B[34m0000009c0000009c\x1B[0m, \x1B[34m0000009d0000009d\x1B[0m\n" " \x1B[34m0000009e0000009e\x1B[0m, \x1B[34m0000009f0000009f\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000a0000000a0\x1B[0m, \x1B[34m000000a1000000a1\x1B[0m, " "\x1B[34m000000a2000000a2\x1B[0m, \x1B[34m000000a3000000a3\x1B[0m, " "\x1B[34m000000a4000000a4\x1B[0m, \x1B[34m000000a5000000a5\x1B[0m\n" " \x1B[34m000000a6000000a6\x1B[0m, \x1B[34m000000a7000000a7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000a8000000a8\x1B[0m, \x1B[34m000000a9000000a9\x1B[0m, " "\x1B[34m000000aa000000aa\x1B[0m, \x1B[34m000000ab000000ab\x1B[0m, " "\x1B[34m000000ac000000ac\x1B[0m, \x1B[34m000000ad000000ad\x1B[0m\n" " \x1B[34m000000ae000000ae\x1B[0m, \x1B[34m000000af000000af\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000b0000000b0\x1B[0m, \x1B[34m000000b1000000b1\x1B[0m, " "\x1B[34m000000b2000000b2\x1B[0m, \x1B[34m000000b3000000b3\x1B[0m, " "\x1B[34m000000b4000000b4\x1B[0m, \x1B[34m000000b5000000b5\x1B[0m\n" " \x1B[34m000000b6000000b6\x1B[0m, \x1B[34m000000b7000000b7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000b8000000b8\x1B[0m, \x1B[34m000000b9000000b9\x1B[0m, " "\x1B[34m000000ba000000ba\x1B[0m, \x1B[34m000000bb000000bb\x1B[0m, " "\x1B[34m000000bc000000bc\x1B[0m, \x1B[34m000000bd000000bd\x1B[0m\n" " \x1B[34m000000be000000be\x1B[0m, \x1B[34m000000bf000000bf\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000c0000000c0\x1B[0m, \x1B[34m000000c1000000c1\x1B[0m, " "\x1B[34m000000c2000000c2\x1B[0m, \x1B[34m000000c3000000c3\x1B[0m, " "\x1B[34m000000c4000000c4\x1B[0m, \x1B[34m000000c5000000c5\x1B[0m\n" " \x1B[34m000000c6000000c6\x1B[0m, \x1B[34m000000c7000000c7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000c8000000c8\x1B[0m, \x1B[34m000000c9000000c9\x1B[0m, " "\x1B[34m000000ca000000ca\x1B[0m, \x1B[34m000000cb000000cb\x1B[0m, " "\x1B[34m000000cc000000cc\x1B[0m, \x1B[34m000000cd000000cd\x1B[0m\n" " \x1B[34m000000ce000000ce\x1B[0m, \x1B[34m000000cf000000cf\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000d0000000d0\x1B[0m, \x1B[34m000000d1000000d1\x1B[0m, " "\x1B[34m000000d2000000d2\x1B[0m, \x1B[34m000000d3000000d3\x1B[0m, " "\x1B[34m000000d4000000d4\x1B[0m, \x1B[34m000000d5000000d5\x1B[0m\n" " \x1B[34m000000d6000000d6\x1B[0m, \x1B[34m000000d7000000d7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000d8000000d8\x1B[0m, \x1B[34m000000d9000000d9\x1B[0m, " "\x1B[34m000000da000000da\x1B[0m, \x1B[34m000000db000000db\x1B[0m, " "\x1B[34m000000dc000000dc\x1B[0m, \x1B[34m000000dd000000dd\x1B[0m\n" " \x1B[34m000000de000000de\x1B[0m, \x1B[34m000000df000000df\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000e0000000e0\x1B[0m, \x1B[34m000000e1000000e1\x1B[0m, " "\x1B[34m000000e2000000e2\x1B[0m, \x1B[34m000000e3000000e3\x1B[0m, " "\x1B[34m000000e4000000e4\x1B[0m, \x1B[34m000000e5000000e5\x1B[0m\n" " \x1B[34m000000e6000000e6\x1B[0m, \x1B[34m000000e7000000e7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000e8000000e8\x1B[0m, \x1B[34m000000e9000000e9\x1B[0m, " "\x1B[34m000000ea000000ea\x1B[0m, \x1B[34m000000eb000000eb\x1B[0m, " "\x1B[34m000000ec000000ec\x1B[0m, \x1B[34m000000ed000000ed\x1B[0m\n" " \x1B[34m000000ee000000ee\x1B[0m, \x1B[34m000000ef000000ef\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000f0000000f0\x1B[0m, \x1B[34m000000f1000000f1\x1B[0m, " "\x1B[34m000000f2000000f2\x1B[0m, \x1B[34m000000f3000000f3\x1B[0m, " "\x1B[34m000000f4000000f4\x1B[0m, \x1B[34m000000f5000000f5\x1B[0m\n" " \x1B[34m000000f6000000f6\x1B[0m, \x1B[34m000000f7000000f7\x1B[0m\n" " ]\n" " }\n" " {\n" " v: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m000000f8000000f8\x1B[0m, \x1B[34m000000f9000000f9\x1B[0m, " "\x1B[34m000000fa000000fa\x1B[0m, \x1B[34m000000fb000000fb\x1B[0m, " "\x1B[34m000000fc000000fc\x1B[0m, \x1B[34m000000fd000000fd\x1B[0m\n" " \x1B[34m000000fe000000fe\x1B[0m, \x1B[34m000000ff000000ff\x1B[0m\n" " ]\n" " }\n" " ]\n" " opmask: vector<\x1B[32muint64\x1B[0m> = [\n" " \x1B[34m0000010000000100\x1B[0m, \x1B[34m0000010100000101\x1B[0m, " "\x1B[34m0000010200000102\x1B[0m, \x1B[34m0000010300000103\x1B[0m, " "\x1B[34m0000010400000104\x1B[0m, \x1B[34m0000010500000105\x1B[0m, " "\x1B[34m0000010600000106\x1B[0m\n" " \x1B[34m0000010700000107\x1B[0m\n" " ]\n" " mxcsr: \x1B[32muint32\x1B[0m = \x1B[34m12345678\x1B[0m\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestArm, ZxThreadWriteStateDebugRegsAArch64) { zx_thread_state_debug_regs_aarch64_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint32_t kCrIncrement = 0x00010001U; constexpr uint64_t kVrIncrement = 0x100000001UL; uint32_t cr = 0; uint64_t vr = 0; for (size_t i = 0; i < sizeof(buffer.hw_bps) / sizeof(buffer.hw_bps[0]); ++i) { buffer.hw_bps[i].dbgbcr = cr; buffer.hw_bps[i].dbgbvr = vr; cr += kCrIncrement; vr += kVrIncrement; } buffer.hw_bps_count = 3; for (size_t i = 0; i < sizeof(buffer.hw_wps) / sizeof(buffer.hw_wps[0]); ++i) { buffer.hw_wps[i].dbgwcr = cr; buffer.hw_wps[i].dbgwvr = vr; cr += kCrIncrement; vr += kVrIncrement; } buffer.hw_wps_count = 2; buffer.esr = 0xeeeeffff; THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_DEBUG_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_DEBUG_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m528\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_debug_regs_aarch64_t\x1B[0m = {\n" " hw_bps: array<\x1B[32mzx_thread_state_debug_regs_aarch64_bp_t\x1B[0m> = [\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00000000\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000000000000\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00010001\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000100000001\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00020002\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000200000002\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00030003\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000300000003\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00040004\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000400000004\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00050005\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000500000005\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00060006\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000600000006\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00070007\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000700000007\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00080008\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000800000008\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m00090009\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000900000009\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000a000a\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000a0000000a\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000b000b\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000b0000000b\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000c000c\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000c0000000c\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000d000d\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000d0000000d\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000e000e\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000e0000000e\x1B[0m }\n" " { dbgbcr: \x1B[32muint32\x1B[0m = \x1B[34m000f000f\x1B[0m, " "dbgbvr: \x1B[32muint64\x1B[0m = \x1B[34m0000000f0000000f\x1B[0m }\n" " ]\n" " hw_bps_count: \x1B[32muint8\x1B[0m = \x1B[34m03\x1B[0m\n" " hw_wps: array<\x1B[32mzx_thread_state_debug_regs_aarch64_wp_t\x1B[0m> = [\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00100010\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001000000010\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00110011\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001100000011\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00120012\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001200000012\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00130013\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001300000013\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00140014\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001400000014\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00150015\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001500000015\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00160016\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001600000016\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00170017\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001700000017\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00180018\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001800000018\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m00190019\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001900000019\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001a001a\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001a0000001a\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001b001b\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001b0000001b\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001c001c\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001c0000001c\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001d001d\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001d0000001d\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001e001e\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001e0000001e\x1B[0m }\n" " { dbgwcr: \x1B[32muint32\x1B[0m = \x1B[34m001f001f\x1B[0m, " "dbgwvr: \x1B[32muint64\x1B[0m = \x1B[34m0000001f0000001f\x1B[0m }\n" " ]\n" " hw_wps_count: \x1B[32muint8\x1B[0m = \x1B[34m02\x1B[0m\n" " esr: \x1B[32muint32\x1B[0m = \x1B[34meeeeffff\x1B[0m\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } TEST_F(InterceptionWorkflowTestX64, ZxThreadWriteStateDebugRegsX64) { zx_thread_state_debug_regs_x86_t buffer; memset(&buffer, 0, sizeof(buffer)); constexpr uint64_t kIncrement = 0x100000001UL; uint64_t value = 0; for (size_t i = 0; i < sizeof(buffer.dr) / sizeof(buffer.dr[0]); ++i) { buffer.dr[i] = value; value += kIncrement; } buffer.dr6 = 0x66666666; buffer.dr7 = 0x77777777; THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT( ZX_OK, ZX_THREAD_STATE_DEBUG_REGS, buffer, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_DEBUG_REGS\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m48\x1B[0m)\n" " regs: \x1B[32mzx_thread_state_debug_regs_x86_t\x1B[0m = {\n" " dr: vector<\x1B[32muint64\x1B[0m> = [ " "\x1B[34m0000000000000000\x1B[0m, \x1B[34m0000000100000001\x1B[0m, " "\x1B[34m0000000200000002\x1B[0m, \x1B[34m0000000300000003\x1B[0m ]\n" " dr6: \x1B[32muint64\x1B[0m = \x1B[34m0000000066666666\x1B[0m\n" " dr7: \x1B[32muint64\x1B[0m = \x1B[34m0000000077777777\x1B[0m\n" " }\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n"); } #define THREAD_WRITE_STATE_SINGLE_STEP_DISPLAY_TEST(name, errno, value, expected) \ TEST_F(InterceptionWorkflowTestX64, name) { \ uint32_t single_step = value; \ THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT(errno, ZX_THREAD_STATE_SINGLE_STEP, single_step, \ expected); \ } \ TEST_F(InterceptionWorkflowTestArm, name) { \ uint32_t single_step = value; \ THREAD_WRITE_STATE_DISPLAY_TEST_CONTENT(errno, ZX_THREAD_STATE_SINGLE_STEP, single_step, \ expected); \ } THREAD_WRITE_STATE_SINGLE_STEP_DISPLAY_TEST( ZxThreadWriteStateSingleStep0, ZX_OK, 0, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_SINGLE_STEP\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m4\x1B[0m, " "single_step: \x1B[32muint32\x1B[0m = \x1B[34m0\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n") THREAD_WRITE_STATE_SINGLE_STEP_DISPLAY_TEST( ZxThreadWriteStateSingleStep1, ZX_OK, 1, "\n" "\x1B[32m0.000000\x1B[0m " "test_3141 \x1B[31m3141\x1B[0m:\x1B[31m8764\x1B[0m " "zx_thread_write_state(" "handle: \x1B[32mhandle\x1B[0m = \x1B[31mcefa1db0\x1B[0m, " "kind: \x1B[32mzx.thread_state_topic\x1B[0m = \x1B[34mZX_THREAD_STATE_SINGLE_STEP\x1B[0m, " "buffer_size: \x1B[32msize\x1B[0m = \x1B[34m4\x1B[0m, " "single_step: \x1B[32muint32\x1B[0m = \x1B[34m1\x1B[0m)\n" "\x1B[32m0.000000\x1B[0m " " -> \x1B[32mZX_OK\x1B[0m\n") } // namespace fidlcat
// Distributed under the MIT License. // See LICENSE.txt for details. #include "PointwiseFunctions/AnalyticData/GrMhd/RiemannProblem.hpp" #include <pup.h> #include "DataStructures/DataVector.hpp" // IWYU pragma: keep #include "DataStructures/Tensor/EagerMath/DotProduct.hpp" #include "DataStructures/Tensor/Tensor.hpp" // IWYU pragma: keep #include "PointwiseFunctions/Hydro/LorentzFactor.hpp" #include "PointwiseFunctions/Hydro/Tags.hpp" #include "Utilities/ContainerHelpers.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/MakeWithValue.hpp" #include "Utilities/Math.hpp" // IWYU pragma: keep namespace grmhd::AnalyticData { RiemannProblem::RiemannProblem( const double adiabatic_index, const double left_rest_mass_density, const double right_rest_mass_density, const double left_pressure, const double right_pressure, const std::array<double, 3>& left_spatial_velocity, const std::array<double, 3>& right_spatial_velocity, const std::array<double, 3>& left_magnetic_field, const std::array<double, 3>& right_magnetic_field, const double lapse, const double shift) noexcept : equation_of_state_(adiabatic_index), adiabatic_index_(adiabatic_index), left_rest_mass_density_(left_rest_mass_density), right_rest_mass_density_(right_rest_mass_density), left_pressure_(left_pressure), right_pressure_(right_pressure), left_spatial_velocity_(left_spatial_velocity), right_spatial_velocity_(right_spatial_velocity), left_magnetic_field_(left_magnetic_field), right_magnetic_field_(right_magnetic_field), lapse_(lapse), shift_(shift) {} RiemannProblem::RiemannProblem(CkMigrateMessage* /*unused*/) noexcept {} void RiemannProblem::pup(PUP::er& p) noexcept { p | equation_of_state_; p | background_spacetime_; p | adiabatic_index_; p | left_rest_mass_density_; p | right_rest_mass_density_; p | left_pressure_; p | right_pressure_; p | left_spatial_velocity_; p | right_spatial_velocity_; p | left_magnetic_field_; p | right_magnetic_field_; p | lapse_; p | shift_; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::RestMassDensity<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::RestMassDensity<DataType>> /*meta*/) const noexcept { auto mass_density = make_with_value<Scalar<DataType>>(x, 0.0); for (size_t i = 0; i < get_size(get<0>(x)); ++i) { if (get_element(get<0>(x), i) <= discontinuity_location_) { get_element(get(mass_density), i) = left_rest_mass_density_; } else { get_element(get(mass_density), i) = right_rest_mass_density_; } } return mass_density; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::SpatialVelocity<DataType, 3>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::SpatialVelocity<DataType, 3>> /*meta*/) const noexcept { auto spatial_velocity = make_with_value<tnsr::I<DataType, 3, Frame::Inertial>>(x, 0.0); for (size_t i = 0; i < get_size(get<0>(x)); ++i) { if (get_element(get<0>(x), i) <= discontinuity_location_) { get_element(get<0>(spatial_velocity), i) = left_spatial_velocity_[0]; get_element(get<1>(spatial_velocity), i) = left_spatial_velocity_[1]; get_element(get<2>(spatial_velocity), i) = left_spatial_velocity_[2]; } else { get_element(get<0>(spatial_velocity), i) = right_spatial_velocity_[0]; get_element(get<1>(spatial_velocity), i) = right_spatial_velocity_[1]; get_element(get<2>(spatial_velocity), i) = right_spatial_velocity_[2]; } } return spatial_velocity; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::SpecificInternalEnergy<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::SpecificInternalEnergy<DataType>> /*meta*/) const noexcept { return equation_of_state_.specific_internal_energy_from_density_and_pressure( get<hydro::Tags::RestMassDensity<DataType>>( variables(x, tmpl::list<hydro::Tags::RestMassDensity<DataType>>{})), get<hydro::Tags::Pressure<DataType>>( variables(x, tmpl::list<hydro::Tags::Pressure<DataType>>{}))); } template <typename DataType> tuples::TaggedTuple<hydro::Tags::Pressure<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::Pressure<DataType>> /*meta*/) const noexcept { auto pressure = make_with_value<Scalar<DataType>>(x, 0.0); for (size_t i = 0; i < get_size(get<0>(x)); ++i) { if (get_element(get<0>(x), i) <= discontinuity_location_) { get_element(get(pressure), i) = left_pressure_; } else { get_element(get(pressure), i) = right_pressure_; } } return pressure; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::MagneticField<DataType, 3>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::MagneticField<DataType, 3>> /*meta*/) const noexcept { auto magnetic_field = make_with_value<tnsr::I<DataType, 3, Frame::Inertial>>(x, 0.0); for (size_t i = 0; i < get_size(get<0>(x)); ++i) { if (get_element(get<0>(x), i) <= discontinuity_location_) { get_element(get<0>(magnetic_field), i) = left_magnetic_field_[0]; get_element(get<1>(magnetic_field), i) = left_magnetic_field_[1]; get_element(get<2>(magnetic_field), i) = left_magnetic_field_[2]; } else { get_element(get<0>(magnetic_field), i) = right_magnetic_field_[0]; get_element(get<1>(magnetic_field), i) = right_magnetic_field_[1]; get_element(get<2>(magnetic_field), i) = right_magnetic_field_[2]; } } return magnetic_field; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::DivergenceCleaningField<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::DivergenceCleaningField<DataType>> /*meta*/) const noexcept { return {make_with_value<Scalar<DataType>>(x, 0.0)}; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::LorentzFactor<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::LorentzFactor<DataType>> /*meta*/) const noexcept { const auto spatial_velocity = get<hydro::Tags::SpatialVelocity<DataType, 3>>( variables(x, tmpl::list<hydro::Tags::SpatialVelocity<DataType, 3>>{})); return { hydro::lorentz_factor(dot_product(spatial_velocity, spatial_velocity))}; } template <typename DataType> tuples::TaggedTuple<hydro::Tags::SpecificEnthalpy<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<hydro::Tags::SpecificEnthalpy<DataType>> /*meta*/) const noexcept { return equation_of_state_.specific_enthalpy_from_density_and_energy( get<hydro::Tags::RestMassDensity<DataType>>( variables(x, tmpl::list<hydro::Tags::RestMassDensity<DataType>>{})), get<hydro::Tags::SpecificInternalEnergy<DataType>>(variables( x, tmpl::list<hydro::Tags::SpecificInternalEnergy<DataType>>{}))); } template <typename DataType> tuples::TaggedTuple<gr::Tags::Lapse<DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<gr::Tags::Lapse<DataType>> /*meta*/) const noexcept { return {make_with_value<Scalar<DataType>>(x, lapse_)}; } template <typename DataType> tuples::TaggedTuple<gr::Tags::Shift<3, Frame::Inertial, DataType>> RiemannProblem::variables( const tnsr::I<DataType, 3>& x, tmpl::list<gr::Tags::Shift<3, Frame::Inertial, DataType>> /*meta*/) const noexcept { auto shift = make_with_value<tnsr::I<DataType, 3, Frame::Inertial>>(x, 0.0); get<0>(shift) = shift_; return {std::move(shift)}; } bool operator==(const RiemannProblem& lhs, const RiemannProblem& rhs) noexcept { return lhs.adiabatic_index_ == rhs.adiabatic_index_ and lhs.left_rest_mass_density_ == rhs.left_rest_mass_density_ and lhs.right_rest_mass_density_ == rhs.right_rest_mass_density_ and lhs.left_pressure_ == rhs.left_pressure_ and lhs.right_pressure_ == rhs.right_pressure_ and lhs.left_spatial_velocity_ == rhs.left_spatial_velocity_ and lhs.right_spatial_velocity_ == rhs.right_spatial_velocity_ and lhs.left_magnetic_field_ == rhs.left_magnetic_field_ and lhs.right_magnetic_field_ == rhs.right_magnetic_field_ and lhs.lapse_ == rhs.lapse_ and lhs.shift_ == rhs.shift_; } bool operator!=(const RiemannProblem& lhs, const RiemannProblem& rhs) noexcept { return not(lhs == rhs); } #define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data) #define TAG(data) BOOST_PP_TUPLE_ELEM(1, data) #define INSTANTIATE_SCALARS(_, data) \ template tuples::TaggedTuple<TAG(data) < DTYPE(data)> > \ RiemannProblem::variables( \ const tnsr::I<DTYPE(data), 3>& x, \ tmpl::list<TAG(data) < DTYPE(data)> > /*meta*/) const noexcept; GENERATE_INSTANTIATIONS(INSTANTIATE_SCALARS, (double, DataVector), (hydro::Tags::RestMassDensity, hydro::Tags::SpecificInternalEnergy, hydro::Tags::Pressure, hydro::Tags::DivergenceCleaningField, hydro::Tags::LorentzFactor, hydro::Tags::SpecificEnthalpy, gr::Tags::Lapse)) #define INSTANTIATE_VECTORS(_, data) \ template tuples::TaggedTuple<TAG(data) < DTYPE(data), 3> > \ RiemannProblem::variables( \ const tnsr::I<DTYPE(data), 3>& x, \ tmpl::list<TAG(data) < DTYPE(data), 3> > /*meta*/) const noexcept; GENERATE_INSTANTIATIONS(INSTANTIATE_VECTORS, (double, DataVector), (hydro::Tags::SpatialVelocity, hydro::Tags::MagneticField)) #undef DTYPE #undef TAG #undef INSTANTIATE_SCALARS #undef INSTANTIATE_VECTORS // The GR tags have a different template parameter ordering than the rest of the // code, so need to instantiate separately. template tuples::TaggedTuple<gr::Tags::Shift<3, Frame::Inertial, double>> RiemannProblem::variables( const tnsr::I<double, 3>& x, tmpl::list<gr::Tags::Shift<3, Frame::Inertial, double>> /*meta*/) const noexcept; template tuples::TaggedTuple<gr::Tags::Shift<3, Frame::Inertial, DataVector>> RiemannProblem::variables( const tnsr::I<DataVector, 3>& x, tmpl::list<gr::Tags::Shift<3, Frame::Inertial, DataVector>> /*meta*/) const noexcept; } // namespace grmhd::AnalyticData
/* Copyright Soramitsu Co., Ltd. 2016 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. */ #ifndef IROHA_ACCOUNT_HPP #define IROHA_ACCOUNT_HPP #include <common/types.hpp> #include <string> namespace iroha { namespace model { /** * Account Model */ struct Account { struct Permissions { Permissions() { issue_assets = false; create_assets = false; create_accounts = false; create_domains = false; read_all_accounts = false; add_signatory = false; remove_signatory = false; set_permissions = false; set_quorum = false; can_transfer = false; } /** * Can account add assets to own account; * Dangerous operation - require high number of quorum; */ bool issue_assets; /** * Can account create new type of assets; * Dangerous operation - require high number of quorum; */ bool create_assets; /** * Can create new accounts */ bool create_accounts; /** * Can create new domains */ bool create_domains; /** * Can account read private information of other accounts; * Auditor's permission */ bool read_all_accounts; /** * Can add signatory to all other accounts */ bool add_signatory; /** * Can add signatory to all other accounts */ bool remove_signatory; /** * Set permissions to all other accounts * Administrator's account permission */ bool set_permissions; /** * Permission to set quorum * Administrator's account permission */ bool set_quorum; /** * Can account provide unlimited transfers to other accounts; * User's account permission */ bool can_transfer; bool operator==(const Permissions &rhs) const; bool operator!=(const Permissions &rhs) const; }; /** * User name is used as unique identifier of an account */ std::string account_id; /** * Account has only one domain. * Name of the domain of a account */ std::string domain_name; /** * Account permissions */ Permissions permissions; /** * Minimum quorum of signatures need for transactions */ uint32_t quorum; }; } } #endif // IROHA_ACCOUNT_HPP
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_processing/audio_buffer.h" #include "webrtc/common_audio/include/audio_util.h" #include "webrtc/common_audio/resampler/push_sinc_resampler.h" #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h" #include "webrtc/common_audio/channel_buffer.h" #include "webrtc/modules/audio_processing/common.h" namespace webrtc { namespace { const size_t kSamplesPer16kHzChannel = 160; const size_t kSamplesPer32kHzChannel = 320; const size_t kSamplesPer48kHzChannel = 480; int KeyboardChannelIndex(const StreamConfig& stream_config) { if (!stream_config.has_keyboard()) { assert(false); return 0; } return stream_config.num_channels(); } size_t NumBandsFromSamplesPerChannel(size_t num_frames) { size_t num_bands = 1; if (num_frames == kSamplesPer32kHzChannel || num_frames == kSamplesPer48kHzChannel) { num_bands = rtc::CheckedDivExact(num_frames, kSamplesPer16kHzChannel); } return num_bands; } } // namespace AudioBuffer::AudioBuffer(size_t input_num_frames, size_t num_input_channels, size_t process_num_frames, size_t num_process_channels, size_t output_num_frames) : input_num_frames_(input_num_frames), num_input_channels_(num_input_channels), proc_num_frames_(process_num_frames), num_proc_channels_(num_process_channels), output_num_frames_(output_num_frames), num_channels_(num_process_channels), num_bands_(NumBandsFromSamplesPerChannel(proc_num_frames_)), num_split_frames_(rtc::CheckedDivExact(proc_num_frames_, num_bands_)), mixed_low_pass_valid_(false), reference_copied_(false), activity_(AudioFrame::kVadUnknown), keyboard_data_(NULL), data_(new IFChannelBuffer(proc_num_frames_, num_proc_channels_)) { assert(input_num_frames_ > 0); assert(proc_num_frames_ > 0); assert(output_num_frames_ > 0); assert(num_input_channels_ > 0); assert(num_proc_channels_ > 0 && num_proc_channels_ <= num_input_channels_); if (input_num_frames_ != proc_num_frames_ || output_num_frames_ != proc_num_frames_) { // Create an intermediate buffer for resampling. process_buffer_.reset(new ChannelBuffer<float>(proc_num_frames_, num_proc_channels_)); if (input_num_frames_ != proc_num_frames_) { for (size_t i = 0; i < num_proc_channels_; ++i) { input_resamplers_.push_back( new PushSincResampler(input_num_frames_, proc_num_frames_)); } } if (output_num_frames_ != proc_num_frames_) { for (size_t i = 0; i < num_proc_channels_; ++i) { output_resamplers_.push_back( new PushSincResampler(proc_num_frames_, output_num_frames_)); } } } if (num_bands_ > 1) { split_data_.reset(new IFChannelBuffer(proc_num_frames_, num_proc_channels_, num_bands_)); splitting_filter_.reset(new SplittingFilter(num_proc_channels_, num_bands_, proc_num_frames_)); } } AudioBuffer::~AudioBuffer() {} void AudioBuffer::CopyFrom(const float* const* data, const StreamConfig& stream_config) { assert(stream_config.num_frames() == input_num_frames_); assert(stream_config.num_channels() == num_input_channels_); InitForNewData(); // Initialized lazily because there's a different condition in // DeinterleaveFrom. const bool need_to_downmix = num_input_channels_ > 1 && num_proc_channels_ == 1; if (need_to_downmix && !input_buffer_) { input_buffer_.reset( new IFChannelBuffer(input_num_frames_, num_proc_channels_)); } if (stream_config.has_keyboard()) { keyboard_data_ = data[KeyboardChannelIndex(stream_config)]; } // Downmix. const float* const* data_ptr = data; if (need_to_downmix) { DownmixToMono<float, float>(data, input_num_frames_, num_input_channels_, input_buffer_->fbuf()->channels()[0]); data_ptr = input_buffer_->fbuf_const()->channels(); } // Resample. if (input_num_frames_ != proc_num_frames_) { for (size_t i = 0; i < num_proc_channels_; ++i) { input_resamplers_[i]->Resample(data_ptr[i], input_num_frames_, process_buffer_->channels()[i], proc_num_frames_); } data_ptr = process_buffer_->channels(); } // Convert to the S16 range. for (size_t i = 0; i < num_proc_channels_; ++i) { FloatToFloatS16(data_ptr[i], proc_num_frames_, data_->fbuf()->channels()[i]); } } void AudioBuffer::CopyTo(const StreamConfig& stream_config, float* const* data) { assert(stream_config.num_frames() == output_num_frames_); assert(stream_config.num_channels() == num_channels_ || num_channels_ == 1); // Convert to the float range. float* const* data_ptr = data; if (output_num_frames_ != proc_num_frames_) { // Convert to an intermediate buffer for subsequent resampling. data_ptr = process_buffer_->channels(); } for (size_t i = 0; i < num_channels_; ++i) { FloatS16ToFloat(data_->fbuf()->channels()[i], proc_num_frames_, data_ptr[i]); } // Resample. if (output_num_frames_ != proc_num_frames_) { for (size_t i = 0; i < num_channels_; ++i) { output_resamplers_[i]->Resample(data_ptr[i], proc_num_frames_, data[i], output_num_frames_); } } // Upmix. for (size_t i = num_channels_; i < stream_config.num_channels(); ++i) { memcpy(data[i], data[0], output_num_frames_ * sizeof(**data)); } } void AudioBuffer::InitForNewData() { keyboard_data_ = NULL; mixed_low_pass_valid_ = false; reference_copied_ = false; activity_ = AudioFrame::kVadUnknown; num_channels_ = num_proc_channels_; } const int16_t* const* AudioBuffer::channels_const() const { return data_->ibuf_const()->channels(); } int16_t* const* AudioBuffer::channels() { mixed_low_pass_valid_ = false; return data_->ibuf()->channels(); } const int16_t* const* AudioBuffer::split_bands_const(size_t channel) const { return split_data_.get() ? split_data_->ibuf_const()->bands(channel) : data_->ibuf_const()->bands(channel); } int16_t* const* AudioBuffer::split_bands(size_t channel) { mixed_low_pass_valid_ = false; return split_data_.get() ? split_data_->ibuf()->bands(channel) : data_->ibuf()->bands(channel); } const int16_t* const* AudioBuffer::split_channels_const(Band band) const { if (split_data_.get()) { return split_data_->ibuf_const()->channels(band); } else { return band == kBand0To8kHz ? data_->ibuf_const()->channels() : nullptr; } } int16_t* const* AudioBuffer::split_channels(Band band) { mixed_low_pass_valid_ = false; if (split_data_.get()) { return split_data_->ibuf()->channels(band); } else { return band == kBand0To8kHz ? data_->ibuf()->channels() : nullptr; } } ChannelBuffer<int16_t>* AudioBuffer::data() { mixed_low_pass_valid_ = false; return data_->ibuf(); } const ChannelBuffer<int16_t>* AudioBuffer::data() const { return data_->ibuf_const(); } ChannelBuffer<int16_t>* AudioBuffer::split_data() { mixed_low_pass_valid_ = false; return split_data_.get() ? split_data_->ibuf() : data_->ibuf(); } const ChannelBuffer<int16_t>* AudioBuffer::split_data() const { return split_data_.get() ? split_data_->ibuf_const() : data_->ibuf_const(); } const float* const* AudioBuffer::channels_const_f() const { return data_->fbuf_const()->channels(); } float* const* AudioBuffer::channels_f() { mixed_low_pass_valid_ = false; return data_->fbuf()->channels(); } const float* const* AudioBuffer::split_bands_const_f(size_t channel) const { return split_data_.get() ? split_data_->fbuf_const()->bands(channel) : data_->fbuf_const()->bands(channel); } float* const* AudioBuffer::split_bands_f(size_t channel) { mixed_low_pass_valid_ = false; return split_data_.get() ? split_data_->fbuf()->bands(channel) : data_->fbuf()->bands(channel); } const float* const* AudioBuffer::split_channels_const_f(Band band) const { if (split_data_.get()) { return split_data_->fbuf_const()->channels(band); } else { return band == kBand0To8kHz ? data_->fbuf_const()->channels() : nullptr; } } float* const* AudioBuffer::split_channels_f(Band band) { mixed_low_pass_valid_ = false; if (split_data_.get()) { return split_data_->fbuf()->channels(band); } else { return band == kBand0To8kHz ? data_->fbuf()->channels() : nullptr; } } ChannelBuffer<float>* AudioBuffer::data_f() { mixed_low_pass_valid_ = false; return data_->fbuf(); } const ChannelBuffer<float>* AudioBuffer::data_f() const { return data_->fbuf_const(); } ChannelBuffer<float>* AudioBuffer::split_data_f() { mixed_low_pass_valid_ = false; return split_data_.get() ? split_data_->fbuf() : data_->fbuf(); } const ChannelBuffer<float>* AudioBuffer::split_data_f() const { return split_data_.get() ? split_data_->fbuf_const() : data_->fbuf_const(); } const int16_t* AudioBuffer::mixed_low_pass_data() { if (num_proc_channels_ == 1) { return split_bands_const(0)[kBand0To8kHz]; } if (!mixed_low_pass_valid_) { if (!mixed_low_pass_channels_.get()) { mixed_low_pass_channels_.reset( new ChannelBuffer<int16_t>(num_split_frames_, 1)); } DownmixToMono<int16_t, int32_t>(split_channels_const(kBand0To8kHz), num_split_frames_, num_channels_, mixed_low_pass_channels_->channels()[0]); mixed_low_pass_valid_ = true; } return mixed_low_pass_channels_->channels()[0]; } const int16_t* AudioBuffer::low_pass_reference(int channel) const { if (!reference_copied_) { return NULL; } return low_pass_reference_channels_->channels()[channel]; } const float* AudioBuffer::keyboard_data() const { return keyboard_data_; } void AudioBuffer::set_activity(AudioFrame::VADActivity activity) { activity_ = activity; } AudioFrame::VADActivity AudioBuffer::activity() const { return activity_; } size_t AudioBuffer::num_channels() const { return num_channels_; } void AudioBuffer::set_num_channels(size_t num_channels) { num_channels_ = num_channels; } size_t AudioBuffer::num_frames() const { return proc_num_frames_; } size_t AudioBuffer::num_frames_per_band() const { return num_split_frames_; } size_t AudioBuffer::num_keyboard_frames() const { // We don't resample the keyboard channel. return input_num_frames_; } size_t AudioBuffer::num_bands() const { return num_bands_; } // The resampler is only for supporting 48kHz to 16kHz in the reverse stream. void AudioBuffer::DeinterleaveFrom(AudioFrame* frame) { assert(frame->num_channels_ == num_input_channels_); assert(frame->samples_per_channel_ == input_num_frames_); InitForNewData(); // Initialized lazily because there's a different condition in CopyFrom. if ((input_num_frames_ != proc_num_frames_) && !input_buffer_) { input_buffer_.reset( new IFChannelBuffer(input_num_frames_, num_proc_channels_)); } activity_ = frame->vad_activity_; int16_t* const* deinterleaved; if (input_num_frames_ == proc_num_frames_) { deinterleaved = data_->ibuf()->channels(); } else { deinterleaved = input_buffer_->ibuf()->channels(); } if (num_proc_channels_ == 1) { // Downmix and deinterleave simultaneously. DownmixInterleavedToMono(frame->data_, input_num_frames_, num_input_channels_, deinterleaved[0]); } else { assert(num_proc_channels_ == num_input_channels_); Deinterleave(frame->data_, input_num_frames_, num_proc_channels_, deinterleaved); } // Resample. if (input_num_frames_ != proc_num_frames_) { for (size_t i = 0; i < num_proc_channels_; ++i) { input_resamplers_[i]->Resample(input_buffer_->fbuf_const()->channels()[i], input_num_frames_, data_->fbuf()->channels()[i], proc_num_frames_); } } } void AudioBuffer::InterleaveTo(AudioFrame* frame, bool data_changed) { frame->vad_activity_ = activity_; if (!data_changed) { return; } assert(frame->num_channels_ == num_channels_ || num_channels_ == 1); assert(frame->samples_per_channel_ == output_num_frames_); // Resample if necessary. IFChannelBuffer* data_ptr = data_.get(); if (proc_num_frames_ != output_num_frames_) { if (!output_buffer_) { output_buffer_.reset( new IFChannelBuffer(output_num_frames_, num_channels_)); } for (size_t i = 0; i < num_channels_; ++i) { output_resamplers_[i]->Resample( data_->fbuf()->channels()[i], proc_num_frames_, output_buffer_->fbuf()->channels()[i], output_num_frames_); } data_ptr = output_buffer_.get(); } if (frame->num_channels_ == num_channels_) { Interleave(data_ptr->ibuf()->channels(), proc_num_frames_, num_channels_, frame->data_); } else { UpmixMonoToInterleaved(data_ptr->ibuf()->channels()[0], proc_num_frames_, frame->num_channels_, frame->data_); } } void AudioBuffer::CopyLowPassToReference() { reference_copied_ = true; if (!low_pass_reference_channels_.get() || low_pass_reference_channels_->num_channels() != num_channels_) { low_pass_reference_channels_.reset( new ChannelBuffer<int16_t>(num_split_frames_, num_proc_channels_)); } for (size_t i = 0; i < num_proc_channels_; i++) { memcpy(low_pass_reference_channels_->channels()[i], split_bands_const(i)[kBand0To8kHz], low_pass_reference_channels_->num_frames_per_band() * sizeof(split_bands_const(i)[kBand0To8kHz][0])); } } void AudioBuffer::SplitIntoFrequencyBands() { splitting_filter_->Analysis(data_.get(), split_data_.get()); } void AudioBuffer::MergeFrequencyBands() { splitting_filter_->Synthesis(split_data_.get(), data_.get()); } } // namespace webrtc
/* * This is part of my wrapper-class to create * a MD5 Hash from a string and a file. * * This code is completly free, you * can copy it, modify it, or do * what ever you want with it. * * Feb. 2005 * Benjamin Grüdelbach */ /* * Changed unsigned long int types into uint32_t to make this work on 64bit systems. * Sep. 5. 2009 * Petr Mrázek */ #if defined(_MSC_VER) && _MSC_VER >= 1400 #define _CRT_SECURE_NO_WARNINGS #endif //---------------------------------------------------------------------- //basic includes #include <fstream> #include <iostream> #include <errno.h> #include <string.h> //my includes #include "md5wrapper.h" #include "md5.h" //---------privates-------------------------- /* * internal hash function, calling * the basic methods from md5.h */ std::string md5wrapper::hashit(std::string text) { MD5Context ctx; //init md5 MD5Init(&ctx); //update with our string MD5Update(&ctx, (unsigned char*)text.c_str(), text.length()); //create the hash unsigned char buff[16] = ""; MD5Final((unsigned char*)buff,&ctx); //converte the hash to a string and return it return convToString(buff); } /* * converts the numeric hash to * a valid std::string. * (based on Jim Howard's code; * http://www.codeproject.com/cpp/cmd5.asp) */ std::string md5wrapper::convToString(unsigned char *bytes) { char asciihash[33]; int p = 0; for(int i=0; i<16; i++) { ::sprintf(&asciihash[p],"%02x",bytes[i]); p += 2; } asciihash[32] = '\0'; return std::string(asciihash); } //---------publics-------------------------- //constructor md5wrapper::md5wrapper() { } //destructor md5wrapper::~md5wrapper() { } /* * creates a MD5 hash from * "text" and returns it as * string */ std::string md5wrapper::getHashFromString(std::string text) { return this->hashit(text); } /* * creates a MD5 hash from * a file specified in "filename" and * returns it as string * (based on Ronald L. Rivest's code * from RFC1321 "The MD5 Message-Digest Algorithm") */ std::string md5wrapper::getHashFromFile(std::string filename, uint32_t & length, char * first_kb) { FILE *file; MD5Context context; int len; int saved = 0; unsigned char buffer[1024], digest[16]; //open file if ((file = fopen (filename.c_str(), "rb")) == NULL) { return "file unreadable."; } length = 0; //init md5 MD5Init (&context); //read the filecontent while (1) { errno = 0; len = fread (buffer, 1, 1024, file); if(saved < 1024 && first_kb) { memmove(first_kb + saved, buffer, std::min (len, 1024 - saved)); saved += len; } length += len; if(len != 1024) { int err = ferror(file); //FIXME: check errno here. if(err) { fclose(file); return strerror(err); } if(feof(file)) { MD5Update (&context, buffer, len); break; } } MD5Update (&context, buffer, len); } /* generate hash, close the file and return the hash as std::string */ MD5Final (digest, &context); fclose (file); return convToString(digest); } /* * EOF */